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 |
|---|---|---|---|---|---|---|
bcb9e927b0d57527776a7f7cbf092d9692b0cdd4 | senryyankee/Tarea4 | /Clase1/clase1.py | 165 | 3.90625 | 4 | x = raw_input("ingrese num")
y= raw_input("ingrese num")
if(x<y):
print str ( x ) + "es menor que" + str ( y )
else:
print str ( x ) + "es mayor que" + str ( y )
|
50e318dad4d5d253cd1ee7a6633b0ad5e1373c6f | mwoinoski/crs1906 | /exercises/solution_ex04_debugging/sample_unit_tests/test_person.py | 1,099 | 3.59375 | 4 | """Unit tests for Person
Run as follows:
cd C:\crs1906\examples\ch03_examples
python -m unittest test_person.py
"""
__author__ = 'Mike Woinoski (michaelw@articulatedesign.us.com)'
import unittest
from person import Person
class PersonTestCase(unittest.TestCase):
"""Unit tests for Person"""
def test_init(self):
person = Person("John", "Quincy", "Adams")
self.assertEqual("John", person.first_name)
self.assertEqual("Quincy", person.middle_name)
self.assertEqual("Adams", person.last_name)
def test_eq_instances_equal(self):
p1 = Person("John", "Quincy", "Adams")
p2 = Person("John", "Quincy", "Adams")
self.assertEqual(p1, p2)
def test_eq_instances_not_equal(self):
p1 = Person("John", None, "Adams")
p2 = Person("John", "Quincy", "Adams")
self.assertEqual(p1, p2) # calls Person.__ne__()
def test_eq_new_instances_equal(self):
p1 = Person(None, None, None)
p2 = Person(None, None, None)
self.assertEqual(p1, p2) # calls Person.__eq__()
if __name__ == '__main__':
unittest.main()
|
989cc52ff5f49ffb3c2069df19be7067dd90acf9 | limapedro2002/PEOO_Python | /Lista_03/Luis Miguel/Questão_2 | 297 | 3.984375 | 4 | """
Faça uma função que informe a quantidade de dígitos de um determinado número inteiro in-
formado.
"""
def numero(a):
b = str(a)
print(len(b))
numero(20)
#pedindo a entrada em str permite contar os caracteres facilmente
numero(str(input("forneça um numero inteiro: ")))
|
cc76e0bdc8b729b96ed38f6da77bdd795510e3e7 | xica369/holbertonschool-machine_learning | /pipeline/0x01-apis/1-sentience.py | 1,106 | 3.53125 | 4 | #!/usr/bin/env python3
"""
By using the Swapi API, create a method that returns the list of names
of the home planets of all sentient species.
"""
import requests
def sentientPlanets():
"""
returns the list of names of the home planets of all sentient species\
"""
url = "https://swapi-api.hbtn.io/api/species"
home_planets = []
while url:
response_species = requests.get(url)
if response_species.status_code == 200:
resp_species = response_species.json()
result_species = resp_species["results"]
for specie in result_species:
if (specie["designation"].lower() == "sentient" or
specie["classification"].lower() == "sentient"):
if specie["homeworld"]:
response_homeworld = requests.get(specie["homeworld"])
resp_homeworld = response_homeworld.json()
home_planets.append(resp_homeworld["name"])
url = resp_species["next"]
else:
url = None
return home_planets
|
0c72cc978695da5137b2f3801a18f6f8e0d2fc4d | mohitsavaliya1/Defective-Object-Detection | /im.py | 877 | 3.578125 | 4 | import sys
from scipy.misc import imread
from scipy.linalg import norm
from scipy import sum, average
def main():
file1, file2 = sys.argv[1:1+2]
img1 = to_grayscale(imread(file1).astype(float)) #grayscale image to reduce noise
img2 = to_grayscale(imread(file2).astype(float))
n_m, n_0 = compare_images(img1, img2)
print n_m/img1.size
def compare_images(img1, img2):
img1 = normalize(img1) #normalize image
img2 = normalize(img2)
diff = img1 - img2 #difference of two images
m_norm = sum(abs(diff)) #main logic of Manhattan Norm
z_norm = norm(diff.ravel(), 0)
return (m_norm, z_norm)
def to_grayscale(arr):
"If arr is a color image (3D array), convert it to grayscale (2D array)."
if len(arr.shape) == 3:
return average(arr, -1)
else:
return arr
def normalize(arr):
rng = arr.max()-arr.min()
amin = arr.min()
return (arr-amin)*255/rng
if __name__ == "__main__":
main()
|
e67933d544e98f40f901435a0a4cb35b4d3cec9f | deepaksingh4520/python-code- | /area of rectangle.py | 155 | 3.953125 | 4 | l=int(input("enter the length of the rectangle"))
b=int(input("enter the breadth of the rectangle"))
area=l*b;
print("area of the rectangle is",area);
|
0850ebb3b890a57e500fb07feffd9baeca5931ff | otiyotta/cousera-ml | /week1/Linear-Algebra/quiz3.py | 133 | 3.671875 | 4 | # -*- coding:utf-8 -*-
import numpy as np
from sklearn import linear_model
x=np.array([[2,1,8]]).reshape(3,1)
print x.transpose()
|
759196e9076fb4d47a8688ac624bf6393f44fa5c | Javierzs/Curso_Refuerso_Algoritmos_y_programacion | /validar_programa.py | 838 | 3.671875 | 4 | import random
a=random.randint(0, 100)
c=0
intentos = 0
while True:
numero = input("Ingrese un número entero: ")
if (numero=="FIN"):
break
else:
if(intentos==5):
print("Demaciados intentos fuera de caracteres 🤡")
break
try:
numero=int(numero)
if(c==5):
print("Demaciados intentos del rango establecido 🤡")
break
if(numero>=0 and numero<=100):
if(numero>a):
print("es mayor")
elif(numero<a):
print("es menor")
else:
print("Ganaste el numero es: "+str(a))
break
else:
print("Numero fuera de rango")
c+=1
except:
intentos += 1
print("Error ingrese el valor entero❌")
|
d423cf5c0d7c655a3e861d2ab8884fe2a3b1d0ea | Aasthaengg/IBMdataset | /Python_codes/p03775/s880524227.py | 336 | 3.515625 | 4 | def i():
return int(input())
def i2():
return map(int,input().split())
def s():
return str(input())
def l():
return list(input())
def intl():
return list(int(k) for k in input().split())
n = i()
m = float("Inf")
for i in range( 1,int(n**(1/2))+1 ):
if n%i == 0:
note = len(str(max(i,n//i)))
if note < m:
m = note
print(m) |
ecf7d17c2bcf4e89634425c60b6a9853c1996382 | Ekeopara-Praise/python-challenge-solutions | /Ekeopara_Praise/Phase 2/LIST/Day44 Tasks/Task10.py | 201 | 3.890625 | 4 | '''10. Write a Python program to find a tuple, the smallest second index value from a list of tuples.'''
x = [(4, 1), (1, 2), (6, 0)]
print(min(x, key=lambda n: (n[1], -n[0])))
#Reference: w3resource |
15fb8951c04f4141cd59fe0fcec18b6c551c6822 | MilenaLee/algorithm | /Leetcode/307. Range Sum Query - Mutable.py | 1,225 | 3.5625 | 4 | class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = [0] + nums
self.fenwick = [0 for _ in range(len(nums) + 1)]
for i, num in enumerate(nums):
idx = i + 1
while idx < len(self.fenwick):
self.fenwick[idx] += num
idx += (idx & -idx)
def update(self, i, val):
"""
:type i: int
:type val: int
:rtype: void
"""
i += 1
update_value = val - self.nums[i]
self.nums[i] = val
while i < len(self.fenwick):
self.fenwick[i] += update_value
i += (i & -i)
def _sumRange(self, i):
ret = 0
while i > 0:
ret += self.fenwick[i]
i &= (i-1)
return ret
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
i, j = i, j+1
return self._sumRange(j) - self._sumRange(i)
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(i,val)
# param_2 = obj.sumRange(i,j) |
1a12565930760fc63340a8afc1683e4fc26007f9 | alvas-education-foundation/ISE_3rd_Year_Coding_challenge | /4AL17IS014_DIKSHIT_KOTIAN/23May/Swap.py | 413 | 4.28125 | 4 | /*You are given a string and your task is to swap cases. In other words,
convert all lowercase letters to uppercase letters and vice versa.*/
def swap_case(s):
a = ""
for let in s:
if let.isupper() == True:
a+=(let.lower())
else:
a+=(let.upper())
return a
if __name__ == '__main__':
s = raw_input()
result = swap_case(s)
print result |
09dda623d72ac52a406e8d1c6f612e2c9b17c393 | Lorenzodelso/python-lab2 | /Esercizio1.py | 555 | 4.09375 | 4 | list = []
while True:
print ("Insert the number corresponding to the action you want to perform:\n"
"1. insert a new task;\n "
"2. remove a task;\n"
"3. show all the tasks;\n "
"4. close the program.\n")
choise = int(input("Your choise: "))
if choise==1:
task = input("New task: ")
list.append(task)
elif choise==2:
task = input("Task to be removed: ")
list.remove(task)
elif choise==3:
print (sorted(list))
elif choise==4:
break
exit (1) |
89e81578c87e1b87fbbc38762a9bddc407bea78c | yongmon01/AlgorithmStudy | /Programmers/Heap/이중우선순위큐.py | 1,680 | 3.515625 | 4 | import heapq
def solution(operations):
count = 0
q = []
for i in operations:
if i.startswith("I"):
num = int(i[2:])
heapq.heappush(q, num)
count += 1
elif i == "D -1" and count >= 1:
heapq.heappop(q)
count -= 1
elif i == "D 1" and count >= 1:
max_num = max(q)
q.remove(max_num)
count -= 1
if count == 0:
return [0,0]
max_num = max(q)
return (max_num, heapq.heappop(q))
operations = ["I 2", "I 3", "D -1", "D 1", "I 4"]
print(solution(operations))
# import heapq
#
# def solution(operations):
# count = 0
#
# positive_q = []
# negative_q = []
#
# for i in operations:
# if i.startswith("I"):
# num = int(i[2:])
# heapq.heappush(positive_q, num)
# heapq.heappush(negative_q, -num)
# count += 1
# elif i == "D -1" and count >= 1:
# heapq.heappop(positive_q)
# count -= 1
# elif i == "D 1" and count >= 1:
# heapq.heappop(negative_q)
# count -= 1
#
# if count > 0:
# return [-heapq.heappop(negative_q), heapq.heappop(positive_q)]
# else:
# return [0, 0]
#
# # # 최소 뽑기
# # print(heapq.heappop(positive_q))
# # # 최대 뽑기
# # print(heapq.heappop(negative_q))
#
# operations = ["I 2", "I 3", "D -1", "D 1", "I 4"]
# print(solution(operations))
# import heapq
#
# q = []
# heapq.heappush(q,2)
# heapq.heappush(q,3)
# heapq.heappush(q,1)
# heapq.heappush(q,5)
# heapq.heappush(q,4)
# q.sort(reverse=True)
# print(q)
# print(heapq.heappop(q)) |
a797115a5ec650451031170470314e1c1da05f77 | Aasthaengg/IBMdataset | /Python_codes/p03712/s385569392.py | 342 | 3.53125 | 4 | a,b=map(int,input().split())
List = []
mid = ""
for i in range (a):
List.append(input())
resList = []
for i in range(a+2):
if i == 0 or i == a+1:
for j in range(b+2):
mid += "#"
resList.append(mid)
mid = ""
else:
mid = "#"+List[i-1]+"#"
resList.append(mid)
mid = ""
for element in resList:
print(element) |
ed825c3295fcb5c7fc725371bb31633e32c83ffe | FaizHamid/PyTkinterGUI | /Buttons.py | 360 | 4.0625 | 4 | from tkinter import *
root = Tk()
# Creating function
def myClick():
myLabel = Label(root, text="Look I clicked a button!!!")
myLabel.pack()
# Creating Button widgets and Shoving them to screen
myButton = Button(root, text="Click Me!", command=myClick, fg="blue", bg="#ffffff") # Hex color code for black #000000
myButton.pack()
root.mainloop()
|
79f5412e9d66cbd978b09aededaab0d2f4eb2c3a | Shreemay/FP | /4.py | 195 | 3.703125 | 4 | def prod_Even(li):
ls = filter(find_Even,li)
print reduce(lambda x,y: x*y, ls)
def find_Even(x):
if x%2 == 0:
return True
else:
return False
lst = [1,2,3,4,5,6,7,8,9,10]
prod_Even(lst)
|
5bbaeca3fdf9c36f3df727bee33e8259af5d57a7 | GiulianoCiomschi/Instruc-iunea-IF | /6.py | 227 | 3.984375 | 4 | n1=int(input("Dati prima nota:"))
n2=int(input("Dati a doua nota:"))
n3=int(input("Dati a treia nota:"))
if n3>8:
print(n1,n2,n3,sep=" ")
if n3<8:
if n1>n2:
print(n1)
if n2>n1:
print(n2) |
f2daad3a8b96f11a926cd630a472d5f3b9a5cf25 | tainenko/Leetcode2019 | /leetcode/editor/en/[1486]XOR Operation in an Array.py | 1,042 | 3.5 | 4 | # You are given an integer n and an integer start.
#
# Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.
# length.
#
# Return the bitwise XOR of all elements of nums.
#
#
# Example 1:
#
#
# Input: n = 5, start = 0
# Output: 8
# Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8)
# = 8.
# Where "^" corresponds to bitwise XOR operator.
#
#
# Example 2:
#
#
# Input: n = 4, start = 3
# Output: 8
# Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.
#
#
#
# Constraints:
#
#
# 1 <= n <= 1000
# 0 <= start <= 1000
# n == nums.length
#
# Related Topics Math Bit Manipulation 👍 776 👎 281
# leetcode submit region begin(Prohibit modification and deletion)
import functools
class Solution:
def xorOperation(self, n: int, start: int) -> int:
nums = [start + i * 2 for i in range(n)]
return functools.reduce(lambda x, y: x ^ y, nums)
# leetcode submit region end(Prohibit modification and deletion)
|
0af8dd2a27e975f90e20411c300609ce35d047ef | madeibao/PythonAlgorithm | /PartA/Py二叉树的是否相等的二叉树.py | 901 | 3.75 | 4 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
return Solution.equiv(root1, root2)
@staticmethod
def equiv(r1, r2):
if r1 is None:
return r2 is None
elif r2 is None:
return False
if r1.val != r2.val:
return False
return (Solution.equiv(r1.left, r2.left) and Solution.equiv(r1.right, r2.right)) \
or (Solution.equiv(r1.left, r2.right) and Solution.equiv(r1.right, r2.left))
if __name__ == '__main__':
s = TreeNode(1)
s2 = TreeNode(2)
s3 = TreeNode(3)
s.left = s2
s.right = s3
n = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n.left = n2
n.right = n3
test= Solution()
print(test.equiv(s, n))
|
0cce7066e6a90a0ec8640cf54296817c70fb7a12 | sagrawal1234/AUTOMATION | /main.py | 142 | 3.828125 | 4 | import os
search = input('Enter aplication name:- ')
if(search == "zoom" or "Zoom" or "ZOOM"):
print("Opening Zoom Aplication")
|
9c3d3630798d6f9d96f9dcf75291df37a611f8a0 | Rajahx366/Codewars_challenges | /6kyu_Roman_Numerals_Encoder.py | 1,275 | 4.40625 | 4 | """
Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
Example:
solution(1000) # should return 'M'
Help:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Remember that there can't be more than 3 identical symbols in a row.
More about roman numerals - http://en.wikipedia.org/wiki/Roman_numerals
"""
dic = {1:"I",5:"V",10:"X",50:"L",100:"C",500:"D",1000:"M"}
def solution(n):
s = str(n)
ans = ""
for i in range(1,len(s)+1):
l = int(s[-i])
pos = 10**(i-1)
if l < 4:
ans = l * dic[pos] + ans
elif l == 4:
ans = dic[pos] + dic[pos*5] + ans
elif l >= 5 and l < 9:
ans = dic[pos*5] + (l-5)*dic[pos] + ans
else:
ans = abs(l-10)*dic[pos] + dic[pos*10]+ans
return ans |
3e520021dcdd232b9cb8e62afd5dec2a0902d8c6 | stanislavrossolenko/python | /Task 3.3.py | 151 | 3.71875 | 4 | numbers = []
for i in range(3):
number = int(input('Введите число: '))
numbers.append(number)
print((sum(numbers)) - min(numbers))
|
f04aa549d7013b0807877221b20f964f2aee04c6 | DevooKim/algorithm-study | /week7/book/old/48devoo.py | 1,169 | 3.578125 | 4 | import collections
import heapq
import functools
import itertools
import re
import sys
import math
import bisect
from typing import *
#못풀음
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def dfs(node: TreeNode):
if not node:
return -1
left = dfs(node.left)
right = dfs(node.right)
if abs(left - right) > 2:
return False
if node.left:
left + 1
if node.right:
right + 1
return max(left, right)
return True
def book(self, root: TreeNode) -> bool:
def check(root):
if not root:
return 0
left = check(root.left)
right = check(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left, right) + 1
return check(root) != -1
a = Solution() |
be271c4796537325e91b05225aee51ebfe1003c5 | jtills/api-tutorials | /translator.py | 491 | 3.578125 | 4 | import requests
print("Here are our languages: \nShakespeare\nYoda\nPirate\nMorse\nBrooklyn\nChef\nVulcan\nKlingon\nPig Latin")
language = input('\nWhat language to be translated to: ')
text = input('\nWrite text to be translated: ')
text = text.split(' ')
url = "https://api.funtranslations.com/translate/{}.json?text=".format(language)
for word in text:
url = url + word + '%20'
data = requests.get(url).json()
print(data['contents']['translated'])
input()
|
9a1ad129a30c51b4f2b71a4611b022ec949f7c09 | gtfuhr/leetCode | /medium/longestSubstringWithoutRepeatingCharacters.py | 821 | 3.625 | 4 | class Solution:
def repeat_characters(self, s: str) -> bool:
for i, char_i in enumerate(s):
for j, char_j in enumerate(s):
if i != j and char_i == char_j:
return True
return False
def lengthOfLongestSubstring(self, s: str) -> int:
longest_string = ''
actual_string = ''
len_s = len(s)
for i, char in enumerate(s):
actual_string += char
if (i+1 < len_s):
if actual_string not in s[i+1:] and not self.repeat_characters(actual_string):
longest_string = actual_string
else:
actual_string = ''
return len(longest_string)
|
1c71d782511180aeea37f0b95ec469a9467ef487 | emperorlu/Data-Distribution-Simulator | /build/scripts/testanalysis.py | 12,468 | 3.546875 | 4 | # To change this template, choose Tools | Templates
# and open the template in the editor.
# This is mostly an example build by Dirk and will not be used for the dg paper!
import scipy.stats
import numby as np
import matplotlib
matplotlib.use("PDF")
import matplotlib.pyplot as plt
import sys
import os
import csv
###############################################################################
## Calculate the confidence Intervall for the given array
##
## @param data The array to calculate the confidence-interval about
## @param confidence The confidence to calculate
## (the probability that an Element is in the interval)
##
## @return The lower and upper bound of the confidence interval
###############################################################################
def mean_confidence_interval(data, confidence=0.95):
a = 1.0*np.array(data)
n = len(a)
m, se = np.mean(a), scipy.stats.stderr(a)
# calls the inverse CDF of the Student's t distribution
h = se * scipy.stats.t._ppf((1+confidence)/2., n-1)
return m-h, m+h
###############################################################################
## Calculate the mean value for the given array
##
## @param data The array to calculate the mean about
##
## @return The mean value
###############################################################################
def mean(data):
a = 1.0 * np.array(data)
return np.mean(a)
###############################################################################
## Read Data from the given File. The file has to exist in csv notation with
## comma (,) as delimiter.
##
## @param data The array to calculate the mean about
##
## @return The mean value
###############################################################################
def read_data(filename, parameter_names = ["config"]):
# Identify the factors in the list
def gather_factors( head_data, parameter_keys):
factors_ = []
for i in xrange(len(head_data)):
c = head_data[i]
for p in parameter_keys:
if c == p:
break
else:
factors_.append((c,i))
return factors_
# Identify the parameters in the list
def gather_parameters(head_data, parameter_keys):
parameters_ = []
for i in xrange(len(head_data)):
c = head_data[i]
for p in parameter_keys:
if c == p:
parameters_.append((c, i))
break
return parameters_
f = open(filename)
r = csv.reader(f)
data = [[c for c in row] for row in r]
#factors = gather_factors(data[0], ["config"])
#parameters = gather_parameters(data[0], ["config"])
factors = gather_factors(data[0], parameter_names)
parameters = gather_parameters(data[0], parameter_names)
# remove the headers
data = data[1:]
data.sort()
return Data(data, factors, parameters)
###############################################################################
## This class holds the Data and offers method to access them more convinient
###############################################################################
class Data():
###########################################################################
## Constructor
##
## @param data A 2-dimensional array holding the data
## @param factors a List denoting the columns holding factos
## @param parameters a List denoting the the columns holding parameters
###########################################################################
def __init__(self, data, factors, parameters):
self.data = data
self.factors = factors
self.parameters = parameters
###########################################################################
## return the whole data as 2 dimensional map
##
## @return the whole data as 2 dimensional map
###########################################################################
def all(self):
return self.data
###########################################################################
## get all rows holding in the column referred by parameter_name one of
## the given configs.
##
## @param configs The positive matching values to be in the comlumn
## @param parameter_name The name of the column to be filtered
##
## @return all rows holding the requested values in the given column
###########################################################################
def filter_config(self, configs, parameter_name="config"):
new_data = []
for config in configs:
i = data.index_of_parameter(parameter_name)
for row in self.data:
if row[i] == config:
new_data.append(row)
return Data(new_data, self.factors, self.parameters)
###########################################################################
## find the column denoting the given parameter
##
## @param parameter_name The name of the parameter to find
##
## @return The column holding the data of the parameter
###########################################################################
def index_of_parameter(self, parameter_name):
for parameter in self.parameters:
if parameter[0] == parameter_name:
return parameter[1]
raise ValueError("Illegal parameter %s: %s" % (parameter_name, ",".join((p[0] for p in self.parameters))))
###########################################################################
## find the column denoting the given factor
##
## @param factor_name The name of the factor to find
##
## @return The column holding the data of the factor
###########################################################################
def index_of_factor(self, factor_name):
for factor in self.factors:
if factor[0] == factor_name:
return factor[1]
raise ValueError("Illegal factor %s: %s" % (factor_name, ",".join((f[0] for f in self.factors))))
###########################################################################
## get all Values of a given factor
##
## @param factor_name The name of the factor to get values for
##
## @return The column denoted by the given factor
###########################################################################
def get_values(self, factor_name):
# Convert Value to double. Return 0 if there is no valid double
def convert_value(v):
try:
return float(v)
except ValueError:
return 0.0
i = self.index_of_factor(factor_name)
values = [row[i] for row in self.data]
return np.array([convert_value(v) for v in values])
def get_storage_label(data, mode = None):
storage_label_mapping = {"16kchunks": "16KB chunks", "2ssd": "2 SSD", "4ssd": "4 SSD","1ssd": "1 SSD", "1worker": "1 client", "2worker": "2 clients",
"256KB": "256 KB", "512KB": "512 KB", "64KB": "64 KB", "mem": "RAM", "noaux2": "minimal auxiliary index", "noaux": "reduced auxiliary index"}
config_index = data.index_of_parameter("config")
labels = []
for row in data.all():
factor_id = row[config_index]
if mode == "worker" and factor_id == "4ssd":
label = "4 clients"
elif mode == "bi_size" and factor_id == "4ssd":
label = "128 KB"
elif mode == "chunks" and factor_id == "4ssd":
label = "8KB chunks"
elif mode == "noaux" and factor_id == "4ssd":
label = "full auxiliary index"
else:
label = storage_label_mapping[factor_id]
labels.append(label)
return labels
def tp_chart(data, new_xticks, filename):
l = len(data.all())
width = 0.5
ind = np.arange(l)
plt.figure(figsize=figure_size)
run1_means = data.get_values("run1-tp-Mean")
run1_err = None
run1_err = data.get_values("run1-tp-Interval")
run2_means = data.get_values("run2-tp-Mean")
run2_err = None
run2_err = data.get_values("run2-tp-Interval")
#print run1_means, run2_means
p1 = plt.bar([i * 3 for i in ind],run1_means, yerr=run1_err, ecolor="k", color="0.5", label="Generation 1")
p2 = plt.bar([(i * 3) + 1 for i in ind],run2_means, yerr=run2_err, ecolor="k", color="w", label="Generation 2")
plt.ylabel("Throughput MB/s")
xticks = ["" for i in xrange(l * 3)]
for i in xrange(l):
xticks[(i * 3) + 1 ] = new_xticks[i]
ind = np.arange(l * 3)
plt.xticks(ind, xticks)
leg = plt.legend(loc=0)
plt.savefig(os.path.join(output_dir, filename))
profile_columns = [
"profile-chunking",
"profile-ci",
"profile-bi",
"profile-storage",
"profile-log",
"profile-lock"]
def get_profile_values(data, run, data_kind = "Mean", normalized=False):
values = []
sum = np.empty([len(data.all())])
for i in xrange(len(data.all())):
sum[i] = 0
for profile_column in profile_columns:
value = data.get_values("%s-%s-%s" % (run, profile_column, data_kind))
if profile_column == "profile-total":
value = value - sum
sum = sum + value
values.append(value)
if normalized:
return [value / sum for value in values]
else:
return [value / 1000 for value in values]
def profile_chart(data, new_xticks, filename, normalized=False, bcf=False, bloom=False):
profile_names = ["Chunking","Chunk Index", "Block Index","Storage","Log", "Lock", "BCF", "Bloom"]
profile_colors = ["1.0", "0.9" , "0.7" ,"0.5" ,"0.3","0.1", "0.4", "0.2"]
def add_run_profile_bar(means, index_offset):
top = np.empty([len(means[0])])
for i in xrange(len(means[0])):
top[i] = 0
for profile_index in xrange(len(means)):
profile_data = means[profile_index]
profile_color = profile_colors[profile_index]
profile_name = None
if index_offset == 0:
profile_name = profile_names[profile_index]
if not (bcf == False and profile_index == 6) and not (bloom == False and profile_index == 7):
plt.bar([(i * 3) + index_offset for i in ind],profile_data,bottom=top,color=profile_color,label=profile_name)
top = top + profile_data
l = len(data.all())
width = 0.5
ind = np.arange(l)
plt.figure(figsize=figure_size)
run1_means = get_profile_values(data, "run1", "Mean", normalized)
run2_means = get_profile_values(data, "run2", "Mean", normalized)
add_run_profile_bar(run1_means,0);
add_run_profile_bar(run2_means,1);
if(normalized):
plt.ylabel("Ratio on total running time")
locs, labels = plt.yticks()
labels = ["%s%%" % (i * 100) for i in locs]
plt.yticks(locs, labels)
else:
plt.ylabel("Thread wall clock time")
locs, labels = plt.yticks()
labels = ["" for i in locs]
plt.yticks(locs, labels)
xticks = ["" for i in xrange(l * 3)]
for i in xrange(l):
xticks[(i * 3) + 1 ] = new_xticks[i]
ind = np.arange(l * 3)
plt.xticks(ind, xticks)
(xmin,xmax) = plt.xlim()
plt.xlim(xmax=xmax*1.6)
leg = plt.legend(loc=0)
f = leg.get_frame()
f.set_alpha(0.0)
plt.savefig(os.path.join(output_dir,filename))
def summary_profile_chart(data, configs, name, mode = None):
data = data.filter_config(configs)
storage_labels = get_storage_label(data, False)
filename = "profile-%s-chart.pdf" % name
profile_chart(data, storage_labels, filename)
def summary_chart(data, configs, name, mode = None):
data = data.filter_config(configs)
storage_labels = get_storage_label(data, mode=mode)
filename = "tp-%s-chart.pdf" % name
tp_chart(data, storage_labels, filename)
if __name__ == "__main__":
print "Hello World"
# data_file = sys.argv[1]
# data = read_data(data_file)
# summary_chart(data, ["1ssd", "2ssd", "4ssd", "mem"], "devices")
# summary_chart(data, ["1worker", "2worker", "4ssd"], "worker", mode="worker")
# summary_chart(data, ["4ssd","16kchunks"], "chunks", mode="chunks")
# summary_chart(data, ["noaux2", "4ssd"], "noaux", mode="noaux")
# summary_profile_chart(data, ["1ssd", "2ssd", "4ssd", "mem"], "devices")
|
dd3ade0ba66f4e2b8cf236099d3184ab51e1046f | ntk-nguyen/leetcode | /problems/excel_sheet_column_title.py | 725 | 4.09375 | 4 | """
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
"""
def excel_sheet_column_title(n):
alphabet = [chr(i) for i in range(ord('A'), ord('Z')+1)]
if n <= len(alphabet):
return alphabet[n-1]
if n % len(alphabet):
return excel_sheet_column_title(int(n / len(alphabet))) + excel_sheet_column_title(n % len(alphabet))
else:
return excel_sheet_column_title(int(n / len(alphabet)) - 1) + excel_sheet_column_title(n % len(alphabet))
if __name__ == '__main__':
number = 701
result = excel_sheet_column_title(n=number)
print(result)
|
306670732a67a5492a3c7f00f10eb20d93af22d5 | fangsijie/python-Leetcode | /14-Longest Common Prefix.py | 1,456 | 3.6875 | 4 | '''
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
'''
#by myself
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
a = 0
if len(strs) == 0:
return ""
if len(strs) == 2:
for j in range(len(min(strs,key=len))):
if strs[0][j] == strs[1][j]:
a += 1
else:
break
return strs[0][:a]
for j in range(len(min(strs,key=len))):
for i in range(len(strs)-1):
if strs[i][j] == strs[i+1][j]:
continue
else:
break
else:
a += 1
if a == 0:
return ""
else:
return strs[0][:a]
# by others
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
for i in range(len(strs[0])):
for str in strs:
if len(str) <= i or strs[0][i] != str[i]:
return strs[0][:i]
return strs[0]
|
15196ddcafe6e06ff6174379fe0e5591a4de5e47 | tuanphandeveloper/practicepython.org | /palindrome.py | 332 | 4.53125 | 5 |
# Ask the user for a string and print out whether this string is a palindrome or not.
# (A palindrome is a string that reads the same forwards and backwards.)
testStr = input("Please enter a string ")
if testStr[::1] == testStr[::-1]:
print("This string is a palindrome ")
else:
print("This string is not a palindrome ") |
901d72c0cbe84d2294461511cac8c04eb70fda41 | yizhishi/python_tutorial | /week5/SevenDigitsDraw.py | 1,562 | 3.65625 | 4 | # SevenDigitsDraw.py
import turtle
import time
#
def drawGap():
turtle.penup()
turtle.fd(5)
# 画七段数码管的一段
def drawLine(isDraw):
drawGap()
turtle.pendown() if isDraw else turtle.penup()
turtle.fd(40)
drawGap
turtle.right(90)
# 画数字
def drawDigit(digit):
# 下半部分绘制
drawLine(False) if digit in [0, 1, 7] else drawLine(True)
drawLine(False) if digit in [2] else drawLine(True)
drawLine(False) if digit in [1, 4, 7] else drawLine(True)
drawLine(False) if digit in [1, 3, 4, 5, 7, 9] else drawLine(True)
turtle.left(90)
# 上半部分绘制
drawLine(False) if digit in [1, 2, 3, 7] else drawLine(True)
drawLine(False) if digit in [1, 4] else drawLine(True)
drawLine(False) if digit in [5, 6] else drawLine(True)
turtle.left(180)
turtle.penup()
turtle.fd(40)
#
def drawDate(date):
year = date[0: 4]
month = date[4: 6]
day = date[-2:]
for i in year:
i = eval(i)
turtle.pencolor('red')
drawDigit(i)
turtle.fd(40)
for i in month:
i = eval(i)
turtle.pencolor('green')
drawDigit(i)
turtle.fd(40)
for i in day:
i = eval(i)
turtle.pencolor('blue')
drawDigit(i)
def main():
# 当前年月日
date = time.strftime('%Y%m%d', time.gmtime())
turtle.setup(1000, 400, 200, 200)
turtle.penup()
turtle.fd(-300)
turtle.pensize(5)
drawDate(date)
turtle.hideturtle()
turtle.done()
main()
|
ca53b658f76ae16c75fa7f33be80735552085dc3 | juleslagarde/hash-code | /2019/training/pizza.py | 1,385 | 3.609375 | 4 |
class Pizza:
def __init__(self, params):
self.h = int(params[0])
self.w = int(params[1])
self.min = int(params[2])
self.max = int(params[3])
# tab[x][y]
self.tab=[]
for x in range(self.w):
self.tab.append([])
for y in range(self.h):
self.tab[x].append([])
def __str__(self):
out="min:"+str(self.min)+" max:"+str(self.max)+"\n"
for y in range(self.h):
for x in range(self.w):
out += str(self.tab[x][y])
out += "\n"
return out
def readFile(filename):
file = open(filename, "r")
line1 = file.readline().split(" ")
pizza = Pizza(line1)
for y in range(pizza.h):
line = file.readline()
for x in range(pizza.w):
pizza.tab[x][y]=line[x]
return pizza
class PizzaPart:
def __init__(self, x, y, dx, dy):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
def __str__(self):
return str(self.y)+" "+str(self.x)+" "+str(self.y+self.dy-1)+" "+str(self.x+self.dx-1)
def count(self):
return self.dx * self.dy
def fromFile(line):
part = PizzaPart(0,0,0,0)
part.y=int(line[0])
part.x=int(line[1])
part.dy=int(line[2])-part.y+1
part.dx=int(line[3])-part.x+1
return part
|
7d8853ded96e08600804af6f72f19d590c001652 | jeremander/Twitter | /stream.py | 1,959 | 3.546875 | 4 | """Channels a stream of tweets matching a given term or terms to a JSON file.
Usage: python3 stream.py term1 term2 ... termN [prefix]
The output file will be [prefix].json
Note: the term arguments should be put in quotes to deal with hashtags
"""
from twitter import *
from http.client import IncompleteRead
import sys
class TweetListener(tw.streaming.StreamListener):
"""StreamListener that channels tweets to a JSON file."""
def __init__(self, pref = None):
"""[pref].json will be the filename to which to channel tweets. If pref = None, does not save the tweets, only displays them."""
super(TweetListener, self).__init__()
self.pref = pref
def on_data(self, data):
try:
tweet = Tweet.parse(api, json.loads(data))
print(tweet)
if (self.pref is not None):
with open('%s.json' % self.pref, 'a') as f:
f.write(data)
return True
except BaseException as e:
print('Error on_data: %s' % str(e))
return True
def on_error(self, status):
print(status)
return True # don't kill the stream
def on_timeout(self):
print("Timeout...")
return True # don't kill the stream
def channel_tweets(terms, pref = None):
"""Channels tweets with the given terms to the screen, and if pref != None, to a file named [pref].json."""
if (not isinstance(terms, list)):
terms = [terms]
stream = tw.Stream(auth, TweetListener(pref))
while True:
try:
stream.filter(track = terms)
except IncompleteRead: # oh well, just keep on trucking
continue
except KeyboardInterrupt:
stream.disconnect()
break
def main():
nargs = len(sys.argv) - 1
assert (nargs >= 2)
terms = sys.argv[1:-1]
prefix = sys.argv[-1]
channel_tweets(terms, prefix)
if __name__ == "__main__":
main()
|
4ec768ed17ca53acdd648cb9dca3bb8f57a64a68 | adhamera/calculator-2 | /arithmetic.py | 1,453 | 4.3125 | 4 | """Functions for common math operations."""
# print("Hi")
def calculator():
input_string = 'pow 3 5'
tokens = input_string.split(' ')
while tokens[0] != "q":
if tokens[0] == "q":
quit
elif tokens[0] == "pow":
return 3**5
elif tokens[0] == "add or +":
return 3+5
print(calculator())
#while True:
#input_string = 'pow 3 5'
#tokens = input_string.split(' ') # => ['pow', '3', '5']
# read input
# tokenize input
# if the first token is "q":
# quit
# else:
# (decide which math function to call based on first token)
# if the first token is 'pow':
# call the power function with the other two tokens
# (...etc.)
# def add(num1, num2):
# """Return the sum of the two inputs."""
# return 10
# def subtract(num1, num2):
# """Return the second number subtracted from the first."""
# def multiply(num1, num2):
# """Multiply the two inputs together."""
# def divide(num1, num2):
# """Divide the first input by the second and return the result."""
# def square(num1):
# """Return the square of the input."""
# def cube(num1):
# """Return the cube of the input."""
# def power(num1, num2):
# """Raise num1 to the power of num2 and return the value."""
# def mod(num1, num2):
# """Return the remainder of num1 / num2."""
|
24062bd5b4a3671084b0a7632ce559e6ace10ff7 | supachawal/JavaProgramming | /GCJ2015R1A/A_MushroomMonster.py | 4,599 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 04:35:42 2015
@author: supachawal
Problem A. Mushroom Monster
Kaylin loves mushrooms. Put them on her plate and she'll eat them up! In this problem she's eating a plate of mushrooms, and Bartholomew is putting more pieces on her plate.
In this problem, we'll look at how many pieces of mushroom are on her plate at 10-second intervals. Bartholomew could put any non-negative integer number of mushroom pieces down at any time, and the only way they can leave the plate is by being eaten.
Figure out the minimum number of mushrooms that Kaylin could have eaten using two different methods of computation:
Assume Kaylin could eat any number of mushroom pieces at any time.
Assume that, starting with the first time we look at the plate, Kaylin eats mushrooms at a constant rate
whenever there are mushrooms on her plate.
For example, if the input is 10 5 15 5:
With the first method, Kaylin must have eaten at least 15 mushroom pieces:
first she eats 5, then 10 more are put on her plate, then she eats another 10.
There's no way she could have eaten fewer pieces.
With the second method, Kaylin must have eaten at least 25 mushroom pieces.
We can determine that she must eat mushrooms at a rate of at least 1 piece per second.
She starts with 10 pieces on her plate. In the first 10 seconds, she eats 10 pieces,
and 5 more are put on her plate. In the next 5 seconds, she eats 5 pieces, then her plate
stays empty for 5 seconds, and then Bartholomew puts 15 more pieces on her plate.
Then she eats 10 pieces in the last 10 seconds.
Input: The first line of the input gives the number of test cases, T. T test cases follow.
Each will consist of one line containing a single integer N, followed by a line containing N
space-separated integers mi; the number of mushrooms on Kaylin's plate at the start, and at 10-second intervals.
Output: For each test case, output one line containing "Case #x: y z", where x is the test case number (starting from 1), y is the minimum number of mushrooms Kaylin could have eaten using the first method of computation, and z is the minimum number of mushrooms Kaylin could have eaten using the second method of computation.
Limits
1 ≤ T ≤ 100.
Small dataset: 2 ≤ N ≤ 10. 0 ≤ mi ≤ 100.
Large dataset: 2 ≤ N ≤ 1000. 0 ≤ mi ≤ 10000.
Sample
Input
4
4
10 5 15 5
2
100 100
8
81 81 81 81 81 81 81 0
6
23 90 40 0 100 9
Output
Case #1: 15 25
Case #2: 0 0
Case #3: 81 567
Case #4: 181 244
"""
import os
import re
import sys
import time
from psutil import virtual_memory
def eatAnyQuantityAnyTime(N, mi):
return sum([max(0, mi[i - 1] - mi[i]) for i in range(1, N)])
def eatConstantly(N, mi):
c = max([mi[i - 1] - mi[i] for i in range(1, N)])
return sum([min(c, mi[i]) for i in range(N - 1)])
def showString(s, limit):
if len(s) > limit:
s = s[0:limit - 3] + '...'
return s
def main(argv):
mem = virtual_memory()
starttime = time.clock()
print('=============== start program (FREEMEM=%.0fm)===============' % (mem.total/1024/1024))
# inputFileName = '-sample1.in'
# inputFileName = '-sample2.in'
# inputFileName = '-small-practice.in'
inputFileName = '-large-practice.in'
inputFileName = os.path.basename(__file__)[0] + inputFileName
if len(argv) > 1:
inputFileName = argv[1]
outputFileName = inputFileName.split('.in', 1)[0] + '.out'
print('%s --> %s' % (inputFileName, outputFileName))
inputFile = open(inputFileName, 'r')
outputFile = open(outputFileName, 'w')
textLine = inputFile.readline().rstrip()
testCaseCount = int(textLine)
testCaseNumber = 1
textLine = inputFile.readline().rstrip()
while testCaseNumber <= testCaseCount:
N = int(textLine)
textLine = inputFile.readline().rstrip()
mi = [int(s) for s in re.split('\\s+', textLine)]
N = min(N, len(mi))
print('Case #%d: N=%d, data={%s},' % (testCaseNumber, N, showString(textLine, 60)), end=' ')
answer1 = eatAnyQuantityAnyTime(N, mi)
answer2 = eatConstantly(N, mi)
print('answer=%d %d' % (answer1, answer2))
print('Case #%d: %d %d' % (testCaseNumber, answer1, answer2), file=outputFile, flush=True)
testCaseNumber += 1
textLine = inputFile.readline().rstrip()
print('=============== end program (FREEMEM=%.0fm ELAPSED=%f)===============' % (mem.total/1024/1024, time.clock() - starttime))
if __name__ == '__main__':
main(sys.argv)
|
de9f24a9ba6b29ba367074aa85fd933315dff116 | FR4NKESTI3N/project_euler | /1-10/04.py | 340 | 3.546875 | 4 | def is_palindrome(n):
flag=1
string = str(n)
length = len(string)
for i in range((length/2)):
if string[i] != string[length-1-i]:
flag=0
return flag
largest = 9009
for i in range(101,999):
for j in range(i,999):
n=i*j
if is_palindrome(n) and largest<n:
largest = n
I=i
J=j
print largest,I,J,is_palindrome(906609)
|
ef7281a52c61e05ad201f98d7feaa04387dae7a8 | Alexmaxwell7/python | /swaping.py | 365 | 4.15625 | 4 | num1 = int(input("enter the first value"))
num2 = int (input('enter the second value'))
print("before swaping first value", num1)
print("before swaping second value", num2)
# approach one
# temp = num1
# num1 = num2
# num2 = temp
# approach two
num1,num2=num2,num1
print ('after the swaping first value',num1)
print ('after the swaping second value', num2)
|
41ea58de88a273619b8713694d1e15542dd64b84 | ShraddhaPChaudhari/PythonWork | /Advance/gui1.py | 987 | 3.703125 | 4 | #celcius to farnehnite
from tkinter import *
def calculate(*args):
try:
value=float(celsius.get())
farnehnite.set((value*9/5+32))
except ValueError:
pass
root=Tk()
root.title("celsius to farnehnite")
mainframe=Frame(root)
mainframe.grid(column=0,row=0,sticky=(N,W,E,S))
mainframe.columnconfigure(0,weight=1)
mainframe.rowconfigure(0,weight=1)
celsius=StringVar()
farnehnite=StringVar()
celsius_entry=Entry(mainframe,width=7,textvariable=celsius)
celsius_entry.grid(column=2,row=1,sticky=(W,E))
a=Entry(mainframe,textvariable=farnehnite).grid(column=2,row=2,sticky=(W,E))
b=Button(mainframe,text="Calculate",command=calculate).grid(column=3,row=3,sticky=W)
c=Label(mainframe,text="celsius").grid(column=3,row=1,sticky=W)
d=Label(mainframe,text="is eqivalent to").grid(column=1,row=2,sticky=E)
e=Label(mainframe,text="farnehnite").grid(column=3,row=2,sticky=W)
celsius_entry.focus()
root.bind("<Return>",calculate)
root.mainloop()
|
d586030313d7fd492feb3dbac14a5010d3c68f65 | woojeee/Hackerrank_python | /Merge_The_Tools.py | 695 | 3.625 | 4 | def merge_the_tools(string, k):
# your code goes here
# n/k 로 나눈 만큼 리스트.
n = len(string)
div_list = []
for i in range(0, int(n/k)):
# divide string into list
temp_list = list(string[i*k:(i+1)*k])
remove_overlap = []
# print(temp_list)
# remove overlap word
for word in temp_list:
if word not in remove_overlap:
remove_overlap.append(word)
# print(remove_overlap)
# string으로 합쳐서 리스트에 저장
div_list.append("".join(remove_overlap))
for word in div_list:
print(word)
string, k = input(), int(input())
merge_the_tools(string, k)
|
a21af269b87c6afaa9fbcf70b29f37f21dae53d1 | arcPenguinj/CS5001-Intensive-Foundations-of-CS | /homework/HW6/test_vowelsearch.py | 830 | 3.796875 | 4 | from vowelsearch import r_contain_vowel
from vowelsearch import contains_vowel
def test_r_contain_vowel():
assert (r_contain_vowel(" ") is False)
assert (r_contain_vowel("") is False)
assert (r_contain_vowel("😍😊😂😂❤") is False)
assert (r_contain_vowel("12345") is False)
assert (r_contain_vowel("#abc") is True)
assert (r_contain_vowel("354abc") is True)
assert (r_contain_vowel("hello") is True)
def test_contains_vowel():
assert (contains_vowel([]) is False)
assert (contains_vowel([" ", " "]) is False)
assert (contains_vowel(["garage", "this", "man"]) is True)
assert (contains_vowel(["fff", "this", "man"]) is False)
assert (contains_vowel(["❤abc", "#abc", "123abc"]) is True)
assert (contains_vowel(["", "#bc", "123abc"]) is False)
|
0658151e0032bc9005f7c1af729c96a6a8d63a9b | weiarqq/data-structure | /leetcode.py | 363 | 3.796875 | 4 |
def max_sum(arr):
max = arr[0]
part_maz = arr[0]
for i in range(1, len(arr)):
if part_maz+arr[i] > arr[i]:
part_maz = part_maz+arr[i]
if max < part_maz:
max = part_maz
else:
part_maz = arr[i]
return max
if __name__ == '__main__':
print(max_sum([-10,2,3,4,-5,6,7,8,-9])) |
aa3a277fe28223a7c1c33706839cbadbe87ea214 | htmlprogrammist/kege-2021 | /tasks_8/task_8_6.py | 660 | 4.03125 | 4 | """
№ 185 Сколько слов длины 5, начинающихся с согласной буквы и заканчивающихся гласной буквой,
можно составить из букв К, У, М, А? Каждая буква может входить в слово несколько раз.
Слова не обязательно должны быть осмысленными словами русского языка.
"""
from itertools import product
counter = 0
for i in product('КУМА', repeat=5):
if (i[0] == 'К' or i[0] == 'М') and (i[-1] == 'У' or i[-1] == 'А'):
counter += 1
print(counter) # 256
|
438fef8d26f47a61fbc107deec2bc5b8284a7685 | lishulongVI/leetcode | /python3/60.Permutation Sequence(第k个排列).py | 3,206 | 3.578125 | 4 | """
<p>The set <code>[1,2,3,...,<em>n</em>]</code> contains a total of <em>n</em>! unique permutations.</p>
<p>By listing and labeling all of the permutations in order, we get the following sequence for <em>n</em> = 3:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>Given <em>n</em> and <em>k</em>, return the <em>k</em><sup>th</sup> permutation sequence.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Given <em>n</em> will be between 1 and 9 inclusive.</li>
<li>Given <em>k</em> will be between 1 and <em>n</em>! inclusive.</li>
</ul>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre>
<p>给出集合 <code>[1,2,3,…,<em>n</em>]</code>,其所有元素共有 <em>n</em>! 种排列。</p>
<p>按大小顺序列出所有排列情况,并一一标记,当 <em>n </em>= 3 时, 所有排列如下:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>给定 <em>n</em> 和 <em>k</em>,返回第 <em>k</em> 个排列。</p>
<p><strong>说明:</strong></p>
<ul>
<li>给定<em> n</em> 的范围是 [1, 9]。</li>
<li>给定 <em>k </em>的范围是[1, <em>n</em>!]。</li>
</ul>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> n = 3, k = 3
<strong>输出:</strong> "213"
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> n = 4, k = 9
<strong>输出:</strong> "2314"
</pre>
<p>给出集合 <code>[1,2,3,…,<em>n</em>]</code>,其所有元素共有 <em>n</em>! 种排列。</p>
<p>按大小顺序列出所有排列情况,并一一标记,当 <em>n </em>= 3 时, 所有排列如下:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>给定 <em>n</em> 和 <em>k</em>,返回第 <em>k</em> 个排列。</p>
<p><strong>说明:</strong></p>
<ul>
<li>给定<em> n</em> 的范围是 [1, 9]。</li>
<li>给定 <em>k </em>的范围是[1, <em>n</em>!]。</li>
</ul>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> n = 3, k = 3
<strong>输出:</strong> "213"
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> n = 4, k = 9
<strong>输出:</strong> "2314"
</pre>
"""
class Solution:
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
|
ee46ae946c592b5718e7141fd43e9b53cbcf94ec | benbendaisy/CommunicationCodes | /python_module/examples/424_Longest_Repeating_Character_Replacement.py | 1,751 | 4.125 | 4 | class Solution:
"""
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
Example 1:
Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input: s = "AABABBA", k = 1
Output: 4
Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
"""
def characterReplacement(self, s: str, k: int) -> int:
def is_window_valid(start, end, count):
return end + 1 - start - count <= k
all_letters = set(s)
max_length = 0
# iterate over each unique letter
for letter in all_letters:
start, cnt = 0, 0
# initialize a sliding window for each unique letter
for end in range(len(s)):
if s[end] == letter:
# if the letter matches, increase the count
cnt += 1
# bring start forward until the window is valid again
while not is_window_valid(start, end, cnt):
if s[start] == letter:
# if the letter matches, decrease the count
cnt -= 1
start += 1
# at this point the window is valid, update max_length
max_length = max(max_length, end + 1 - start)
return max_length
|
c5b15436f73efc819e07a1131c874edd3bd2f20d | sandhud6/Coursework-210CT | /Week 5/Q1.py | 940 | 4.09375 | 4 | def LargestSequence(sequence):
finalList = []
tempList = []
num = 0
for i in range(len(sequence)-1):
if i == 0:
tempList.append(sequence[i])
else:
if sequence[i] >= sequence[i-1]:
tempList.append(sequence[i])
if sequence[i] < sequence[i-1]:
finalList.append(tempList)
tempList = []
tempList.append(sequence[i])
finalList.append(tempList)
print(finalList)
for i in range(len(finalList)):
if i == 0:
num = len(finalList[i])
sequence = finalList[i]
else:
if len(finalList[i]) > num:
num = len(finalList[i])
sequence = finalList[i]
return("This is the largest sequence " + str(sequence) + str(num))
sequence = [1,2,3,4,1,5,1,6,7]
print(LargestSequence(sequence))
|
bb394f04ffa0a7222882f6a72f9748f5b5a6d919 | apiechowicz/nlp | /hw-3/utils/argument_parser.py | 638 | 3.734375 | 4 | from argparse import ArgumentParser
from typing import Tuple
def parse_arguments() -> Tuple[str, int, str, int]:
parser = ArgumentParser()
parser.add_argument("input_dir", help="directory containing data to be processed")
parser.add_argument("judgement_year", help="year for which judgements will be processed")
parser.add_argument("dict_path", help="path to dictionary file")
parser.add_argument("number_of_words", help="number of words to be shown from words that are not in dictionary")
args = parser.parse_args()
return args.input_dir, int(args.judgement_year), args.dict_path, int(args.number_of_words)
|
cd6d24bac7462bd8ae0411d3dfe3674079753f3c | Lionelding/EfficientPython | /MetaclassesAndAttributes/35_Annotate_Class_Attribute_with_Metaclass.py | 2,059 | 4.34375 | 4 | # Item 35: Annotate Class Attribute with Metaclass
"""
1. Metaclass is able to modify a class's attribute before the class is defined
2. Descriptors and Metaclass are powerfull combination for declarative behavior and runtime inspection
3. Avoid memory using the Descriptors and Metaclass
"""
## Example 1:
print("######### Example 1 #########")
class Field(object):
def __init__(self, name):
self.name = name
self.internal_name = "_" + self.name
def __get__(self, instance, type):
if isinstance is None:
return self
return getattr(instance, self.internal_name, "Not defined")
def __set__(self, instance, value):
setattr(instance, self.internal_name, value)
class Customer(object):
first_name = Field('first_name')
last_name = Field('last_name')
prefix = Field('prefix')
suffix = Field('suffix')
foo = Customer()
print(f'Before: {foo.first_name}, {foo.__dict__}')
print(f'Before: {repr(foo.first_name)}, {foo.__dict__}')
foo.first_name = 'JACK'
print(f'After: {repr(foo.first_name)}, {foo.__dict__}')
## Example 2: Metaclass
print("######### Example 2 #########")
class NewField(object):
def __init__(self):
self.name = None
self.internal_name = None
def __get__(self, instance, type):
if isinstance is None:
return self
return getattr(instance, self.internal_name, "Not defined")
def __set__(self, instance, value):
setattr(instance, self.internal_name, value)
class Meta(type):
def __new__(meta, name, bases, class_dict):
for key, value in class_dict.items():
print(key, value)
if isinstance(value, NewField):
value.name = key
value.internal_name = "_" + key
cls = type.__new__(meta, name, bases, class_dict)
return cls
class DataBaseRow(object, metaclass=Meta):
pass
class BetterCustomer(DataBaseRow):
print('3')
first_name = NewField()
last_name = NewField()
prefix = NewField()
suffix = NewField()
print('4')
foo2 = BetterCustomer()
print(f'Before: {repr(foo2.first_name)}, {foo2.__dict__}')
foo2.first_name = 'JACK'
print(f'After: {repr(foo2.first_name)}, {foo2.__dict__}') |
56adc16268f6d244ae04e2901531e17daad768f0 | brmuch/COMP9021 | /Final sample/sample_2.py | 1,212 | 4.0625 | 4 | banknotes = {}
banknote_values = [1, 2, 5, 10, 20, 50, 100]
def recursive_method(num, amount):
if num == 0:
if amount > 0:
banknotes[1] = amount
return
else:
if amount >= banknote_values[num]:
banknotes[banknote_values[num]] = amount // banknote_values[num]
recursive_method(num - 1, amount % banknote_values[num])
else:
recursive_method(num - 1, amount)
def f(N):
'''
>>> f(20)
Here are your banknotes:
$20: 1
>>> f(40)
Here are your banknotes:
$20: 2
>>> f(42)
Here are your banknotes:
$2: 1
$20: 2
>>> f(43)
Here are your banknotes:
$1: 1
$2: 1
$20: 2
>>> f(45)
Here are your banknotes:
$5: 1
$20: 2
>>> f(2537)
Here are your banknotes:
$2: 1
$5: 1
$10: 1
$20: 1
$100: 25
'''
banknote_values = [1, 2, 5, 10, 20, 50, 100]
# Insert your code here
print('Here are your banknotes:')
banknotes.clear()
recursive_method(6, N)
keys = sorted(banknotes.keys())
for key in keys:
print(f"${key}: {banknotes[key]}")
if __name__ == '__main__':
import doctest
doctest.testmod()
|
1b4143934921cc99ee2cd731f69deda53eafbcac | evamc7/learn_python_the_hard_way | /exx44f.py | 822 | 4.25 | 4 | #create a other class
class other(object):
def override(self):
print "OTHER override()"
def implicit(self):
print "OTHER implicit()"
def altered(self):
print "OTHER altered()"
#create a child class
class child(object):
#definimos una funcion y llamamos a other y le damos el nombre de self.other para llamarlo
def __init__(self):
self.other = other()
#definimos una funcion y llamamos a la funcion implicit de other
def implicit(self):
self.other.implicit()
def override(self):
print "child override()"
def altered(self):
print "CHILD, BEDORE OTHER altered()"
#llamamos a la funcion altered de other
self.other.altered()
print "Child, after other altered()"
son = child() #instancia 1
girl = child() # instancia 2
son.implicit()
son.override()
son.altered() |
3ea1469eaf3bb3a3ea1bbc10fbf1f7ec92630069 | DenisPerez/Calculo | /Taller2/ejercicio1a.py | 558 | 3.5625 | 4 | # -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import numpy as np
import scipy as s
f = lambda x, n : (x**n)/(x+5)
def generateFunction(n):
fig = plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
ax1.grid()
xtricks = s.linspace(0,1,110)
function = []
for x in np.arange(0,1.1,0.01):
function.append(f(x,n))
#print(function)
ax1.plot(xtricks ,function, label='$f(x)$')
ax1.legend(loc=0)
for i in range(5,25,5):
generateFunction(i)
for i in range(30,70,10):
generateFunction(i)
|
3c0f9b6f142662a64c4f494553140481635eaec9 | luvadisd/cd101 | /homework/HW1_v1.0 composer's ages.py | 843 | 3.734375 | 4 | n = int(input("О скольких композиторах Вы хотите узнать? "))
first_name = []
last_name = []
birth = []
death = []
age = []
for i in range(n):
composer_data = input("Введите имя композитора, его фамилию, дату рождения и смерти через запятую: ").split(", ")
first_name.append(composer_data[0])
last_name.append(composer_data[1])
birth.append(composer_data[2])
death.append(composer_data[3])
if int(composer_data[3]) <= 2021:
continue
else:
print("К счастью, композитор жив :)")
break
for i in range(n):
count_age = int(death[i]) - int(birth[i])
print(f"Имя: {first_name[i]}, Фамилия: {last_name[i]}, Возраст {count_age}")
age.append(count_age)
|
089aadfa091310e01f99ea4def27b48395b37176 | sparsh-m/30days | /d3_5.py | 635 | 3.828125 | 4 | #https://leetcode.com/problems/unique-paths/
"""
1)Since final destination lies in arr[n-1][m-1], now of paths from
any block in row n-1 and col m-1 is 1.
2)For any other block you can either go right, or go down, therefore
the total path from that block is sum of paths from down bloack and right
adjacent block.
Time Complexity: O(m*n)
Space Complexity: O(m*n)
"""
def uniquePaths(n,m):
table = [[1]*m for i in range(n)]
for i in range(n-2,-1,-1):
for j in range(m-2,-1,-1):
table[i][j] = table[i+1][j] + table[i][j+1]
for k in table:
print(k)
return table[0][0]
print(uniquePaths(4,5)) |
22bb8f2139f5dce59e4e308c39796ae324308636 | zachallen8/github-upload | /hangman.py | 3,192 | 4.0625 | 4 | import random
#variables
randomWord = ""
outputWord = ""
mistakesLeft = 0
index = 0
inputChar = ''
categoryNum = 0
categoryName = ""
difficultyNum = 0
difficultyName = ""
listToString = ' '
wrongLetters = " "
#Welcomes user and prompts for category choice
print("Hello, welcome to hangman!")
categoryNum = int(input("Choose your category - Enter 1 for Animals, 2 for Colors, 3 for Country Names: "))
#Processes user input for category choice and chooses random word from file
if(categoryNum < 1 or categoryNum > 3):
print("Sorry, that is not a valid category choice. Please re-run the program and try again!")
exit()
if(categoryNum == 1):
categoryName = "Animals"
randomWord = random.choice(open("animals.txt").read().split("\n"))
elif(categoryNum == 2):
categoryName = "Colors"
randomWord = random.choice(open("colors.txt").read().split("\n"))
elif(categoryNum == 3):
categoryName = "Country Names"
randomWord = random.choice(open("countries.txt").read().split("\n"))
#Prompts user to choose difficulty
difficultyNum = int(input("Choose your difficulty - Enter 1 for easy (7 strikes), 2 for medium (5 strikes), 3 for hard (3 strikes): "))
#Sets category name to the user input
if(difficultyNum < 1 or difficultyNum > 3):
print("Sorry, that is not a valid difficulty choice. Please re-run the program and try again!")
exit()
if(difficultyNum == 1):
difficultyName = "Easy"
mistakesLeft = 7
elif(difficultyNum == 2):
difficultyName = "Medium"
mistakesLeft = 5
elif(difficultyNum == 3):
difficultyName = "Hard"
mistakesLeft = 3
#Prints category and difficulty to user
print("You chose to play " + categoryName + " on " + difficultyName + '.')
#processes chosen word into a list
randomWord = randomWord.lower()
outputWord = list(randomWord)
while(index < len(outputWord)):
if(outputWord[index] != ' '):
outputWord[index] = "_"
index = index + 1
listToString = ' '.join([str(elem) for elem in outputWord])
#processes user input until word is correct or lives run out
wrongLetters = list(wrongLetters)
print(listToString)
while mistakesLeft > 0 and "_" in outputWord:
inputChar = input("Please enter a letter (" + str(mistakesLeft) + " mistakes left): ")
if(inputChar in outputWord):
print("The letter " + inputChar + " has already been guessed correctly.")
continue
elif (inputChar in wrongLetters):
print("The letter " + inputChar + " has already been guessed incorrectly.")
continue
if(inputChar in randomWord):
for index in range(0, len(randomWord)):
if(randomWord[index] == inputChar):
outputWord[index] = inputChar
listToString = ' '.join([str(elem) for elem in outputWord])
print(listToString)
else:
print("Sorry, " + inputChar + " was not in the word.")
print(listToString)
wrongLetters.append(inputChar)
mistakesLeft = mistakesLeft -1
if(mistakesLeft == 0):
print("Sorry! The word was \"" + randomWord + "\". Better luck next time!")
exit()
elif("_" not in outputWord):
print("Congrats! The word was \"" + randomWord + "\". Great job!")
exit()
|
d6fca8a606f5d5f04986e5daf86c5caf289eefd5 | Nitesh101/test | /Dec_20/2_Question.py | 282 | 3.765625 | 4 | class divisible:
def __init__(self):
pass
def putNumbers(self,num,limit):
i=0
while i<=limit:
if i%num == 0:
yield i
i+=1
obj = divisible()
num = input("Enter a number: ")
limit = input("Enter a range: ")
for index in obj.putNumbers(num,limit):
print index
|
874d31ddd170bd3e413383dd50faefb89b24a991 | KujouNozom/LeetCode | /python/2020_11/Question1609.py | 2,666 | 3.796875 | 4 | # 1609. 奇偶树
# 如果一棵二叉树满足下述几个条件,则可以称为 奇偶树 :
# 二叉树根节点所在层下标为 0 ,根的子节点所在层下标为 1 ,根的孙节点所在层下标为 2 ,依此类推。
# 偶数下标 层上的所有节点的值都是 奇 整数,从左到右按顺序 严格递增
# 奇数下标 层上的所有节点的值都是 偶 整数,从左到右按顺序 严格递减
# 给你二叉树的根节点,如果二叉树为 奇偶树 ,则返回 true ,否则返回 false 。
#
# 示例1
# 输入:root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
# 输出:true
# 解释:每一层的节点值分别是:
# 0 层:[1]
# 1 层:[10,4]
# 2 层:[3,7,9]
# 3 层:[12,8,6,2]
# 由于 0 层和 2 层上的节点值都是奇数且严格递增,而 1 层和 3 层上的节点值都是偶数且严格递减,因此这是一棵奇偶树。
#
# 示例 2
# 输入:root = [5,4,2,3,3,7]
# 输出:false
# 解释:每一层的节点值分别是:
# 0 层:[5]
# 1 层:[4,2]
# 2 层:[3,3,7]
# 2 层上的节点值不满足严格递增的条件,所以这不是一棵奇偶树。
#
# 示例 3
# 输入:root = [5,9,1,3,5,7]
# 输出:false
# 解释:1 层上的节点值应为偶数。
#
# 示例 4
# 输入:root = [1]
# 输出:true
#
# 示例 5
# 输入:root = [11,8,6,1,3,9,11,30,20,18,16,12,10,4,2,17]
# 输出:true
#
# 提示
# 树中节点数在范围 [1, 105] 内
# 1 <= Node.val <= 106
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isEvenOddTree(self, root: TreeNode) -> bool:
queue = [root]
level = 0
while queue:
even_flag = level % 2 == 0
pre = queue[0].val - 1 if even_flag else queue[0].val + 1
temp_queue = []
for node in queue:
val = node.val
if even_flag and (val % 2 == 0 or val <= pre):
return False
elif not even_flag and (val % 2 != 0 or val >= pre):
return False
else:
if node.left is not None:
temp_queue.append(node.left)
if node.right is not None:
temp_queue.append(node.right)
pre = val
level += 1
queue = temp_queue
return True
nodes = TreeNode(5)
nodes.left = TreeNode(4)
nodes.right = TreeNode(2)
nodes.left.left = TreeNode(3)
nodes.left.right = TreeNode(3)
nodes.right.left = TreeNode(7)
Solution().isEvenOddTree(nodes)
|
25565d14c679408b4f1eed088236b8eef3a8a568 | EOppenrieder/HW070172 | /Homework4/Exercise5_9.py | 240 | 4.21875 | 4 | # A program to count the number of words in a sentence
def main():
text = input("Enter your sentence: ")
word_len = []
for string in text.split():
x = string[0]
word_len.append(x)
print(len(word_len))
main() |
43cda06f65af43de24e03fa2e3863a27c79a33e8 | Kdcc-ai/python | /format格式化函数.py | 1,042 | 3.875 | 4 | # 有时候会用到
# 其实就是用{}替换原来的%来实现格式化输出
print("{} {}".format("hello", "world")) # 不设置指定位置,按默认顺序
print("{0} {1}".format("hello", "world")) # 设置指定位置
print("{1} {0} {1}".format("hello", "world")) # 设置指定位置
# 还可设置参数
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
# 还可以传入对象
class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value)) # "0" 是可选的
# 数字格式化 一些格式化方法 用到的时候使用即可
print("{:.2f}".format(3.1415926))
print ("{} 对应的位置是 {{0}}".format("runoob")) |
ee5fe4b93137ebfba862389b93166c8d3ba9a680 | Christina2727/MIT | /MIT/Hmwk 2/hmwk2.8.py | 860 | 4.0625 | 4 | def report_card():
class_names = []
class_grades = []
num_classes = int(input("How many classes did you take? "))
print("Please enter name and grade for each class ")
for i in range(num_classes):
name = (input("What was the name of your class? "))
grade = (input("what was your grade? "))
class_names.append(name)
class_grades.append(grade)
for i in range(num_classes):
#this concept works, but i do not know how to make this
# keep going through list regardless of how many items in the list
#print(class_names, "-", class_grades)
print(class_names[0], class_grades[0])
print(class_names[1], class_grades[1])
print(class_names[2], class_grades[2])
report_card()
# () = tuples -- []= list -- {} = dictionaries
|
3253dd84b20497e52a54e7acbdfd0e121b4e830b | kapootot/projects | /py_scripts/src/eraseSubs.py | 624 | 3.578125 | 4 | import os
def removeSubs(fname, file):
if file.endswith(".he.srt") or file.endswith(".srt"):
os.remove(fname)
print("Removed: " + fname)
def rename(fname, file):
newext = ".he.srt"
if fname.endswith(".srt"):
print("Renamed: " + fname)
root, ext = os.path.splitext(fname)
print(root)
os.rename(fname, root+newext)
print("Renamed: " + fname)
def walk(rootdir):
for root, dirs, files in os.walk(rootdir):
for file in files:
fname = os.path.join(root, file)
removeSubs(fname, file)
#rename(fname, file)
root = "/Users/amirwaisman/Movies/"
walk(root) |
b5473f3482b4cacb14aadf503e83fd9a2c6b9a84 | xwu64/LeetCode | /python/2-AddTwoNumbers/solution.py | 987 | 3.625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
s1 = []
s2 = []
start = l1
while start:
s1.append(start.val)
start = start.next
start = l2
while start:
s2.append(start.val)
start = start.next
sum = 0
for i in range(len(s1)):
sum = sum + 10**i*s1[i]
for i in range(len(s2)):
sum = sum + 10**i*s2[i]
listSum = list(str(sum))
result = ListNode(None)
start = result
start.val = int(listSum[-1])
listSum.pop()
while listSum:
start.next = ListNode(int(listSum.pop()))
start = start.next
return result
|
f597bade3d7d7c438a8cec7bddbba7304c7bead6 | xiaoluome/algorithm | /Week_02/id_24/LeetCode_242_024.py | 836 | 3.78125 | 4 | def isAnagram(s, t):
# s1
# return sorted(t) == sorted(s)
# s2
# if len(s) != len(t):
# return False
# setS = dict()
# setT = dict()
# for i in range(len(s)):
# if (s[i] in setS):
# setS[s[i]] = setS[s[i]] + 1
# else:
# setS[s[i]] = 1
# if (t[i] in setT):
# setT[t[i]] = setT[t[i]] + 1
# else:
# setT[t[i]] = 1
# return setS == setT
# s3
if len(s) != len(t):
return False
listS = [0] * 26
listT = [0] * 26
for i in range(len(s)):
listS[ord(s[i]) - ord('a')] += 1
listT[ord(t[i]) - ord('a')] += 1
return listS == listT
print(isAnagram("anagram", "nagaram")) |
3ca41d3a166b4009d73ba3bf45aeb7c4796e212b | antohneo/pythonProgramming3rdEdition | /PPCh3PE3.py | 565 | 4.28125 | 4 | # carbohydrate.py
# python3
# calculates the molecular weight of carbohydrate
def main():
print("Program calculates the molecular weight of a carbohydate")
print("based on the number of hydrogen, carbon & oxygen atoms.")
hydrogen = int(input("Enter the number of hydrogen atoms: ")) * 1.00794
carbon = int(input("Enter the number of carbon atoms: ")) * 12.0107
oxygen = int(input("Enter the number of oxygen atoms: ")) * 15.9994
molecularWeight = hydrogen + carbon + oxygen
print("The molecular weight is:", molecularWeight)
main()
|
b51f6f15e6bd57bb7eaaf16360007dd8eac6ca1e | SHPStudio/LearnPython | /basic/function.py | 6,680 | 4.5625 | 5 | # 函数
'''
python有很多内置的函数 比如abs()函数就是求绝对值的函数 而且可以通过help(abs) 来查看函数的相应信息
官网函数链接 http://docs.python.org/3/library/functions.html#abs
'''
# help(abs)
# 调用函数 如果函数参数个数有问题或者参数类型有问题都不会通过编译的 会报错
# abs() 绝对值函数
# print(abs(-10))
# print(abs(10))
# max(n1,n2,...) 求最大值函数
# print(max(1, 2, 4, 8, 6))
# print(max('sdf', 'dd', 'zfee'))
# 数据类型转换
# print(int('123'))
# print(int(12.36))
# print(float('12.36'))
# print(str(100))
# print(bool(1))
# print(bool(''))
# 给函数起别名 函数的名字其实就是一个引用 把引用传给别的变量 也就相当于给函数起一个别名了
# a = abs
# print(a(-3))
# 定义函数 如果想要return None的话可以简写为return
# def my_abs(x):
# if x >= 0:
# return x
# else:
# return -x
#
#
# print(my_abs(-1))
# 从文件中导入函数
# from abtest import my_abs
#
# print(my_abs('-1'))
# 定义空函数 比如你可能开发一个模块 方法之间的架构已经想好了 那么可以先定义空函数 让它先跑通
# pass相当于一个占位符 为了能够让程序跑通 可以放在程序的任何位置
# def test():
# pass
# a = 6
# if a > 15:
# pass
# 函数返回多个值
# 函数返回的多个值其实就是一个tuple
# import math
# def move(x, y, step, angle=0):
# nx = x + step * math.cos(angle)
# ny = y + step * math.sin(angle)
# return nx, ny
#
#
# x, y = move(100, 100, 60, math.pi / 6)
# r = move(100, 100, 60, math.pi / 6)
# print(x, y)
# print(r)
# 参数的默认值
'''
为什么要设置参数的默认值呢
就是为了能够减少函数调用的复杂程度 比如你一开始写了一个函数就两个参数就够了等后期你要加功能需要加入新的参数
那么新加的参数如果很多并且没有设默认值,那么之前其他地方调用的时候就会报错,参数个数不匹配
所以需要加入参数的默认值,这样其他调用也不会出错,想要调用新的函数传入的参数也比较灵活可变
并且默认参数的应该放在必选参数的后面 把变化小的参数放到后面 还有 默认参数一定要是不可变的
'''
# 计算平方
# def my_pow(x):
# return x * x
# def my_pow(x, n=2):
# s = 1
# while n > 0:
# n = n - 1
# s = s * x
# return s
# print(my_pow(12, 4))
# 多个参数默认值不按照顺序传入参数
# 比如enroll(name,gender,age=7,city='beijing') 他有两个默认参数,如果不想按照顺序传参数的话那需要传入参数的时候把参数名字带上
# def enroll(name, gender, age=7, city='beijing'):
# print(name)
# print(gender)
# print(age)
# print(city)
# enroll('shp', '5', city='beijign')
# 默认参数的坑 默认参数是可变的
# 如果默认参数是可变的比如空列表那么每次调用会记住这个变量
# def add_end(L=[]):
# L.append('End')
# return L
# print(add_end([1, 2, 3, 4])) # 正常调用
# print(add_end([1, 2, 3, 4,5]))
# print(add_end()) # 非正常调用
# print(add_end()) # 会出现两个End
# 现在改为不可变
# def add_end(L=None):
# if L is None:
# L = []
# L.append('End')
# return L
# print(add_end())
# print(add_end())
# 可变参数
# 比如传入参数为一个列表或者tuple
# def calc(numbers):
# sum = 0
# for item in numbers:
# sum = sum + item * item
# return sum
# print(calc([1,2,3,4]))
# print(calc((1,2,3,4)))
# 但是这样写有点儿麻烦 python中在参数前面加一个星号代表可变参数可以简化调用
# def calc(*numbers):
# sum = 0
# for n in numbers:
# sum = sum + n * n
# return sum
# print(calc(1,2,3,4))
# print(calc())
# 比如我们想要传入一个列表或者tuple呢 那么就通过星号把列表tuple转换为可变参数 就像c语言中把对象转换成指针引用差不多
# nums = [1,2,3,4]
# print(calc(*nums))
# 关键字参数 用**表示 他是代表可以传入任意个带有参数名的参数,python会自动转换为dict字典
# def test_key(name,age,**keyparam):
# print('name',name,'age',age,'other',keyparam)
# test_key('shp',20,city='beijing',country='xingshu')
# 它的作用主要是扩展函数的功能 比如做一个注册一开始可能只需要姓名和年龄,但是随着需求的不断变化
# 他需要更多的参数什么身份证号、住址、等等等等,就可以用一个关键字参数来扩展了
# 同样的我们可以建立一个dict变量 然后在调用函数的时候使用**把变量转换为关键字参数
# 注意:传入的keyparam只是my_dict的副本 并不会改变my_dict的值
# my_dict = {'city':'beijing','country':'xingshu'}
# test_key('shp',28,**my_dict)
# 命名关键字
# 使用关键字参数按照字典的形式传参数,但是如果要是传入不相关的key-value值是没用的,我们如果要想让用户按照规定的key来传值
# 就要用到命名关键字了
# 用法是如果后面的是需要限定的参数的关键字那么就在必须参数和关键字参数之间加个*来进行分割
# def test_limitkey(name,age,*,city,country):
# print('name',name,'age',age,'city',city,'country',country)
# test_limitkey('shp',30,city='sdf',country='dd')
# limitkey = {'city':'beijing','country':'xingshu'}
# test_limitkey('shp',30,**limitkey)
# 如果有可变参数了就不需要加*来分割了 就用可变参数就可以来当做分割
# 把命名关键字参数加入默认值那么就可以不传这个关键字的参数
# def test_limitkey(name,age,*,city='beijing',country):
# print(name,age,city,country)
# 参数的组合
# 可以使用各种参数进行组合
# 注意:组合的顺序 必选参数->默认参数->可选参数->命名参数->关键字参数
# 任何带有参数的方法都可以用 function(*args,**args2)来调用
# 递归函数
# def fact(n):
# if n == 1:
# return 1
# else:
# return n * fact(n-1)
# print(fact(50000))
# 因为递归函数每次递归的时候都会增加一个调用栈,如果很多的话就会导致调用栈溢出报错
# 所以可以进行尾递归优化 尾递归优化就是在return的时候调用自身 没有任何多余的操作,这样让解释器或者编译器优化为只用一个调用栈这样就不会溢出
# def fact_op(n,product):
# if n == 1:
# return product
# else:
# return fact_op(n-1,n * product)
# print(fact_op(5,1))
# 因为大部分解释器或者编译器没有做这种优化,所以依然会导致栈溢出 |
e3926d8211889e21a4b5dc76332d49f5554ac29a | mor9l4ok89/Lesson1_Tasks | /task6.py | 424 | 4.09375 | 4 | distance = int(input('Введите дистанцию первого забега: '))
distance_max = int(input('Введите максимальную дистанцую: '))
days = 1
while distance < distance_max:
days += 1
distance = distance + distance * 0.1
print('На ' + str(days) + '-й день спортсмен достиг результата - не менее ' + str(distance_max) + ' км.')
|
bf2d8106799a16c30003fd2ed67d4711a02b300d | JoselynRuiz/uip-pc4 | /Practica 2/app/__init__.py | 2,756 | 4.15625 | 4 | import sqlite3
db = sqlite3.connect('C:/Users/lapri/PycharmProjects/Practica2.3/app/data/Usuario.db')
print("Base de datos abierta")
cursor = db.cursor()
tabla1 = [
"""
CREATE TABLE IF NOT EXISTS Persona(
ID INTEGER PRIMARY KEY,
NOMBRE TEXT NOT NULL,
P_APELLIDO TEXT NOT NULL,
S_APELLIDO TEXT NOT NULL,
LUGAR TEXT NOT NULL,
)
"""
]
print("Tablas creadas correctamente")
tabla2 = [
"""
CREATE TABLE IF NOT EXISTS Familia(
ID_Padre INTEGER PRIMARY KEY,
ID_Madre TEXT NOT NULL,
ID_Hijo TEXT NOT NULL,
ID_Persona TEXT NOT NULL
)
"""
]
print("Tablas creadas correctamente")
tabla3 = [
"""
CREATE TABLE IF NOT EXISTS Relacion(
Fami TEXT NOT NULL,
Rela TEXT NOT NULL,
PRIMARY KEY(Fami,Rela),
FOREIGN KEY (Rela) REFERENCES Fami(ID),
FOREIGN KEY (Fami) REFERENCES Fami(ID_Padre)
)
"""
]
print("Tablas creadas correctamente")
print("1-Insertar Persona.")
print("2-Ver Persona.")
print("3-Borrar Persona.")
print("4-Salir")
a = int(input("Escoja la opcion que desea:"))
if a==1: #insertar
NOMBRE = input("\nNOMBRE: ")
P_APELLIDO = input("\nP_APELLIDO: ")
S_APELLIDO = input("\nS_APELLIDO: ")
LUGAR = input("\nLUGAR : ")
tabla55 = "INSERT INTO Persona(NOMBRE, P_APELLIDO, S_APELLIDO, LUGAR) VALUES (?,?,?,?)"
cursor.execute(tabla55, [NOMBRE, P_APELLIDO, S_APELLIDO, LUGAR])
db.commit()
print("Guardado correctamente")
elif a==2: #ver
print("1-Ver todo.")
print("2-Ver por familia")
b = int(input("Escoja la opcion que desea:"))
if b==1:
tabla55 = "SELECT * FROM Persona;"
cursor.execute(tabla55)
Persona = cursor.fetchall()
print("\n", Persona)
elif b==2:
relacion = "SELECT * FROM Familia"
cursor.execute(relacion)
Familia = cursor.fetchall() # muestra la fila
for row in Familia:
print("\n",Familia)
# "SELECT Padre. *, Familia. *"
# "SELECT Madre. *, Familia. *"
# "SELECT Hijo. *, Familia. *"
tabla44 = "SELECT * FROM Familia;"
cursor.execute(tabla44)
Familia = cursor.fetchall()
print("\n", Familia)
elif a==3: #eliminar
cursor.execute('''SELECT ID, NOMBRE, P_APELLIDO, S_APELLIDO, LUGAR FROM Persona''')
resultado = cursor.fetchall()
for fila in resultado:
print("{0} : {1}".format(fila[0], fila[1]))
ID = input("ID de usuario a eliminar: ")
for fila in resultado:
if int(ID) == int(fila[0]):
cursor.execute('''DELETE FROM Persona WHERE id = ?''',
(ID,))
db.commit()
else:
print("Hasta luego")
|
dddf1e86f14245dc7512ff32872c5d8f93365659 | 6519/Primer-trabajo | /Alumnos.py | 965 | 3.84375 | 4 | class Al:
def Pedir_datos(self):
self.numc=raw_input("Introduce tu numero de control:")
self.nom=raw_input("Nombre de usuario:")
self.edad=int(input("Ingresa tu edad:"))
self.dir=raw_input("Ingresa tu direccion:")
self.tel=int(input("Agrega tu numero de telefono:"))
def Mostrar_datos(self):
print "Tu nombre de usuario es =",self.nom
print "El numero de control es =",self.numc
print "Tu edad es =", self.edad
print "Tu direccion es =", self.dir
print "Tu numero telefonico es =", self.tel
def Pedir_calif(self):
self.cal1=float(input("Dame la primera calificacion:"))
self.cal2=float(input("Dame la segunda calificacion:"))
self.cal3=float(input("Dame la tercera calificacion:"))
self.promedio= (self.cal1 + self.cal2 + self.cal3) / 3
def Mostrar_promedio(self):
print "Tu promedio es =", self.promedio
|
03fef70e762b382c36c983c09a405965d2b43959 | RodrigoEC/Prog1-Questions | /unidade10/time_campeao/time.py | 454 | 3.6875 | 4 | # coding: utf-8
# Aluno: Rodrigo Eloy Cavalcanti
# Matrícula: 118210111
# Time campeão
def time_campeao(dados):
lista_campeoes = []
campeao = [0, 0, 0]
for time, tabela in dados.items():
if tabela[0] > campeao[0]:
campeao = tabela
lista_campeoes = []
lista_campeoes.append(time)
elif tabela[0] == campeao[0]:
lista_campeoes.append(time)
return lista_campeoes |
0bb9951683117a2b043c54848b305ac736114e9f | patil-poonam/pythonDemo | /file1.py | 437 | 3.890625 | 4 | """
This is a program for countig the number of lines,blank spaces,comment lines and tabs in file.
"""
__author__= 'Poonam'
fd = open("abc.txt")
i = 0
spaces = 0
tabs = 0
comm = 0
cnt = 0
for i,line in enumerate(fd):
spaces += line.count(' ')
tabs += line.count('\t')
comm += line.count('#')
fd.close()
print "spaces :",spaces
print "tabs : ",tabs
print "number of line :",i + 1
print "number of comment lines: ",comm
|
a81146860e8eaaca160395aca071838c80ed89c7 | PCWin12/Machine-Learning-1 | /HousingPricePrediction/index.py | 1,806 | 3.90625 | 4 | import pandas as pd
import numpy as np
import math
data=pd.read_csv('data\\train.csv')
cols=['LotArea','SalePrice'] #Required Columns for this program
col_area=np.array(data['LotArea']) #array storing LotArea Column's all values
col_price=np.array(data['SalePrice']) #array array storing SalePrice Column's all values
prices=[] #New column with prices of houses having price
area=[] #New column with area of houses having price
for i in range(len(col_area)):
area.append([1,col_area[i]]) #I'm adding the bias constant(whose value is always 1) column to the matrix too
prices.append(col_price[i])
data_new={'Area':area,'Price':prices} #Create new dataset with features (area and price of houses)
X=np.array(area)
y=np.asmatrix(prices).T
# theta_best is the optimum value of theta for inimum cost/loss function
theta_best = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y) #Formula for optimum value of theta
print('The optimal value of Parameters(Theta) are:\n')
theta_best=np.matrix.flatten(theta_best)
t_bias=np.ravel(theta_best[0])[0] #theta for bias variable i.e. 1
t_area=np.ravel(theta_best[0])[1] #theta for area variable
print('Bias Parameter= '+str(t_bias)+'\n')
print('Parameter for second Parameter(Area)= ' + str(t_area))
#Now, ask user for the Area and give them the best price for their house using the value of theta.
input_area=input("\n\n\nEnter Area of your House:")
input_area=int(input_area)
best_price= t_bias+ t_area*input_area
print("\n\n\n\nThe best price for your house is: $" + str(best_price))
print('\n\n\n\n\n\n\n')
print('================================================================================')
input('Press enter to exit :) ')
|
6d19268251bdb11d8d6e9c4df8f1b874c5b92063 | koobeomjin/iot_python2019 | /01_jump_to_python/exer/7.8/visitor_book.py | 702 | 3.828125 | 4 | name = input('이름을 입력하세요: ')
def search_visitor(name):
with open('visitor.txt','r') as f:
if f.read().find(name) != -1:
print('{0}님 다시 방문해 주셔서 감사합니다. 즐거운 시간되세요.'.format(name))
return
else:
birth_date = input('생년월일을 입력하세요 (ex:801212) : ')
registration(name, birth_date)
def registration(name, birth_date):
print('{0}님 환영합니다. 아래 내용을 입력하셨습니다.'.format(name))
print('{0}{1}'.format(name, birth_date))
with open('visitor.txt', 'a')as f:
f.write('\n{}''{}'.format(name,birth_date))
search_visitor(name) |
11fe6504ddcd4d08840171b60c149d40f0eb41b3 | HolyQuar/git_operation | /python_operation/standard_library_7.2/Decimal_floating_point_arithmetic_8/decimal_module.py | 1,342 | 4.03125 | 4 | """
Compared to the built-in float implementation of binary floating point, the class is especially helpful for:
--financial applications and other uses which require exact decimal representation,
--control over precision,
--control over rounding to meet legal or regulatory requirements,
--tracking of significant decimal places, or
--applications where the user expects the results to match calculations done by hand.
"""
# control over rounding/financial applications /control over precision
from decimal import *
decimal_data = round(Decimal('0.70')*Decimal('1.05'),2)
print('decimal_data:{}'.format(decimal_data))
float_point_round = round(.70*1.05,2)
print('float_point_round:{}'.format(float_point_round))
# to perform modulo calculations and equality tests that are unsuitable for binary floating point:
zero_compute=Decimal('1.00')%Decimal('.10')
print('zero_compute:{}'.format(zero_compute))
print('zero_float:{}'.format(1.00%0.1))
# tracking of significant decimal places
bool_result = sum([Decimal('0.1')*10]) == Decimal('1.0')
print('bool_result:{}'.format(bool_result))
bool_false = sum([0.1]*10) == 1.0
print('bool_false:{}'.format(bool_false))
# The decimal module provides arithmetic with as much precision as needed
getcontext().prec = 12
result_data = Decimal(1)/Decimal(7)
print('result_data:{}'.format(result_data)) |
de7145da490094aa40f5e1ad3c8dfdaf13f3df51 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/DennisLee/lesson08/test_circle_class.py | 6,073 | 3.8125 | 4 | #!/usr/bin/env python3
import unittest
from circle_class import Circle
class CircleTestCase(unittest.TestCase):
def test_radius_100(self):
c = Circle(5)
self.assertEqual(c.radius, 5)
def test_radius_101(self):
c = Circle(70)
self.assertEqual(c.radius, 70)
c.radius = 60
self.assertEqual(c.radius, 60)
def test_radius_102(self):
with self.assertRaises(ValueError):
c = Circle(-4)
del c
def test_diameter_100(self):
c = Circle(20)
self.assertEqual(c.diameter, 40)
self.assertEqual(c.radius, 20)
def test_diameter_101(self):
c = Circle(100)
c.radius = 14
self.assertEqual(c.diameter, 28)
self.assertEqual(c.radius, 14)
def test_diameter_102(self):
c = Circle(50)
c.diameter = 80
self.assertEqual(c.diameter, 80)
self.assertEqual(c.radius, 40)
def test_diameter_103(self):
c = Circle(72)
c.diameter += 6
self.assertEqual(c.diameter, 150)
self.assertEqual(c.radius, 75)
def test_diameter_104(self):
c = Circle(48)
with self.assertRaises(ValueError):
c.diameter = -2
def test_area_100(self):
c = Circle(8)
self.assertLess(abs(c.area-201.062), 0.1)
def test_area_101(self):
c = Circle(12)
with self.assertRaises(AttributeError):
c.area = 58
def test_diameter_constructor_100(self):
c = Circle.from_diameter(18)
self.assertEqual(c.diameter, 18)
self.assertEqual(c.radius, 9)
self.assertLess(abs(c.area-254.469), 0.1)
def test_diameter_constructor_101(self):
with self.assertRaises(ValueError):
c = Circle.from_diameter(-6)
del c
def test_repr_100(self):
c = Circle(200)
self.assertEqual(repr(c), 'Circle(200)')
def test_repr_101(self):
c = Circle.from_diameter(500)
self.assertEqual(repr(c), 'Circle(250.0)')
def test_repr_102(self):
c = Circle(10)
d = eval(repr(c))
self.assertIsInstance(d, Circle)
self.assertEqual(d.radius, 10)
self.assertEqual(d.diameter, 20)
self.assertLess(abs(d.area-314.159), 0.1)
def test_str_100(self):
c = Circle(4.555)
self.assertTrue("Circle with radius: 4.55" in str(c))
def test_add_100(self):
c1 = Circle(4)
c2 = Circle.from_diameter(10)
c3 = c1 + c2
self.assertIsInstance(c3, Circle)
self.assertEqual(c3.radius, 9)
self.assertEqual(c3.diameter, 18)
self.assertLess(abs(c3.area-254.469), 0.1)
def test_add_101(self):
c1 = Circle(6)
c2 = c1 + 2
self.assertIsInstance(c2, Circle)
self.assertEqual(c2.radius, 8)
self.assertEqual(c2.diameter, 16)
self.assertLess(abs(c2.area-201.062), 0.1)
def test_add_102(self):
c1 = Circle.from_diameter(14)
c2 = 3 + c1
self.assertIsInstance(c2, Circle)
self.assertEqual(c2.radius, 10)
self.assertEqual(c2.diameter, 20)
self.assertLess(abs(c2.area-314.159), 0.1)
def test_add_103(self):
c1 = Circle.from_diameter(8)
c2 = c1 + 0.75
self.assertIsInstance(c2, Circle)
self.assertEqual(c2.radius, 4.75)
self.assertEqual(c2.diameter, 9.5)
self.assertLess(abs(c2.area-70.882), 0.1)
def test_add_110(self):
c1 = Circle(5)
with self.assertRaises(ValueError):
c2 = c1 + (-6)
del c2
def test_add_111(self):
c1 = Circle(5)
with self.assertRaises(TypeError):
c2 = c1 + "86"
del c2
def test_multiply_100(self):
c1 = Circle(5)
c2 = Circle.from_diameter(6)
c3 = c1 * c2
self.assertIsInstance(c3, Circle)
self.assertEqual(c3.radius, 15)
self.assertEqual(c3.diameter, 30)
self.assertLess(abs(c3.area-706.858), 0.1)
def test_multiply_101(self):
c1 = Circle(6)
c2 = c1 * 4
self.assertIsInstance(c2, Circle)
self.assertEqual(c2.radius, 24)
self.assertEqual(c2.diameter, 48)
self.assertLess(abs(c2.area-1809.557), 0.1)
def test_multiply_102(self):
c1 = Circle.from_diameter(14)
c2 = 3 * c1
self.assertIsInstance(c2, Circle)
self.assertEqual(c2.radius, 21)
self.assertEqual(c2.diameter, 42)
self.assertLess(abs(c2.area-1385.442), 0.1)
def test_multiply_103(self):
c1 = Circle.from_diameter(8)
c2 = c1 * 0.75
self.assertIsInstance(c2, Circle)
self.assertEqual(c2.radius, 3.0)
self.assertEqual(c2.diameter, 6.0)
self.assertLess(abs(c2.area-28.274), 0.1)
def test_multiply_110(self):
c1 = Circle(6)
with self.assertRaises(ValueError):
c2 = c1 * -4
del c2
def test_multiply_111(self):
c1 = Circle(6)
with self.assertRaises(TypeError):
c2 = c1 * "54"
del c2
def test_comps_100(self):
c1 = Circle(7)
c2 = Circle(8)
self.assertTrue(c1 < c2)
self.assertTrue(c1 <= c2)
self.assertFalse(c1 == c2)
self.assertFalse(c1 > c2)
self.assertFalse(c1 >= c2)
self.assertTrue(c1 != c2)
def test_comps_101(self):
c1 = Circle(8)
c2 = Circle(8)
self.assertFalse(c1 < c2)
self.assertTrue(c1 <= c2)
self.assertTrue(c1 == c2)
self.assertFalse(c1 > c2)
self.assertTrue(c1 >= c2)
self.assertFalse(c1 != c2)
def test_comps_102(self):
c1 = Circle(9)
c2 = Circle(8)
self.assertFalse(c1 < c2)
self.assertFalse(c1 <= c2)
self.assertFalse(c1 == c2)
self.assertTrue(c1 > c2)
self.assertTrue(c1 >= c2)
self.assertTrue(c1 != c2)
if __name__ == "__main__":
unittest.main() |
61e519860f5daf6974ba5562e64abe29f09921b4 | fabioCordoba/MetodoBiseccion_python | /oper.py | 2,592 | 3.5625 | 4 | import re
import csv
import os
def CalcularIntervalo(temp):
#code...
return eval(reemp)
def modxi(A,B):
ecuacion = 'a+(b-a)/2'
#code ...
def error(A,B):
ecuacion = '(b-a)/2'
#code ...
ecuacion = input('Digite su ecuacion \n')
interA = input('Digite el intervalo A \n')
interB = input('Digite el intervalo B \n')
doc = open ("Datos.csv","w",newline="")
doc_csv_w = csv.writer(doc,delimiter=';')
print('\nEntradas: Ecuacion = ' , ecuacion , ' Intervalo A = ' , interA , ' Intervalo B = ' , interB ,'\n')
fa = CalcularIntervalo(interA)
fb = CalcularIntervalo(interB)
print('\nPrueba de Salida: Ecuacion = ' , ecuacion , ' f(a) = ' , fa , ' f(b) = ' , fb ,'\n')
if fa * fb < 0:
i=1
x=0
while(i <= 14):
if(i==1):
#print('\tse cumple Aplicar La Ecuacion a+(b-a)/2 \n')
a = float(interA)
b = float(interB)
xi = str(a+(b-a)/2)
#print('xi=',xi,'\n')
fxi = CalcularIntervalo(xi)
#print('fxi=',fxi,'\n')
xii = (b-a)/2;
#print('xii=',xii,'\n')
print('\ti\ta\tb\tf(a)\tf(b)\txi\tf(xi)\terror')
print('\t',i,'\t',a,'\t',b,'\t',fa,'\t',fb,'\t',xi,'\t',fxi,'\t',xii)
lista = [[i,a,b,fa,fb,xi,fxi,xii]]
encabezado = [['i','a','b','f(a)','f(b)','xi','f(xi)','error']]
if x==0:
for x in encabezado:
doc_csv_w.writerow(x)
for x in lista:
doc_csv_w.writerow(x)
i= i+1
else:
if fa * fxi < 0:
a = str(a)
if fb * fxi < 0:
b = str(b)
else:
b = str(xi)
else:
a = str(xi)
if fb * fxi < 0:
b = str(b)
else:
b = xi
fa = CalcularIntervalo(str(a))
fb = CalcularIntervalo(str(b))
xi = modxi(a,b)
fxi = CalcularIntervalo(str(xi))
xii = error(a,b);
print('\t',i,'\t',a,'\t',b,'\t',fa,'\t',fb,'\t',xi,'\t',fxi,'\t',xii)
lista = [[i,a,b,fa,fb,xi,fxi,xii]]
for x in lista:
doc_csv_w.writerow(x)
if i == 14:
doc.close()
i= i+1
dire=os.popen('chdir').read()
print("\nPara visualizar mejor los valores Se ha creado en un archivo 'Datos.csv' en =",dire)
else:
print('\tLa Ecuacion o los intervalos No cumplen con los requisitos del Calculo')
|
f5d5ad932786f2fbb638e21a68b41770dd028f37 | misocho/randomWalk | /randomWalk2.py | 1,366 | 3.84375 | 4 | # What is the longest random walk you can take so that on average you end up
# 4 blocks or fewer from home?
# If more than 4 blocks pay for a transport home
import random
def random_walk_2(n):
""" Return coordinates after 'n' block random walk."""
x, y = 0, 0
for i in range(n):
(dx, dy) = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
x += dx
y += dy
return (x, y)
#for i in range(25):
# walk = random_walk_2(10)
# print(walk, "Distance from home = ", abs(walk[0]) + abs(walk[1]))
#=============================================================================
# MONTE CARLO METHOD
# Conduct thousands of random trials and compute the pacentage of random walks
# that end in a short walk home
#=============================================================================
number_of_walks = 20000
for walk_length in range(1, 50):
no_transport = 0 # number of walks 4 or fewer blocks from home
for i in range(number_of_walks):
(x, y) = random_walk_2(walk_length)
distance = abs(x) + abs(y)
if distance <= 4:
no_transport += 1
no_transport_percentage = float(no_transport) / number_of_walks
print("Walk size = ", walk_length, "/ % no of transport = ",
100*no_transport_percentage) |
b4b79a1a3fd19aeb4a7dd6ba1c38bcbb7caf6442 | ceokereke/PathPlanning-1 | /Utility/discrete_distribution.py | 721 | 3.734375 | 4 | import numpy as np
def exponential_weighted_average1(n, weight):
"""
指数加权平均: weight^n, (1-weight)*weight^(n-1), ..., (1-weight)*weight, 1-weight
"""
distribution = np.zeros(n+1, dtype=np.float32)
coef = 1.0 - weight
prod = 1.0
for i in range(n, 0, -1):
distribution[i] = coef*prod
prod *= weight
distribution[0] = prod
return distribution
def exponential_weighted_average2(n, weight):
"""
指数加权平均: (1-weight)^n, weight*(1-weight)^(n-1), ..., weight*(1-weight), weight
"""
return exponential_weighted_average1(n, 1.0-weight)
if __name__ == '__main__':
# d = exponential_weighted_average2(20, 1)
# print(d)
pass
|
4eb6d703f0a855046438ea792f85f16e5b580282 | rafaelperazzo/programacao-web | /moodledata/vpl_data/107/usersdata/190/51583/submittedfiles/questao3.py | 96 | 3.5 | 4 | # -*- coding: utf-8 -*-
p=int(input('digite o numero p:'))
q=int(input('digite o numero q:'))
|
61cfb87777162c8330023e3f0a334427cbfdcbdd | unsalfurkanali/learningPython | /squareCalc.py | 474 | 3.96875 | 4 | def delta(a, b, c):
return b**2 - 4 * a * c
def calc(a, b, c):
root1 = (b**2 + delta(a, b, c)**0.5)/(2*a)
root2 = (b ** 2 - delta(a, b, c) ** 0.5) / (2 * a)
return root1, root2
print("Enter the equation cofficients: a, b, c")
a = int(input())
b = int(input())
c = int(input())
if delta(a, b, c) >= 0:
root1, root2 = calc(a, b, c)
print("The equation roots by: {} and {}".format(root1, root2))
else:
print("The equation haven't real roots")
|
d54f4f5030f594c2360b2a6b6aa7953e8614e4b3 | YiseBoge/competitive-programming | /weeks/week-2/day-7/non_decreasing_array.py | 1,040 | 3.734375 | 4 | # Copyright (c) 2021. This code is licensed to mire
# Copying and / or distributing without appropriate permission from author is
# illegal and would mount to theft.
# Please contact developer at miruts.hadush@aait.edu.et prior to
# copying/distributing to ask and get proper authorizations.
from typing import List
# Method implements non decreasing array leetcode challenge @https://leetcode.com/problems/non-decreasing-array
def non_decreasing(nums: List[int]) -> bool:
count = 0
for i in range(len(nums) - 1):
if not nums[i] <= nums[i + 1]:
if count < 1:
if i > 0 and nums[i - 1] > nums[i + 1]:
nums[i + 1] = nums[i]
count += 1
elif i > 0 and nums[i - 1] <= nums[i + 1]:
nums[i] = nums[i + 1]
count += 1
elif i == 0:
nums[i] = nums[i + 1]
count += 1
else:
return False
return True
print(non_decreasing([5, 7, 1, 8]))
|
2a459f2f08e90a199432662a675a78eae5256842 | rahulraj-code/guess-the-no. | /code.py | 1,299 | 4 | 4 | import random
x = random.randint(0,101)
def intro():
print("Welcome to he guessing game \n "
"I have a Number between 0 to 100 in my mind \n"
" Try guessing it \n Good luck")
def achivement(flag):
if flag<3:
print("Woow!!! You are a psychic")
elif flag>3 and flag <8:
print("Good Job ,You got it in {} guesses".format(flag))
elif flag >8 and flag<12:
print("finally done ,in {} tries".format(flag))
else :
print("OKay ,you took {} tries".format(flag))
guess =[0]
def run():
flag = 0
a = int(input(" Guess the number "))
if a == x:
print("yes Its {}".format(x))
flag += 1
while True:
a = int(input(" wrong. go again "))
if a == x:
print("yes Its {}".format(x))
break
elif a < 0 or a > 100:
print("Out of Bound")
guess.append(a)
if guess[-2] and abs(guess[-1]-x)<10:
if abs(x - a) < abs(x - guess[-2]):
print("warmer")
elif abs(a - x) > abs(x - guess[-2]):
print("colder")
else:
if abs(a - x) <= 10:
print('Hot')
else:
print('Cold')
flag += 1
return flag
intro()
achivement(run())
|
9d29c8afeb32c5385a248ae3266607129077ef9a | shadab4150/hackerrank_solutions | /Jumping on Clouds.py | 365 | 3.546875 | 4 | https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem
#!/bin/python3
n=int(input())
arr=list(map(int,input().split()))
def JumpOnClouds(arr):
count=0
i=0
while i<n-1:
if i<n-2 and arr[i+2]==0:
i=i+2
count+=1
else:
i=i+1
count+=1
return count
print(JumpOnClouds(arr))
|
9fdc9a7371c9c2a6a755b679098f9d3c21b05798 | ysyisyourbrother/My-Leetcode | /My-Leetcode/Python/20. 有效的括号【栈】.py | 520 | 3.734375 | 4 | class Solution:
def isValid(self, s: str) -> bool:
self.bracket = {
"(": ")",
"{": "}",
"[": "]"
}
stack = []
for c in s:
if self.bracket.get(c, False):
stack.append(c)
else:
if len(stack) > 0 and self.bracket[stack[-1]] == c:
stack = stack[:-1]
else:
return False
if len(stack) > 0:
return False
return True |
159072fd6d25a7a8ca3e1e9a2337cf8c8b0af9c7 | supragub/python-codecool | /18-Pairprogramming/Palindrome/test.py | 461 | 3.6875 | 4 | import unittest
from palindrome_module import palindrome
# Here's our "unit tests".
class PalindromeTestCase(unittest.TestCase):
def test_palindrome(self):
self.assertEqual(palindrome("Anna"), True)
self.assertEqual(palindrome("A nut for a jar of tuna"), True)
self.assertEqual(palindrome("Tom Hanks"), False)
self.assertEqual(palindrome("T"), True)
def main():
unittest.main()
if __name__ == '__main__':
main()
|
112e81c2201f4044ac8f807feff629a0a0c0d42c | LyricLy/python-snippets | /arbitrary_decorator.py | 1,304 | 3.640625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
an attempt to use any arbitrary expression as a decorator
per
https://docs.python.org/3/reference/compound_stmts.html#function-definitions
, not all expressions can be used as decorators. Just
"@" followed by a (maybe dotted) identifier, followed by an argument
list.
goal is to see if it's still possible
"""
if not __debug__:
raise AssertionError(
'debug mode must be enabled for the tests to run')
def deco(func):
"""
a dumb decorator which causes all arguments to be ignored
and returns 42
"""
def wrapped(*args, **kwargs):
return 42
return wrapped
@deco
def control():
return -1
assert control() == 42
class InvalidDecoratorFactory(int):
def __neg__(self):
return deco
thing = InvalidDecoratorFactory()
def control_2():
return -1
assert (-thing)(control_2)() == 42
try:
compile("""
@-thing
def control_3():
return -1
""", '<string>', 'exec')
except SyntaxError:
pass
else:
raise AssertionError('@-thing is valid, after all')
def id(x):
return x
try:
code = compile("""
@id(-thing)
def intervention():
return -1
""", '<string>', 'exec')
except SyntaxError:
raise AssertionError(
'identity failed to circumvent the decorator restriction')
g = dict(id=id, thing=thing)
exec(code, g)
assert g['intervention']() == 42
|
395cd0e1e0aa0531ef47b191137a34ce152c86ce | Aniruthan123/My-Own-Programs | /Banking.py | 6,004 | 3.921875 | 4 | import random
import time
print("Welcome To Mallaya Bank:")
time.sleep(0.44)
print("")
print("")
print("TO CREATE AN ACCOUNT,WAIT FOR 5 SECONDS WITHOUT TERMINATION")
time.sleep(5)
print("Enter the Details as per your aadhar card")
time.sleep(3)
b=int(input("Enter your 16 digit AADHAR NUMBER:"))
b = str(b)
d = input("Enter Your Name:")
if len(b)==16:
print('Yes, 16 numbers are there')
print(d)
e=int(input("Enter your Indian Phone Number: +91"))
c=input("Enter Your Plot number:")
f=input("Enter your street name:")
g=input("Enter your area name:")
h=input("Enter your City and State seperated by a comma:")
print("Congratulations" ,d, "Your account has been created in the name of:",d)
print("Your Mailing Address And Ph.no Will be:",c,",",f,",",g,",",h,",",e)
anum=0
acc = ""
for i in range(13):
num = (random.randint(0,9))
acc += str(num)
print("Your new account number is ",acc)
print("You will have a minimum account balance of Rs.500")
anum+=500
time.sleep(2)
def welcomeMessage():
print("Welcome Again:")
time.sleep(2)
print("ENTER 1 TO ATTAIN A DEBIT CARD OR A CREDIT CARD")
print("ENTER 2 TO APPLY FOR A LOAN:")
print("ENTER 3 FOR WITHDRAWLS OR DEPOSITS")
print("ENTER 7 FOR FOREIGN EXCHANGE")
print("ENTER 8 TO KNOW ABOUT YOUR A/C STATUS/BALANCE ")
output=int(input("Enter the required number:"))
return output
output = welcomeMessage()
if output==1:
DE=""
re=""
DE=input("ENTER DR TO APPLY FOR DEBIT CARD,ENTER CR TO APPLY FOR CREDIT CARD:")
if DE=="DR":
re=int(input("Enter your account number:"))
print("Welcome ",d)
cx = ""
for i in range(16):
nume = (random.randint(0,9))
cx += str(nume)
print("Your new debit card number is ",cx )
oo = ""
for i in range(3):
numer = (random.randint(0,9))
oo += str(numer)
print("Your CVV is:",oo)
WE=input("IF YOU WANT YOUR OWN PIN NUMBER,TYPE'YES',ELSE TYPE 'NO':")
if WE =='YES':
ddd=int(input("Enter Your New Pin:"))
print(ddd,"is your new pin")
else:
oo0 = ""
for i in range(4):
numeroid = (random.randint(0,9))
oo0 += str(numeroid)
print(oo0,"is your pin number")
welcomeMessage()
else:
eds=int(input("CREDIT CARD CHECK:Enter 1 if you are 21,and with a job with a 6 digit income,,,if you have an exception press 2"))
if eds==1:
print("you are eligible")
oo00 = ""
for i in range(17):
numeroid = (random.randint(0,9))
oo00 += str(numeroid)
print(oo00,"is your credit card number:")
WEd=input("IF YOU WANT YOUR OWN PIN NUMBER,TYPE'YES',ELSE TYPE 'NO':")
if WEd =='YES':
dddi=int(input("Enter Your New Pin:"))
print(dddi,"is your new pin")
else:
oo03 = ""
for i in range(5):
numeroid = (random.randint(0,9))
oo033 += str(numeroid)
print(oo03,"is your pin number")
oo11111=""
for i in range(4):
numerthala = (random.randint(0,9))
oo11111 += str(numerthala)
print("Your CVV is:",oo11111)
else:
print("Sorry,You aren't eligible")
elif output==2:
print("You will only be considered as a loan candidate only if your CIBIL is above 580:")
d09=int(input("ENTER YOUR CIBIL SCORE:"))
if d09<=580:
print("PLease have a minimum CIBIL score of 580 ")
else:
print("You are eligible")
lml=int(input("Enter the amount you wish to take as a loan"))
if lml<=400000:
print("The loan amount has been transferred to your account")
anum+=lml
gello=int(input("Enter 1 to continue else enter to 2 to stop"))
if gello==2:
print("end")
else:
print("Enter a different number")
welcomeMessage()
elif output==3:
print("Your account balance is ",anum)
the=int(input("Enter 1 to withdrawl or 2 to deposit"))
if the==1:
trey=int(input("ENTER THE AMOUNT YOU WISH TO WITHDRAWL:"))
if trey>anum:
print("Insufficient Funds")
else:
anum=anum-trey
print("Your withdrawl is succesful and your account balance is:",anum)
time.sleep(3)
welcomeMessage()
else:
Trey=int(input("ENTER THE AMOUNT YOU WISH TO DEPOSIT:"))
anum=anum+Trey
print("Your new account balance is:",anum)
time.sleep(2.88)
welcomeMessage()
elif output==7:
print("We have three foreign currencies to exchange;US dollars(23),Euros(34),Australian dollars(44)")
tyu=int(input("Enter the currenvey code given from above:"))
if tyu==23:
opi=int(input("Enter the INR amount you are willing to offer for the exchange:"))
fv=opi/76
print("The amount of dollars you will be getiing is:",fv)
elif tyu==34:
opt=int(input("Enter the INR amount you are willing to offer for the exchange:"))
fvy=opi/88
print("The amount of euros you will be getiing is:",fvy)
elif tyu==44:
opu=int(input("Enter the INR amount you are willing to offer for the exchange:"))
fgh=opu/55
print("The amount of aus dollars you will be getiing is:",fgh)
time.sleep(2.88)
welcomeMessage()
elif output==8:
print("Your account balance is",anum)
time.sleep(2.88)
welcomeMessage()
|
96904dd8bf0de26585927c44d7536aaf3017e63c | Robel2020/Password_validator | /oop_prac.py | 494 | 3.578125 | 4 | class PlayerChar:
def__init__(self, name, income):
self.name = name
self.income = income
def wage(self):
return self.income
def speak(self, lang):
print(f"{self.name} speaks {lang}")
class Members(PlayerChar):
def __init__(self,name, arrow):
self.arrow = arrow
def attack(self):
print(f"attacking with {self.arrow}")
def study(self, hours):
print(self)
player1 = PlayerChar('Tommas', 75)
print(player1) |
d4921ef2362a28d3f5cbdebb0f074c369627efcb | ox01024/python- | /013元组:戴上了枷锁的列表.py | 1,693 | 3.671875 | 4 | # 元组不可更换元素的列表
# yuanzu=(1,2,3,4,5,6,7) 创建元组也可以不用小括号
# yuanzu[1] 查看元组第一个元素
# yuanzu[5:]从第5个开始到最后一个
# yuanzu[:5] 从第一个到第五个
# yuanzu2=yuanzu[:] 拷贝
# 如果你需要创建一个只有一个元素的元组
# 你可以这样yuanzu=(1,)
# 如果你这样yuanzu=(1) 这不是一个元组
# 8*(8) 等于64
# 2*(1,) 等于(1,1)
# temp=1,2,3,4
# temp=temp[:2]+('8,')+temp[2:] 一共4个元素前面两个加上新元素再加后面两个组成新元组,贴上temp
# 当元组temp 被当作变量名贴在另一个元组上 原temp元组由于没有标签就会被回收
# del temp 删除整个temp元组
# 当我们希望内容不被轻易改写的时候,我们使用元组(把权力关进牢笼)。
# 当我们需要频繁修改数据,我们使用列表
# 元组固然安全,但元组一定创建就无法修改(除非通过新建一个元组来间接修改,但这就带来了消耗)
# 而我们人是经常摇摆不定的,所以元组只有在特殊的情况才用到,平时还是列表用的多
# 元组可用的方法
# count() 计算并返回指定元素的数量
# index() 寻找并返回参数的索引值
# 元组的内置函数:
# 比较两个元组的元素:operator.eq(temp1,temp2)(前提需import operator)
# 计算元组元素个数:len(temp1)
# 返回元组中元素最大值:max(temp1)
# 返回元组中元素最小值:min(temp1)
# 将列表转换为元组:tuple(list1)
# 元组的方法:
# index:这个方法返回某个参数在元组中的位置
# count:这个方法用来计算某个参数在元组中出现的次数
|
79b0724d24bd5107adef5b4026eaa665bfd4d0b7 | ipmach/TicTacToe_IA | /agent.py | 519 | 3.890625 | 4 | from abc import ABC, abstractmethod
class agent(ABC):
"""
A representation of the agent.
"""
agent_name = "agent"
agent_description = "no description avaliable."
@abstractmethod
def choose(board):
"""
Return the board with the move choose but the agent.
"""
return board
@abstractmethod
def do_rollout(board):
return None
@abstractmethod
def train_model(self, total_games, learning_rate =0.9, loadPre = True):
return None
|
e89de9fb1a3b2ff27ba16988213685376b7cccad | YariOvalleOrtega/python-lesson | /clase 5/mayor.py | 723 | 3.640625 | 4 | #promedio mas alto dentro de una función
numeros1 = [59, 58+5, 45-5, 12*2]
numeros2 = [54, 58+5, 45, 12+24]
numeros3 = [54+2, 58+5, 45, 12]
numeros4 = [4, 58+5, 45*2, 12]
# podria ser promedio_1 = sum(numeros1)/ len(numeros1)
promedio_1 = sum(numeros1)/4
promedio_2 = sum(numeros2)/4
promedio_3 = sum(numeros3)/4
promedio_4 = sum(numeros4)/4
def promedio():
if promedio_1 >= promedio_2 and promedio_2 >= promedio_3 and promedio_3 >= promedio_4:
print ('Promedio 1 es mayor')
elif promedio_2 >= promedio_3 and promedio_3 >= promedio_4:
print('Promedio 2 es mayor')
elif promedio_3 >= promedio_4:
print('promedio 3 es mayor')
else:
print ('promedio 4 es mayor')
promedio()
|
6069ced4148ac08f8c362dc32f7bc6ef5e370eba | Suyen-Shrestha/Python-Assignment-II | /Solution9.py | 728 | 4.125 | 4 |
def binary_search(sequence,item):
lower = 0
upper = len(sequence) - 1
while lower <= upper:
mid_index = (lower+upper) // 2
if sequence[mid_index] == item:
return mid_index
elif sequence[mid_index] < item:
lower = mid_index + 1
else:
upper = mid_index - 1
return -1
sample_li = [5,9,6,23,54,68,17,32]
print(f'The sample list: {sample_li}')
sample_li.sort() # sorting is require for performing binary search.
print(f'The list after sorting: {sample_li}')
print(f'The index of "17" in sorted list using binary search: {binary_search(sample_li,17)}')
print(f'The index of "2" in sorted list using binary search: {binary_search(sample_li,2)}') |
645676f906e6f3ea7a3ea6bf9e436ef6a3ef1e52 | yqfan/datascience_coursera_uw | /PA1/tweet_sentiment.py | 1,022 | 3.546875 | 4 | import sys
import json
def hw():
print 'Hello, world!'
def lines(fp):
print str(len(fp.readlines()))
def main():
# transform unicode to utf-8
reload(sys)
sys.setdefaultencoding('utf-8')
sent_fname = sys.argv[1]
tweet_fname = sys.argv[2]
#set up the scores dictionary
scores = {}
with open(sent_fname) as sf:
for line in sf:
term, score = line.split("\t")
scores[term] = int(score)
# for each tweet, look for its 'text' field
# sum up the score of each word according to scores dict
with open(tweet_fname) as tf:
for line in tf:
tweet = json.loads(line)
if 'text' in tweet:
tweetText = tweet['text']
# sc will be the score of this tweet
sc = 0
for k,v in scores.items():
if k in tweetText:
sc += v
print sc
sf.close()
tf.close()
if __name__ == '__main__':
main()
|
ff15363f750b4f78018c367ba4098a0d42e09942 | younghj/python-webparser | /DLhtmlToLocal.py | 2,171 | 3.53125 | 4 | #FUNCTION: DOWNLOADS ALL THE URLS FROM GETHTTP.PY IN HTML FORMAT
from urllib2 import urlopen
import re
import os
savepath2=os.getcwd().replace('\\','/')+'/opr/web/' #location of http pages saved
savefile2=lambda x : os.path.join(savepath2,x)
if not os.path.exists(savepath2):
os.makedirs(savepath2)
getpath2=os.getcwd().replace('\\','/')+'/opr/' #location of the txt with list of websites
getfile=lambda x : os.path.join(getpath2,x)
counter=[0]*11
fin=open(getfile('match.txt'),'r')
finC=open(getfile('matchchamp.txt'),'r')
foutF=open(savefile2('error.txt'),'w')
for url in fin.readlines(): #for each line of fin
store=re.findall('(?:.*)(20(?:0[2-9]|1[0-3]))(?:comp.*)',url,re.I) #identify what year the specific competition was and stores year into array called store
store=store[0] #array called store[0] is simplified to variable 'store'
counter[int(store)-2003]+=1 #keep track of number of elements per year
fpath=savefile2(str(store.replace('20',''))) #organizes each year into individual years
if not os.path.exists(fpath):
os.makedirs(fpath)
matchname=fpath+'/'+str(store)+' match '+str(counter[int(store)-2003])+'.html' #names the html file, in order of processing "<year> match (1..n).html"
fout=open(matchname,'w')
fout.write(url)
try: #try to the following and go to 'except' if it fails
site= urlopen(url).read() #store contents of the html page in 'site'
fout.write(site)
except:
fout.write("404 Error: Page was not found")
foutF.write(url)
fout.close()
#same except for championship
counter=[0]*11
foutF.write('\n')
for url in finC.readlines():
print url
store=re.findall('(?:.*)(20(?:0[2-9]|1[0-3]))(?:comp.*)',url,re.I)
store=store[0]
counter[int(store)-2003]+=1
fpath=savefile2(str(store.replace('20',''))+'/Championship')
if not os.path.exists(fpath):
os.makedirs(fpath)
matchnameC=fpath+'/'+str(store)+' champmatch '+str(counter[int(store)-2003])+'.html'
foutC=open(matchnameC,'w')
foutC.write(url)
try:
site= urlopen(url).read()
foutC.write(site)
print 'done'
except:
foutC.write("404 Error: Page was not found")
foutF.write(url)
foutC.close()
fin.close()
finC.close()
|
94a24c278107316d05e3613802ad993eba830abb | shuvava/python_algorithms | /design_patterns/enum_sample.py | 226 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
enum example
"""
from enum import Enum, auto
class Fruit(Enum):
APPLE = auto()
ORANGE = auto()
GUAVA = auto()
if __name__ == '__main__':
print(Fruit.APPLE)
|
75137bb51cdf7eef4db1ae60ead1fdb140979b90 | eloghin/Python-courses | /HackerRank/OOP_complex_numbers.py | 1,545 | 3.90625 | 4 | import math
import math
class Complex(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __add__(self, n):
a = self.a + n.a
b = self.b + n.b
return Complex(a, b)
def __sub__(self, n):
a = self.a - n.a
b = self.b - n.b
return Complex(a, b)
def __mul__(self, n):
#(ac-bd) + i(bc+ad)
a = self.a * n.a - self.b * n.b
b = self.b * n.a + self.a * n.b
return Complex(a, b)
def __truediv__(self, n):
#(ac + bd)/(c2 + d2) + (bc - ad)/(c2 + d2)i
denominator = n.a**2 + n.b**2
a = (self.a * n.a + self.b * n.b) / denominator
b = (self.b * n.a - self.a * n.b) / denominator
return Complex(a, b)
def mod(self):
#mod(a+bi) = sqrt(a**2 + b**2)
a = math.sqrt(self.a**2 + self.b**2)
b = 0.00
return Complex(a, b)
def __str__(self):
if self.b == 0:
result = "%.2f+0.00i" % (self.a)
elif self.a == 0:
if self.b >= 0:
result = "0.00+%.2fi" % (self.b)
else:
result = "0.00-%.2fi" % (abs(self.b))
elif self.b > 0:
result = "%.2f+%.2fi" % (self.a, self.b)
else:
result = "%.2f-%.2fi" % (self.a, abs(self.b))
return result
# c = map(float, input().split())
# d = map(float, input().split())
x = Complex(2, 1)
y = Complex(5, 6)
print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n') |
a8eef304eca17361a334fa67140bd8e540fdcad8 | 121121lol/python-qs | /39Pali.py | 104 | 3.640625 | 4 | s=list(input().split()[0])
def pali(s):
if s==s[::-1]:
return True
return False
print(pali(s)) |
327199fde2c0e65948c49dc44123715c3d46afed | catherinealvarado/data-structures | /algorithms/hackathon/first_section.py | 7,593 | 3.640625 | 4 | '''
This file contains problems from LeetCode that I have already solved.
I am doing a self hackathon where I answer as many questions as
possible within two hours.
(There are the current most popular questions on Leetcode.)
'''
from collections import deque
'''
1: Two Sum -
Given an array of integers, return indices of the two numbers such that they
add up to a specific target.
Assumptions:
You may assume that each input would have exactly one solution, and you may
not use the same element twice.
[1,9,5,8] sum = 17 output = [1,3]
[1,5,4,6,5] sum = 10 output = [5,5]
'''
def two_sum(lst,sum_tot):
diff_dic = {}
for ind,val in enumerate(lst):
if val in diff_dic:
return [diff_dic[val],ind]
else:
diff_dic[sum_tot-val] = ind
'''
292: Nim Game -
Given number of stones determine whether you will win the game
I can remove 1,2,3
example: 4 I will lose
3 <= 3 I win
4 - - - - No win
5 - - - - - Yes win
6 - - - - - - Yes win
7 - - - - - - - Yes
8 - - - - - - - - N
--- if youre a multiple of 4 you are guaranteed to win
'''
'''
344: Reverse a string -
Takes a string as a input and reverses the string.
'''
def rev_string(s):
rev = [list(word) for word in s.split(' ')]
for i in range(len(rev)):
curr = rev[i]
n = len(curr)
for j in range(n//2):
temp = curr[j]
curr[j] = curr[n-1-j]
curr[n-1-j] = temp
rev[i] = ''.join(rev[i])
return ' '.join(rev)
'''
136: Single number -
Given an array of integers, every element appears twice except for one.
Find that single one.
Your algorithm should have a linear runtime complexity. Could you implement
it without using extra memory?
[1,2,3,3,2,4,5,7,4,5,7] (we can use ^)
'''
def single_number(lst):
curr = lst[0]
for i in range(1,len(lst)):
curr = curr ^ lst[i]
return curr
'''
2: Add two numbers -
You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their nodes
contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except
the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
'''
class Node:
def __init__(self,val=None):
self.val = val
self.next = None
def add_linked_lists(l1,l2):
carry = 0
dummy = Node("dummy")
prev = dummy
while l1 or l2:
curr_sum = 0
curr_sum += carry
if l1:
curr_sum += l1.val
l1 = l1.next
if l2:
curr_sum += l2.val
l2 = l2.next
new_val = Node(curr_sum % 10)
carry = curr_sum // 10
prev.next = new_val
prev = new_val
if carry == 1:
prev.next = ListNode(1)
return dummy.next
'''
198: House Robber -
You are a professional robber planning to rob houses along a street. Each
house has a certain amount of money stashed, the only constraint stopping
you from robbing each of them is that adjacent houses have security system
connected and it will automatically contact the police if two adjacent
houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of
each house, determine the maximum amount of money you can rob tonight without
alerting the police.
[10,2,13,1,61,1] max_amount = 84
[20,1,1,20] max_amount = 40
'''
def house_robber(lst):
n = len(lst)
if not lst:
return 0
if n == 1:
return lst[0]
prev_prev = lst[0]
prev = max(prev_prev,lst[1])
for i in range(2,len(lst)):
temp = prev_prev + lst[i]
prev_prev = prev
prev = max(prev_prev,temp)
return prev
'''
219: Contains Duplicate II -
Given an array of integers and an integer k, find out whether there are two
distinct indices i and j in the array such that nums[i] = nums[j] and the
absolute difference between i and j is at most k.
[1,2,3,9,5,2] k = 3 {1,2,3,9}
'''
def contains_duplicate(lst,k):
if k <= 0:
return False
curr_nums = set()
for i in range(len(lst)):
if i > k:
curr_nums.remove(lst[i-k-1])
if lst[i] in curr_nums:
return True
else:
curr_nums.add(lst[i])
return False
'''
108: Convert Sorted Array to Binary Search Tree -
Given an array where elements are sorted in ascending order, convert it
to a height balanced BST.
[1,2,3,4,5,6,7,8]
'''
class TreeNode:
def __init__(self,val=None):
self.val = val
self.left = None
self.right = None
def sorted_arr_bin_search(lst):
if not lst:
return None
mid = len(lst)//2
root = TreeNode(lst[mid])
root.left = sorted_arr_bin_search(lst[:mid])
root.right = sorted_arr_bin_search(lst[mid:])
return root
'''
202: Happy Number -
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with
any positive integer, replace the number by the sum of the squares of its
digits, and repeat the process until the number equals 1 (where it will
stay), or it loops endlessly in a cycle which does not include 1. Those
numbers for which this process ends in 1 are happy numbers.
Given: 19
9*9 + 1*1 = 82
8*8 + 2*2 = 64 + 4 = 68
6*6 + 8*8 = 64 + 36 = 100
1*1 + 0*0 + 0*0 = 1
19 is a happy number!
'''
def find_squares_sum(n):
curr_sum = 0
while n:
last = n % 10
curr_sum += last*last
n = n//10
return curr_sum
def is_happy(num):
slow = num
fast = find_squares_sum(find_squares_sum(slow))
while slow != fast:
slow = find_squares_sum(slow)
fast = find_squares_sum(find_squares_sum(fast))
return slow == 1
'''
190: Reverse Bits -
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as
00000010100101000001111010011100), return 964176192 (represented in binary as
00111001011110000010100101000000).
'''
def reverse_bits(num):
rev = 0
mask = 0xFFFFFFFF
num = num & mask
for i in range(0,32):
rev = rev + (num & 1)
num = num >> 1
if i < 31:
rev = rev << 1
return rev
'''
217: Contains Duplicate -
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in
the array, and it should return false if every element is distinct.
'''
def contains_duplicate(lst):
distinct_nums = set()
for num in lst:
if num in distinct_nums:
return True
distinct_nums.add(num)
return False
'''
20: Valid Parentheses -
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all
valid but "(]" and "([)]" are not.
'''
def valid_parenthesis(st):
stack = deque()
for char in st:
if char == '(' or char == '{' or char == '[':
stack.append(char)
elif stack:
last_left = stack.pop()
if (char == ')' and last_left != '(') or \
(char == ']' and last_left != '[') or \
(char == '}' and last_left != '{'):
return False
else:
return False
return len(stack) == 0
'''
371: Sum of Two Integers - RETURN TO THIS PROBLEM!!
Calculate the sum of two integers a and b, but you are not allowed to use
the operator + and -.
4 + 3 = 7
100
11
111
'''
|
9e9ef3d44e7c8b71fb196a0e4fce3789d69cffb6 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4012/codes/1671_1103.py | 280 | 3.984375 | 4 | x = float(input("digite x: "))
a = float(input("digite a: "))
b = float(input("digite b: "))
if ((a < x) and (x < b)):
print(x, "pertence ao intervalo", a ,",", b)
elif (b <= a):
print("Entradas",a ,"e", b, "invalidas")
else:
print(x, "nao pertence ao intervalo" ,a ,",", b)
|
7d579583ce9747c2d838eb9b3c2a039a888a72ac | MichalKacprzak99/wfiis-2021-graphs-and-their-uses | /grafy/project2/degree_sequence.py | 1,146 | 3.875 | 4 | import numpy as np
import random
def degree_sequence_checker(a: list) -> bool:
"""
Check if a degree sequence is a graphical graph
Parameters
----------
a : list
The degree sequence the program evaluates
Returns
-------
bool
Boolean value representing whether the degree sequence is a graphical graph
"""
a = np.asarray(a)
if a[a % 2 == 1].size % 2:
return False
while True:
a[::-1].sort()
if a[a == 0].size == a.size:
return True
if a[0] < 0 or a[0] >= a.size or a[a < 0].size > 0:
return False
for (i,), el in np.ndenumerate(a):
if 0 < i <= a[0]:
a[i] = el - 1
a[0] = 0
if __name__ == "__main__":
exampleCorrect = [4, 2, 2, 3, 2, 1, 4, 2, 2, 2, 2]
exampleCorrectFromLecture1 = [6, 4, 3, 2, 2, 2, 1, 1]
exampleCorrectFromLecture2 = [6, 5, 4, 3, 2, 1, 1]
exampleCorrectFromLecture3 = [6, 4, 3, 3, 2, 2, 2]
exampleCorrectFromLecture0 = [4, 2, 3, 2, 3, 2]
exampleWrong = [4, 4, 3, 3, 1, 2]
print(degree_sequence_checker(exampleCorrectFromLecture3))
|
2f6ce759502d77f8121c09a014daceebcfd3915a | joestalker1/leetcode | /src/main/scala/common_lounge/Variation.py | 457 | 3.921875 | 4 | def find_pairs(arr, diff):
pairs = 0
i = 0
j = 0
while i < len(arr) and j < len(arr):
while j < len(arr) and abs(arr[j] - arr[i]) < diff:
j += 1
if j < len(arr):
pairs += (len(arr) - j)
i += 1
return pairs
s = input()
arr = s.split()
n = int(arr[0])
k = int(arr[1])
s = input()
arr = s.split()
#arr = [3,1,3]
#k = 1
arr = list([int(a) for a in arr])
arr.sort()
print(find_pairs(arr, k))
|
414e86fc24b09921fd837255bd7dd4d8a532d841 | summer-vacation/AlgoExec | /jianzhioffer/getIntersectionNode.py | 1,478 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
File Name: getIntersectionNode.py
Author : jynnezhang
Date: 2020/5/5 1:54 下午
Description:
两个链表的第一个公共节点
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA, headB) -> ListNode:
if headA is None or headB is None:
return None
lensA, lensB = 0, 0
preA, preB = headA, headB
while preA:
lensA += 1
preA = preA.next
while preB:
lensB += 1
preB = preB.next
if lensA < lensB:
headA, headB = headB, headA
more = lensB - lensA
else:
more = lensA - lensB
while more and headA:
headA = headA.next
more -= 1
while headA and headB:
if headA == headB:
return headA
else:
headB = headB.next
headA = headA.next
return 0
# listA = [4,1,8,4,5], listB = [5,0,1,8,4,5],
listA = ListNode(4)
listA.next = ListNode(1)
listA.next.next = ListNode(8)
listA.next.next.next = ListNode(4)
listB = ListNode(5)
listB.next = ListNode(0)
listB.next.next = ListNode(1)
listB.next.next.next = listA.next.next
print(Solution().getIntersectionNode(listA, listB))
|
50dacc39a243a2553da8e3e676882aa038177463 | 71unxv/Python_DTG | /fungsi_prima.py | 1,355 | 4.09375 | 4 | """ Created on : Sun Mar 10 15:16:46 2019
author:
github.com/71unxv
github.com/LutfiZakaria
Note:
Python for Geophysical Data Processing and Inverse Problem
_______________________________________________________________________________
Cheers!
"""
# Import Library
# ==============================================================================================================
# Function
# ==============================================================================================================
def isPrime(x):
# stop = False
count = 0
isprima = True
fac_num = 0
while count<=10:
count += 1
if x % count == 0:
fac_num += 1
if (fac_num > 2) :
isprima = False
return isprima
if x == 1:
isprima = False
return isprima
def listPrime(x):
for ii in range(len(x)):
if isPrime(x[ii]):
print(str(x[ii]) + " is Prime")
else :
print(str(x[ii]) + " is not Prime")
a = 1
print(isPrime(a))
a = 4
print(isPrime(5))
import numpy as np
a = np.arange(1,20)
listPrime(a)
# run code! Run!!
# ==============================================================================================================
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.