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 |
|---|---|---|---|---|---|---|
93ada3bcca88672c3e9d9ef336fbe5c128c14286 | lailacampos/Python-for-beginners-Udemy | /Section23 - Regular Expressions/Real Python/Part_2/regex_utility_functions.py | 2,639 | 4.1875 | 4 | # Utility Functions
# https://realpython.com/regex-python-part-2/#utility-functions
# re.split() Splits a string into substrings using a regex as a delimiter
# re.escape() Escapes characters in a regex
import re
# re.split(<regex>, <string>, maxsplit=0, flags=0)
# Splits a string into substrings.
# re.split(<regex>, <string>) splits <string> into substrings using <regex> as the delimiter and returns the substrings as a list.
# Splits the specified string into substrings delimited by a comma (,), semicolon (;), or slash (/) character, surrounded by any amount of whitespace
regex = r'''
\s* # Optional whitespace
[,;/-] # Delimiters
\s* # Optional whitespace
'''
print(re.split(regex, 'foo-bar , quiz ; baz ', flags=re.VERBOSE)) # ['foo', 'bar', 'quiz', 'baz ']
# If <regex> contains capturing groups, then the return list includes the matching delimiter strings as well:
print(re.split('(\s*[,;/-]\s*)', 'foo-bar , quiz ; baz ')) # ['foo', '-', 'bar', ' , ', 'quiz', ' ; ', 'baz ']
# Split <string> apart into delimited tokens, process the tokens in some way, then piece the string back together using the same delimiters that
# originally separated them:
string = 'foo,bar ; baz / quiz'
regex = r'(\s*[,;/-]\s*)'
a = re.split(regex, string) # a = ['foo', ',', 'bar', ' ; ', 'baz', ' / ', 'qux']
# Enclose each token in <>'s
for i, s in enumerate(a):
# Will be True for the tokens but not the delimiters.
# As in the delimiters will match, but the words won't. So enclose that which doesn't match.
if not re.fullmatch(regex, s):
a[i] = f'<{s}>'
print(a[i]) # [<foo>, <bar>, <baz>, <quiz>]
a = ''.join(a)
print(a) # <foo>,<bar> ; <baz> / <quiz>
######################################################################################
# re.escape(<regex>)
# Escapes characters in a regex.
# re.escape(<regex>) returns a copy of <regex> with each nonword character (anything other than a letter, digit, or underscore) preceded by a
# backslash.
# It's useful if you’re calling one of the re module functions, and the <regex> you’re passing in has a lot of special characters that you want
# the parser to take literally instead of as metacharacters.
print(re.match('foo^bar(baz)|quiz', 'foo^bar(baz)|quiz')) # None
# Escaping with \ character:
print(re.match('foo\^bar\(baz\)\|quiz', 'foo^bar(baz)|quiz')) # match = 'foo^bar(baz)|quiz'
# Using re.escape():
print(re.match(re.escape('foo^bar(baz)|quiz'), 'foo^bar(baz)|quiz')) # match = 'foo^bar(baz)|quiz'
|
b1dde3cc0a862207a2e8d822445fccf3bb2cd76e | ivanovishx/algorithms_exercises_ivan | /CTCI_book/CH1 - Arrays and strings/1.9.py | 807 | 4.46875 | 4 | # 1.9 String Rotation: Assume you have a method isSubstring which checks if one word
# is a substring of another. Given two strings, S1 and S2, write code to check if S2 is a rotation of S1
# using only one call to isSubstring (e.g., "waterbottle" is a rotation of u "erbottlewat").
def isSubstring(str1, str2):
return str1.find(str2) != -1
def isRotation(str1, str2):
# startIndex = isSubstring(str1, str2)
if len(str1) == len(str2):
# print("-",str1+str1,"--")
# print("Hi")
return isSubstring(str1+str1, str2)
return False
#Start
print (isRotation("waterbottle", "erbottlewat"))
a = "waterbottlewaterbottle"
print(a.find("F"))
print(a.find("f"))
print(a.find("n"))
print(a.find("ness"))
print(a.find("ess"))
print(a.find("z"))
print(a.find("Homer"))
print(a.find("erbottlewat"))
|
deb03e16b591bd2d56e156943b83af3ca3d96112 | fedhere/UInotebooks | /dataWrangling/aSimplePythonThatWritesToCSV.py | 1,584 | 4.34375 | 4 | # Author: federica bianco, NYU, September 2016
##############################
# Code written to demonstrate ho to pass arguments to a python script
# for HW2 of PUI2016
# http://cosmo.nyu.edu/~fb55/PUI2016
##############################
# put the name of the outut file as input argument:
# i.e. run the code as
# python aPythonScriptThatWritesToCSV.py mycvs.csv
###########
# the next line import packages that change the python 2 print function
# so that it require the same syntax as python 3
# thus the code will work both in python 2 and python 3
from __future__ import print_function
# the next import allows me to read line input arguments
import sys
# this line checks how many arguments are passed to python
# the arguments are stored in sys.argv which is a list
# the first argument is the name of the code
# so sys.argv is a list with at least one element
# with the output filename in input it will be a list of 2
# if you add more than one word as argument it will give you an error as well
if not len(sys.argv) == 2:
print("Invalid number of arguments. Run as: python aPythonScriptThatWritesToCSV.py mycvs.csv")
sys.exit()
# this line opens a file for writing using the name you chose
# the "w" tells it you are opening for writing, not reading
fout = open(sys.argv[1], "w")
# this line prints the numbers from 1 to 10 separated by commas
# 10 times in 10 rows
# to your output file
# notice the "\n" character at the end of each line:
# that's the line break
for i in range(10):
fout.write("1,2,3,4,5,6,7,8,9,10\n")
# that's a way to write to a csv file!
|
32ea2cdb6e0b4c07dfce39306e0f7a76dfe85624 | felixglush/optimal_covering | /timer.py | 774 | 3.9375 | 4 | """
Contains a simple timer function, to be called as a decorator.
Usage:
------
- import
::
from timer import timeit
- define function with timeit used as decorator
::
@timeit
def some_func(x):
...
- call the function
::
some_func(5)
- prints function name and execution time
::
>>> "some_func" 12.09 ms
"""
from time import time
def timeit(method):
def timed(*args, **kw):
ts = time()
result = method(*args, **kw)
te = time()
if 'log_time' in kw:
name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int((te - ts) * 1000)
else:
print('%r %2.2f ms' % (method.__name__, (te - ts) * 1000))
return result
return timed
|
3f0d3b579fe20d60f8500195cdad2e106bc0fcaf | rakibsarwer/Python-Problem-Solving-Shubin-s-Book-First-part1 | /turtleDesign.py | 241 | 3.859375 | 4 | import turtle
turtle.shape('turtle')
turtle.color("blue")
turtle.speed(5)
counter = 0
while counter < 36:
for i in range(4):
turtle.forward(100)
turtle.left(90)
turtle.right(10)
counter+=1
turtle.exitonclick() |
c909d8d94d6e1ce524fcdc9cf3cdfb4310bc54bf | shahpriyesh/PracticeCode | /ArrayQuestions/SortedSquares.py | 714 | 3.53125 | 4 | class SortedSquares:
def __init__(self):
pass
# O(n) time, O(n) space [ Two Pointer approach ]
def sortedSquares(self, A):
result = []
front = 0
rear = len(A)-1
while front <= rear:
if abs(A[front]) >= abs(A[rear]):
result.insert(0, A[front] ** 2)
front += 1
else:
result.insert(0, A[rear] ** 2)
rear -= 1
return result
# O(nlgn) time, O(n) space [ sort approach ]
def sortedSquares2(self, A):
result = [n**2 for n in A]
result.sort()
return result
object = SortedSquares()
A = [-4,-1,0,3,10]
print(object.sortedSquares2(A)) |
f725c17e4d21d4db470272f86ae49bfa8e010db8 | Nandheeswarraja/mycoding | /vowel.py | 176 | 4.0625 | 4 | ch=int(input("Enter a character"))
if(ch==a,e,i,o,u):
print("the letter is vowel")
elif(ch==Z,T,B,G,H):
print("the letter is a consonant")
else:
print("the letter is invalid")
|
a5f827dc9b68cdaf5b6ca638130e331f6471fb87 | mbellitti/lp | /wordplay.py | 962 | 3.84375 | 4 | fin = open('/home/ksarnek/codice/python/wordsEn.dat')
def has_no_e(str):
for letter in str:
if letter == "e":
return False
return True
def avoids(str, forbidden):
for letter in str:
if letter in forbidden:
return False
return True
def uses_only(word, allowed):
for letter in word:
if letter not in allowed:
return False
return True
def triple_double(word):
if len(word) < 6:
print("Word too short")
else:
for i in range(len(word)-5):
if word[i] == word[i+1] and word[i+2] == word[i+3] and word[i+4] == word[i+5]:
return True
return False
def in_fin(of, word):
for line in of:
par = line.strip()
if par == word:
return True
return False
#we = 0
#woe = 0
#for line in fin:
# word = line.strip()
# we += 1
# if has_no_e(word):
# woe += 1
# #print(word)
|
e17123e0eadf5e2f221ea6841aca9d204c5d1bdd | AlgorithmOnline/jaeeun | /1_202010119.py | 2,439 | 3.546875 | 4 | def findFunc(x1,y1,x2,y2):
a=findA(x1,y1,x2,y2)
flag = False # 특이
if a==float('inf'):
flag = True
#print("x=",x1)
if y1==y2:
return x1,y1,True
return x1,float('inf'), True
b= findB(x1,y1,a)
#print(a,"x+",b,"=y")
return a,b,False
def findA(x1,y1,x2,y2):
if x1==x2:
return float('inf')
else:
return (y2-y1)/(x2-x1)
def findB(x1,y1,a):
return y1-a*x1
def findCrossPoint(x1,y1,x2,y2,x3,y3,x4,y4):
a1,b1,flag1= findFunc(x1,y1,x2,y2)
a2,b2,flag2= findFunc(x3,y3,x4,y4)
if flag1 and b1==float('inf'):# x=a1
return a1,a2*a1+b2
elif flag1: # (a1,b1)
return x1,x2
if flag2 and b2==float('inf'):
return a2,a1*a2+b1
elif flag2:
return x3,x4
else:
# print(a2,b2,a1,b1)
if a2!=a1:
return (b1-b2)/(a2-a1), (b1*a2-b2*a1)/(a2-a1)
else: # 일직선
# print("어쩌지")
if min(x1,x2)<=max(x3,x4) and min(x3,x4)<=max(x1,x2) and min(y1,y2)<=max(y3,y4) and min(y3,y4)<=max(y1,y2):
if min(x1,x2)==max(x3,x4):
return min(x1,x2),min(x1,x2)*a1+b1
if max(x1,x2)==min(x3,x4):
return max(x1,x2),max(x1,x2)*a1+b1
else:
return float('inf'),float('inf')
x1, y1, x2, y2=map(int, input().split())
x3, y3, x4, y4=map(int, input().split())
xans=float('inf')
yans=float('inf')
answer=0
didanswer=False
def ccw(x1,y1,x2,y2,x3,y3):
tmp= (x2-x1)*(y3-y1)- (x3-x1)*(y2-y1)
if tmp> 0:
return 1
elif tmp < 0:
return -1
else:
return 0
if ccw(x1,y1,x2,y2,x3,y3) * ccw(x1,y1,x2,y2,x4,y4)==0 and ccw(x3,y3,x4,y4,x1,y1) * ccw(x3,y3,x4,y4,x2,y2)==0:
didanswer=True
if min(x1,x2)<=max(x3,x4) and min(x3,x4)<=max(x1,x2) and min(y1,y2)<=max(y3,y4) and min(y3,y4)<=max(y1,y2):
answer=1
xans, yans=findCrossPoint(x1,y1,x2,y2,x3,y3,x4,y4)
if ccw(x1,y1,x2,y2,x3,y3) * ccw(x1,y1,x2,y2,x4,y4)<=0 and ccw(x3,y3,x4,y4,x1,y1) * ccw(x3,y3,x4,y4,x2,y2)<=0:
if not didanswer:
xans, yans=findCrossPoint(x1,y1,x2,y2,x3,y3,x4,y4)
answer=1
print(answer)
if xans!=float('inf') and yans!=float('inf'):
if xans%1==0:
xans=round(xans)
if yans%1==0:
yans=round(yans)
print(xans,yans)
xans=float('inf')
yans=float('inf')
|
ad248a44445dae2d867076c3655195e1e3c9c014 | anilece/infytq-PF | /CELSIUS_TO_FARHENHEIT.py | 260 | 3.921875 | 4 |
def convert_temp(Celsius_val):
Farhenheit_val=0
Farhenheit_val=((9/5)*Celsius_val)+32
return Farhenheit_val
Celsius_val=98
## for run time input use Celsius_val=input()
Result=0
Result=convert_temp(Celsius_val)
print("Farhenheit value-",Result)
|
7c8cf9b0d8e68eb33908a590ef8c6fca9ab82a71 | brcabral/curso-python-essencial | /ppe/session13_leitura_escrita_arquivo/exemplos/seek_e_cursor.py | 2,196 | 4.6875 | 5 | """
Seek e Cursor
seek() -> É utilizado para movimentar o cursor pelo arquivo
"""
arquivo = open('texto.txt')
print(f'Conteúdo do arquivo: {arquivo.read()}')
print(f'Conteúdo do arquivo: {arquivo.read()}')
# seek() -> A função seek() é utilizada para movimentar o cursor pelo arquivo.
# Ela recebe um parâmetro que indica a nova posição do cursor.
# Movimenta o cursor para a posição 0 (zero - início) do arquivo
arquivo.seek(0)
print(f'Conteúdo do arquivo: {arquivo.read()}')
arquivo.seek(22)
print(f'Conteúdo do arquivo: {arquivo.read()}')
print("--------------------------------------------------")
arquivo = open('texto.txt')
# readline() -> Ler o conteúdo do arquivo linha a linha
print(f'Conteúdo da 1ª linha: {arquivo.readline()}')
print(f'Conteúdo da 2ª linha: {arquivo.readline()}')
print(f'Conteúdo da 3ª linha: {arquivo.readline()}')
print(f'Conteúdo da 4ª linha: {arquivo.readline()}')
print("--------------------------------------------------")
arquivo = open('texto.txt')
# readlines() -> Ler o conteúdo do arquivo e retorna uma lista, onde cada linha é um elemento da lista
print(f'Lista com o conteúdo do arquivo: {arquivo.readlines()}')
print("--------------------------------------------------")
"""
OBS.: Quando abrimos um arquivo é criada uma conexão entre o arquivo no disco e o programa.
Essa conexão é chamada de streaming. Ao finalizar os trabalhos com o arquivo devemos fechar
essa conexão, para isso utilizamos a função close()
"""
# Abrir o arquivo
arquivo = open('texto.txt')
# Trabalhar com o arquivo
print(f'Conteúdo do arquivo: {arquivo.read()}')
# arquivo.closed -> Verifica se o arquivo está aberto ou fechado
print(f'O arquivo está fechado? {arquivo.closed}')
# Fechar o arquivo
arquivo.close()
print(f'O arquivo está fechado? {arquivo.closed}')
# OBS.: Se tentarmos manipular um arquivo fechado, teremos um ValueError
print("--------------------------------------------------")
arquivo = open('texto.txt')
# Limitar a quantidade de caracteres lido
print(f'Limitando a leitura do arquivo a 56 caracteres: {arquivo.read(56)}')
print(f'Continuar lendo (10) o arquivo do 57 caractere: {arquivo.read(10)}')
|
7ccda61b66afeb43310bef28c8dd6b2724a14b51 | ZiadAlmuhrij/Python-Saudi-Dev-Org | /11.py | 163 | 3.96875 | 4 | x = 5
y = 6
print (x < 4 or x > 8)
x =["apple" , "orange"]
y =["apple" , "orange"]
z = x
print(x is not z)
print(x is not y)
print(x != z)
print("orange" in x) |
083ba07de64972ef7df2750710ab00059df2e21c | LarisaOvchinnikova/python_codewars | /Speed Control.py | 275 | 3.546875 | 4 | # https://www.codewars.com/kata/56484848ba95170a8000004d/train/python
def gps(s, x):
if len(x) <= 1:
return 0
distances = [abs(x[i] - x [i - 1]) for i in range(1,len(x))]
hours = s/3600
speed = [dist/hours for dist in distances]
return max(speed) |
684ec3e53330ab0c2b4f3982ebb330eb12af5790 | Dmitry1212/PythonBase | /dz5_3.py | 1,395 | 3.875 | 4 | # 3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов.
# Определить, кто из сотрудников имеет оклад менее 20 тыс.,
# вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников.
poor_salary = 20000
try:
file = open('оклады.txt', 'r', encoding='utf-8')
# с указанием кодировки выдавал ошибку, т.к. файл содавался по умолчанию в кодировке windows-1251
content = file.read().splitlines() # чтобы без спец символов переноса строки было
print(content)
print(f'Оклад менее {poor_salary} рублей:')
sum = 0 # суммы окладов
cnt = 0 # число сотрудников
for i in content:
if i != '':
temp = i.split()
if float(temp[1]) <= poor_salary:
print(f'{temp[0]}')
sum += float(temp[1])
cnt += 1
print(f'Средняя заработная плата: {sum / cnt:.2f}')
file.close()
except:
print('Ошибка чтения файла')
|
4fc117b30e6403c21d831e7c651e033792771f7e | WestFive/Python | /day-2/test1.py | 177 | 3.84375 | 4 | name = "luss"
if name is "Buu":
print("hi buu")
elif name is "lucy":
print("hi lucy")
elif name is "jay":
print("hi jay")
else:
print(" no one named %s"%name)
|
4097eff1e1744ff25eab16f7f43c28193ab98b63 | Kantheesh/Learning-Python | /str5.py | 256 | 3.859375 | 4 | # startswith
# endswith
inp = "ajay kumar"
out = inp.startswith("aj")
print(out)
out = inp.startswith("jay")
print(out)
# inp1 = "print('a')"
inp1 = "# isdecimal -> given a string, check if it is decimal"
out = inp1.startswith("#")
print(out) |
bfb13c7b52be2857e4b38664df7cfea0c8309512 | Ademvp9/Lab-111 | /Práctica 2/Ejercicio 1.py | 373 | 3.984375 | 4 | print("Ingrese el tiempo disponible en segundos: ")
x=int(input())
print("Ingrese el trabajo representado en horas, segundo, minutos")
h=int(input("Ingrese las horas: "))
m=int(input("Ingrese los minutos: "))
s=int(input("Ingrese los segundos: "))
h=h*60*60
m=m*60
z=h+m+s
if z>x:
print("El trabajo no se puede realizar")
else:
print("El trabajo se pude realizar")
|
10009f65d1e1c67732076eea969b8a3beadeb7f2 | Adityanagraj/infytq-previous-year-solutions | /Prefix and Suffix.py | 493 | 3.890625 | 4 | """
A non empty string containing only alphabets. Print length of longest prefix in the string
which is same as suffix without overlapping.Else print -1 if no prefix or suffix exists.
>>Input 1
Racecar
>>Output 1
-1
>>Input 2
aaaa
>>Output 2
2
"""
string=input()
length=len(string)
mid=int(length)//2
m=-1
for i in range(mid,0,-1):
pre=string[0:i]
suf=string[length-i:length]
if (pre==suf):
print(len(suf))
break
else:
print(m) |
0e4f1a90d19907b891b6fb1746f979cbecde61ff | wann31828/leetcode_solve | /python_solution/119.py | 993 | 3.890625 | 4 | '''
119. Pascal's Triangle II
Easy
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
'''
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
cur = [1,1]
if rowIndex == 0:
return [1]
elif rowIndex == 1:
return cur
else:
for i in range(2,rowIndex+1):
pre = cur[:]
#cur = []
for j in range(i+1):
#i[n] = i-1[n-1] + i-1[n]
if j == 0:
cur[j] =1
elif j == i:
cur.append(1)
else:
cur[j] = pre[j-1] + pre[j]
#print(cur)
return cur
|
1ead8d6df4cdee8a3e2c8a9a4fe2abfffe3a2cf2 | cofinoa/cfdm | /cfdm/data/numpyarray.py | 1,077 | 3.609375 | 4 | from . import abstract
from ..core.data import NumpyArray as core_NumpyArray
class NumpyArray(abstract.Array, core_NumpyArray):
'''An underlying numpy array.
'''
def __getitem__(self, indices):
'''x.__getitem__(indices) <==> x[indices]
Returns a subspace of the array as an independent numpy array.
The indices that define the subspace must be either `Ellipsis` or a
sequence that contains an index for each dimension. In the latter
case, each dimension's index must either be a `slice` object or a
sequence of two or more integers.
Indexing is similar to numpy indexing. The only difference to numpy
indexing (given the restrictions on the type of indices allowed) is:
* When two or more dimension's indices are sequences of integers
then these indices work independently along each dimension
(similar to the way vector subscripts work in Fortran).
.. versionadded:: 1.7.0
'''
return self.get_subspace(self._get_component('array'), indices,
copy=True)
#--- End: def
#--- End: class
|
e40914b3394dc7eea4c4f373340538fa38f383bc | Harshilpatel134/cs5590_python_deep_learning | /Lab3/Scource/lab3/task1.py | 1,910 | 3.75 | 4 | import csv
import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
dates = []
mopen = []
def getdata(fn):
with open(fn, 'r') as csvfile:
csvfr = csv.reader(csvfile)
next(csvfr) # skipping column names
for row in csvfr:
r=row[0].split("-")
dates.append(int(r[0]+r[1]+r[2]))
print(int(r[0]+r[1]+r[2]))
print(float(row[1]))
mopen.append(float(row[1]))
return
def splot(dates, mopen):
linear_mod = linear_model.LinearRegression()
dates = np.reshape(dates, (len(dates), 1)) # converting to matrix of n X 1
mopen = np.reshape(mopen, (len(mopen), 1))
linear_mod.fit(dates, mopen) # fitting the data points in the model
plt.scatter(dates, mopen, color='blue') # plotting the initial datapoints
plt.xlabel("month.year")
plt.ylabel("price")
plt.plot(dates, linear_mod.predict(dates), color='red', linewidth=3) # plotting the line made by linear regression
plt.show()
return
def predict_price(dates, mopen, x):
linear_mod = linear_model.LinearRegression() # defining the linear regression model
dates = np.reshape(dates, (len(dates), 1)) # converting to matrix of n X 1
mopen = np.reshape(mopen, (len(mopen), 1))
linear_mod.fit(dates, mopen) # fitting the data points in the model
predicted_mintemp = linear_mod.predict(x)
return predicted_mintemp[0][0], linear_mod.coef_[0][0], linear_mod.intercept_[0]
getdata('NASDAQComposite.csv') # calling get_data method by passing the csv file to it
splot(dates, mopen)
# image of the plot will be generated. Save it if you want and then Close it to continue the execution of the below code.
print("predicted values are:")
(predicted_price, coefficient, constant) = predict_price(dates, mopen, 20171011)
print("The stock open price on 2017/10/11 is: $", str(predicted_price))
|
25bf66ede52af033e5fc728760ecc02fcae70737 | JoeSamyn-GCU/305_RungeKutta | /main.py | 9,996 | 3.828125 | 4 | """
Author: Joe Samyn
Class: CST-305
Professor: Dr. Citro
Creation Date: 1.29.21
Last Revision Date: 1.31.21
Purpose: The purpose of this program is to solve the ordinary differential equation: y' = y/(e^x) - 1. The Equation
is solved using the Runge-Kutta algorithm and the ODEint package from SciPy. The results are compared and plotted using
the MatPlotLib library.
"""
import pandas as pd
import numpy as np
import datetime as dt
import matplotlib.pyplot as plt
from scipy.integrate import odeint as ode
def find_k_sum(y, x, dx, kn, prev_kval):
"""
Finds the sum of all the K values in the Runge-Kutta 4th order algorithm
Parameters
----------
y: float
Yn value
x: float
Xn value
dx: float
Step size
kn: int
K being solved (K1, K2, K3, or K4)
prev_kval: float
Value of the previous K (Kn-1)
"""
# If calculating K4
if kn >= 4:
# Calculate K4
k = (y + (dx*prev_kval))/(np.exp(x + dx) - 1)
return k
# If calculating K2 or K3
elif kn == 2 | kn == 3:
# Find dx midpoint
dx_mid = dx/2
# Calculate X at midpoint
x_temp = x + dx_mid
# Calculate Y at midpoint
y_temp = y + (dx_mid * prev_kval)
# Calculate K value with calculated X and Y values above
k = (y_temp/(np.exp(x_temp) - 1))*2
# Return K plus the next K value using recursion
return k + find_k_sum(y, x, dx, kn + 1, k)
# If calculating K1 just calculate using initial ODE
else:
k = y/(np.exp(x) - 1)
# Return K plus sum of all other calculated K values
return k + find_k_sum(y, x, dx, kn + 1, k)
def solve_rk(y, x, dx, n):
"""
Solves the differential equation using the Runge-Kutta method
ODE: y' = y/(e^x - 1)
Parameters
----------
y: int
initial condition for y
x: int
initial condition for x
dx: float
step size
n: int
The number of x and y values to calculate using Runge-Kutta algorithm
Returns
----------
float[][]
2D float containing all x & y values calculated
"""
# Initialize the calculated XY list with Y0 and X0
calculated_xy = [[x, y]]
# Set curr_y to Y0
curr_y = y
# Set curr_x to X0
curr_x = x
# Loop through and solve RK for Xn and Yn
for i in range(1, n):
# Calculate Yn
curr_y = curr_y + (dx / 6) * find_k_sum(curr_y, curr_x, dx, 1, 0)
# Calculate Xn
curr_x = curr_x + dx
# Append Xn and Yn to list
calculated_xy.append([curr_x, curr_y])
# return results of RK algorithm in list
return calculated_xy
def calculate_error(rk_calcs, odeint_calcs):
"""
Calculates the error between the Runge-Kutta method of solving differential equations and
the odeint method for solving differential equations.
Parameters
----------
rk_calcs: float[][]
Calculations generated from the RK method
odeint_calcs: float[][]
Calculations generated from the ODEint method
Returns
----------
double[]
Array containing error decimal for each Xn and Yn
"""
# Initialize error list
errors = []
# Loop through rk_calc and odeint_calc and calculate the error between the two
for i in range(1000):
# Calculate error using percent error formula (experimental - theoretical)/theoretical
err = np.abs((rk_calcs[i][1] - odeint_calcs[i][0])/odeint_calcs[i][0])
# Add error to end of list
errors.append(err)
# Return error list when complete
return errors
def model(y, x):
"""
The differential equation model being solved by ODEint
Parameters
----------
y: float
the starting y value from the inital condition (in this example Y0 = 5)
x: float
The x values to be used to find y. Each X value has step size of 0.02
Returns
----------
float
dydx value for the differential equation at X and Y
"""
dydx = y/(np.exp(x) - 1)
return dydx
def calculate_stop_val_x(dx):
"""
Calculates the ending value for X given that 1000 values are needed with a step size of 0.02.
Should calculate that ending value is 21.
Parameters
----------
dx: float
The delta X value or step size for the differential equation
Returns
----------
float
The ending value of the range for a starting point of 1 using step size 1000 times.
"""
return 1 + (dx * 1000)
def display_error(err, x, rk_calcs, odeint_calcs):
"""
Plots the error for each step in the differential equation solving process using a line graph.
Shows a table of the error for each step in the calculation.
Shows the average error for the entire calculation.
Y-Axis: error decimal
X-Axis: Xn value that corresponds to the error
Parameters
----------
err: float[]
The error array generated when calculating the error.
x: float[]
The Xn values
Returns
----------
None
"""
# Plot the error
plt.plot(x, err)
# Set X label
plt.xlabel('Xn Values')
# Set Y label
plt.ylabel('Error In Decimal')
# Set title
plt.title('Error Between Runge-Kutta and Odeint Calculations')
# Show Plot
plt.show()
# Convert arrays to numpy arrays
np_rk = np.array(rk_calcs)
np_ode = np.array(odeint_calcs)
np_err = np.array(err)
# Create table from values using pandas
error_table = pd.DataFrame({'X': x})
error_table['Y_RK'] = np_rk[:, 1]
error_table['Y_ODEint'] = np_ode[:, 0]
error_table['Error_Decimal'] = np_err
error_table['Error_Percentage'] = np_err*100
# Print first few items in table
print(error_table.head())
# Convert the table to HTML file for easy viewing
error_table.to_html('error_results.html')
# Calculate the avg error for all calculations
# Calculate sum of all error values
err_sum = np_err.sum()
# Divide sum by N
avg_err = err_sum/1000
# Display error
print('The average error between the Runge-Kutta algorithm and ODEint is: ' + str(avg_err*100) + '%')
def plot_rk(rk_calc):
"""
Plots the X and Y values for the Runge-Kutta solution on a line graph
Parameters
----------
rk_calc: double[][]
2D array containing all the [Xn, Yn] values for the solution
Returns
----------
None
"""
# Convert rk_calc to numpy array for plotting
np_rk_values = np.array(rk_calc)
# Plot the values
plt.plot(np_rk_values[:, 0], np_rk_values[:, 1])
# Set Y limit to 8 to match ODE graph
plt.ylim([5.0, 8.0])
# Set X label
plt.xlabel('Xn Values (1 - 21)')
# Set Y label
plt.ylabel('Calculated Y Values For X')
# Set title
plt.title('Runge-Kutta Results for X0, Y0 to X1000, Y1000')
# Show Plot
plt.show()
def plot_odeint(ode_calc, x):
"""
Plots the X and Y values from the ODEint solution on a line graph
Parameters
----------
ode_calc: double[][]
Yn values calculated for the corresponding X
x: float[]
Xn values
Returns
----------
None
"""
# Convert ode_calc to numpy array for plotting
np_ode_calc = np.array(ode_calc[:,0])
plt.plot(x, np_ode_calc)
# Set X label
plt.xlabel('Xn Values (1 - 21)')
# Set Y label
plt.ylabel('Calculated Y Values For X')
# Set title
plt.title('ODEint Results for X0, Y0 to X1000, Y1000')
# Show Plot
plt.show()
def plot_rk_odeint_overlapping(rk_calc, ode_calc, x):
"""
Plots the Runge-Kutta results and the ODEint results on the same graph to demonstrate differences in the algorithms
results
Parameters
----------
rk_calc: double[][]
results from the Runge-Kutta calculations
ode_calc: double[][]
Yn results from the ODEint calculations
x: float[]
Xn values for the ODEint calculations
Returns
----------
None
"""
# Convert ode_calc to numpy array for plotting
np_ode_calc = np.array(ode_calc[:, 0])
# Plot odeint values
odeint_plt, = plt.plot(x, np_ode_calc, label='ODEint')
# Convert rk_calc to numpy array for plotting
np_rk_values = np.array(rk_calc)
# Plot the values
rk_plt, = plt.plot(np_rk_values[:, 0], np_rk_values[:, 1], label='Runge-Kutta')
# Set X label
plt.xlabel('Xn Values')
# Set Y Label
plt.ylabel('Yn Values')
# Set Title
plt.title('Runge-Kutta vs ODEint')
# Show legend for plots
plt.legend(handles=[rk_plt, odeint_plt])
# Add some transparency to make graph more clear
# Show Plots
plt.show()
# Run the main program
if __name__ == '__main__':
# initialize starting variables for RK algorithm
n = 1000
dx = 0.02
y_init = 5
x_init = 1
# Grab start time of calculations
start_time = dt.datetime.now()
# Run Runge-Kutta calculation
rk_calculations = solve_rk(y_init, x_init, dx, n)
# Initialize starting variables for odeint calculations
x_stop_val = calculate_stop_val_x(dx)
# set x range
x = np.arange(1, x_stop_val, dx)
# Run ODEint calculation
ode_calculations = ode(model, y_init, x)
# Grab end time of calculations
end_time = dt.datetime.now()
# Calculate runtime of calculations for solving ODE with RK and ODEint
print("Program Runtime: " + str((end_time - start_time).microseconds/1000))
# Plot Results
# Plot Runge-Kutta
plot_rk(rk_calculations)
# Plot ODEint
plot_odeint(ode_calculations, x)
# Plot both together on same graph
plot_rk_odeint_overlapping(rk_calculations, ode_calculations, x)
# calculate error between RK algorithm and odeint results
err_calcs = calculate_error(rk_calculations, ode_calculations)
# Display all error calculations
display_error(err_calcs, x, rk_calculations, ode_calculations)
|
3aa7413a54ac321d32c4a907f6e7cf58425a539b | venkor/Python3Learning | /miodny.py | 955 | 3.765625 | 4 | from os.path import exists
from sys import argv
script, input_file, output_file = argv
#user_sentence = input("Type in a sentence here.\n")
#print(f"Congrats, you've type in:\n{user_sentence}\n")
#print(f"Your sentence is {len(user_sentence)} bytes long.")
#filename = input("Type in the file to copy:\n")
def copy_file(input_file, output_file):
if (exists(input_file)) == True:
print(f"The file \"{input_file}\" exists. Copying...")
indata = (open(input_file)).read()
out_file = open(output_file, 'w')
out_file.write(indata)
out_file.close()
print(f"Copy finished. Length of {output_file} is {len(output_file)} bytes.")
else:
print(f"The file \"{input_file}\" does not exist!\n")
print("Enter the name of file to copy and hit RETURN or CTRL-C to exit.\n")
input_file = input("Input file: ")
copy_file(input_file, output_file)
copy_file(input_file, output_file)
|
953c8f551fa045d9282a3fa20e1c5b738dca7483 | Erkaman/graphics-experiments | /samples/game/src/rand.py | 358 | 3.5625 | 4 | import random
def print_rands():
for i in range(512):
# print str(random.uniform(-1,1.0)) +"f", ",",
print"1.0f", ",",
i = i+1
if i % 20 == 0:
print ""
def print_shuffle():
li = range(0,512)
random.shuffle(li)
print ','.join(map(str, li))
print len(li)
print_rands()
#print_shuffle()
|
c605d89334dcb268a40bc91cd10474512d8fc9f1 | wiheto/netplotbrain | /netplotbrain/plotting/plot_spheres.py | 1,875 | 3.71875 | 4 | import numpy as np
def _plot_spheres(ax, nodes, node_columnnames, node_color='salmon', node_size=20, alpha=None, **kwargs):
"""
Function that plots spheres in figure.
Parameters
---------------
ax : matplotlib ax
nodes : dataframe
node dataframe with x, y, z coordinates.
node_columnnames : list of string
name of node column coordinates in datadrame to correspond with x,y,z.
node_size : string or float, int
if string, must refer to a column in nodes.
node_color : string or matplotlib color
if non-color string, must refer to a column in nodes
Returns
-------------
Nothing
NOTE: During development, this is not being updated as much as _plot_circles.
Some functionality from there should be added to this.
"""
# Get relevant kwargs
node_scale = kwargs.get('node_scale')
node_alpha = kwargs.get('node_alpha')
# Loop through each node and plot a surface plot
for index, row in nodes.iterrows():
# Get the xyz coords for the node
c = [row[node_columnnames[0]],
row[node_columnnames[1]],
row[node_columnnames[2]]]
# Check if node_size is in the dataframe
if node_size in nodes.keys():
r = row[node_size] * node_scale
else:
r = node_size * node_scale
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
# Calculate the x,y,z coordinates of each sphere
x = r*np.cos(u)*np.sin(v)
y = r*np.sin(u)*np.sin(v)
z = r*np.cos(v)
# Select the node color if string or array
if isinstance(node_color, np.ndarray):
ncolor = node_color[index]
else:
ncolor = node_color
ax.plot_surface(c[0]+x, c[1]+y, c[2]+z,
color=ncolor,
alpha=node_alpha)
|
d468241f0c97c623644a3788845f36cf61ad0a55 | subhashreddykallam/Competitive-Programming | /Codeforces/Codeforces Round #563 (Div. 2) - 1174/1174C-Ehab and a Special Coloring Problem.py | 659 | 3.90625 | 4 | def SieveOfEratosthenes(n):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
prime = [0 for i in range(n+1)]
prime[0] = 0
prime[1] = 0
p = 2
current = 1
while (p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p]==0):
prime[p] = current
for i in range(p, n+1, p):
prime[i] = current
current+=1
p += 1
return prime
n = int(input())
prime = SieveOfEratosthenes(n)
print(*prime[2:]) |
bea14851edfc96e0ae205ba1206012c346e32275 | AuJaCef/delivables | /python-3.1/speed-limit.py | 561 | 3.890625 | 4 | #Speed limit
#Austin Cefaratti 1/16/19
#finds the speeding fee
def main():
limit = eval(input("What is the speed limit: "))
print()
speed = eval(input("How fast was the driver going: "))
if speed > 90:
fine = 200 + (50 + ((speed - limit) * 5))
print()
print("You are fined: ",fine)
print()
elif speed > limit:
fine = 50 + (speed - limit) * 5
print()
print("You are fined: ",fine)
print()
else:
print()
print("You are not fined anything.")
print()
main()
|
01e808ffad0a6673256dbb6c7126ce40c6fcc800 | butflame/DesignPattern | /Creational/Factory_Method.py | 1,206 | 3.6875 | 4 | """
Factory Method, one of factory pattern.
"""
import xml.etree.ElementTree as etree
import json
class JSONConnector:
def __init__(self, filepath):
self.data = dict()
with open(filepath, method='r', encoding='utf-8') as f:
self.data = json.load(f)
@property
def parsed_data(self):
return self.data
class XMLConnector:
def __init__(self, filepath):
self.tree = etree.parse(filepath)
@property
def parsed_data(self):
return self.tree
def connection_factory(filepath):
if filepath.endswith('json'):
connector = JSONConnector
elif filepath.endswith('xml'):
connector = XMLConnector
else:
raise ValueError('Cannot connect to {}'.format(filepath))
return connector(filepath)
def connect_to(filepath):
factory = None
try:
factory = connection_factory(filepath)
except ValueError as ve:
print(ve)
return factory
"""
1. JSONConnector and XMLConnector deal with specific file, xml or json.
2. Connection_factory abstract from above two connector, user can ignore file type through this.
3. Abstract more, provide a simple interface, user just call one func and catch exception.
*. Exception catch can be more ignored, just print the error in connection_factory.
""" |
35a65fbaf93fad201083a0c74e5c6a5130033a2f | julianceccacci2005/pizza-thingy | /main.py | 379 | 4.15625 | 4 | num_people = int(input("how many people are there "))
num_pizza = input("how many pizzas are there ")
slices_per_pizza = int(input("how many slices are there "))
cost_per_pizza = float(input("how much does each pizza cost "))
total_slices = num_pizza * slices_per_pizza
slices_per_person = total_slices / num_people
print(f"there are (slices_per_person:.1f) slices per person") |
551637d181ffba2b91bf5ebf111f356d66624a00 | Lima001/BCC-POO-II | /Reflexão/Códigos/verificacao_tipos.py | 2,389 | 3.625 | 4 | '''
Exemplo criado para mostrar que usando metadados é possível
acrescentar parcialmente um aspecto de tipagem estática em Python.
Nesse caso os objetos da classe MinhaClasse devem ser criados usando
a função criar_objeto(), sendo que essa valida os tipos dos dados
conforme anotações no método __init__ da classe, impedindo que objetos
sejam criados caso seus tipos estejam em desacordo com o especificado
pelas anotações do programador.
'''
# Classe exemplo
class MinhaClasse():
# Observe as anotações sendo usadas para indicar o tipo ideial de cada atributo para inicializar um objeto
def __init__(self, atr1: int, atr2: str):
self.atr1 = atr1
self.atr2 = atr2
def __str__(self):
return f"({self.atr1}, {self.atr2})"
def criar_objeto(atr1, atr2):
'''
Função que abstrai a criação de objetos, validando o tipo
dos dados usados para inicializar um objeto em conformidade
as anotações do programador no método __init__()
'''
# Acesso as anotações de cada parâmetro da função ___init__()
# Relemebre que __annotations__ retorna um dicionário contendo o nome
# do parâmetro como chave, e a anotação como valor. Nesse caso devemos
# usar síntaxe de dicionário para acessar os valores das anotações via chave
tipo1 = MinhaClasse.__init__.__annotations__["atr1"]
tipo2 = MinhaClasse.__init__.__annotations__["atr2"]
# Verificando se o tipo dos dados informados correspodem ao tipo especificado pelo programador
if (type(atr1) != tipo1 or type(atr2) != tipo2):
print("Erro - Tipos de dados Incorretos- Impossível criar objeto!")
return None
# Caso tudo esteja em conformidade, o objeto é criado e retornado para ser usado
return MinhaClasse(atr1, atr2)
if __name__ == "__main__":
# Processo de criação de objetos testes
obj1 = criar_objeto(1,2) # Erro -> atr2 deve ser str
obj2 = criar_objeto("A",2) # Erro -> atr1 deve ser int
obj3 = criar_objeto(1,"Minha string") # Ok -> tipos de dados informados corretamente
# Como obj1 e obj2 não foram criados eles serão apresentados como None (devido ao retorno da função)
# Já obj3 (que foi criado) irá invocar o método __str__() sobrescrito na classe MinhaClasse
print(obj1, obj2, obj3) |
0738308946ea1ac436d2527c8cce3b8a9ea1ad46 | xdgoi/Cubius | /Cubius.py | 7,062 | 3.84375 | 4 | # Marcus Cornes
# This will allow me to use date and time in my program
import datetime
# This python module allows me to have OS priviliges that I can use to delete files
import os
# This module will allow me to open URL's from your web browser
import webbrowser
# This is the start message
print("Hello!")
# This code will run the program forever!
while True:
# This makes a prompt to enter a command
response = input("Enter a command: ")
# This is the trigger that will print the current version of my OS
if response == "version":
print("Cubius 0.0.1")
print(os.uname())
# This is the trigger that will print the date and time using the datetime python module
if response == "time":
try:
x = datetime.datetime.now()
print("")
print(x)
print("")
except:
print("")
print("The time program is not working.")
print("")
print("Please report this error at the errors page on GitHub :(")
print("")
# This is the trigger that will create a new .txt file
if response == "txt":
try:
f = open(".txt", "x")
f.close
print("")
print("Created .txt file in the current folder.")
print("")
except FileExistsError:
print("")
print("I'm sorry but it looks like you already have a filecalled .txt!")
print("")
delete = input("Do you want me to delete it and make a new .txt file? Y/N ")
if delete == "Y":
os.remove(".txt")
f = open(".txt", "x")
f.close
print("")
print("Process ran successfully ;)")
print("")
if delete == "N":
print("")
# This is a trigger that will run the code and the code will remove the current directory
if response == "rmDir":
print("")
folder = input("What is the name of the folder you want to delete? ")
try:
os.rmdir(folder)
print("")
print("Operation successful!")
print("")
except FileNotFoundError:
print("")
print("Sorry, the folder you specified couldn't be found! Make sure you spelt the folder name correctly or try again!")
print("")
print("If problems keep persisting, please visit the github repo and report an issue there.")
print("")
# This trigger will be able to open websites via your web browser
if response == "url":
print("")
web = input("What URL do you want to go to? ")
try:
webbrowser.open(web)
except:
print("")
print("Sorry but the URL you typed in couldn't be found! Maybe you should try typing the full URL.")
print("")
# This trigger will give you help when the user types in "help"
if response == "help":
print("")
print("version - Will get you the current version number you are using of cubius.")
print("")
print("time - Will get you the current time.")
print("")
print("txt - Will create a .txt file in the current directory.")
print("")
print("rmDir - Will remove the directory / folder you specify.")
print("")
print("url - Will open the URL that you specify in your preferred web browser.")
print("")
print("help - Will bring you a list of commands that you can use in cubius and will tell you what they do.")
print("")
print("calculator - Will bring up a simple and easy to use calculator.")
print("")
print("rmFile - Will remove a file.")
print("")
print("rename - Will allow you to rename a file.")
print("")
print("MakeDir - Will make a directory / folder.")
print("")
print("WorkingDir - Will print the working directory / folder.")
print("")
print("open - Will print out the contents of a file.")
print("")
print("caterpillar - Will play the caterpillar game.")
print("")
print("MatchMaker - Will play the match maker game.")
print("")
print("lives - Will play the game NineLives.")
# This bit of code will exit the loop.
if response == "exit":
break
if response == "calculator":
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
choice = int(input("Enter your choice: "))
if (choice>=1 and choice<=4):
print("Enter two numbers: ")
num1 = int(input())
num2 = int(input())
if choice == 1:
res = num1 + num2
print("Result = ", res)
elif choice == 2:
res = num1 - num2
print("Result = ", res)
elif choice == 3:
res = num1 * num2
print("Result = ", res)
elif choice == 4:
res = num1 / num2
print("Result = ", res)
else:
print("Wrong input..!!")
if response == "caterpillar":
import caterpillargame
if response == "rmFile":
print("")
fileName = input("What is the name of the file you want to delete?")
try:
os.remove(fileName)
print("")
print("Operation successful!")
print("")
except:
print("")
print("Sorry but the file couldn't be located.")
print("")
if response == "rename":
name = input("What is the current name of the file / folder you want to rename? ")
name2 = input("What is the new name of the file / folder you want to rename? ")
try:
os.rename(name, name2)
print("Operation successful!")
except:
print("Sorry, but it looks like the operation failed! Make sure you spelt everything correctly and try again.")
if response == "MakeDir":
folder = input("What is the name of the new folder?")
try:
os.mkdir(folder)
print("Operation successful!")
except:
print("Sorry, the folder already exists!")
if response == "WorkingDir":
try:
print("")
print(os.getcwd())
print("")
except:
print("Sorry, we failed to get the current working directory!")
if response == "open":
doc = input("What is the name of the file you would like to read?")
try:
f = open(doc, "r")
print(f.read())
print("")
except:
print("Sorry, but the file you specified could not be found!")
if response == "MatchMaker":
import Matchmaker
if response == "lives":
import NineLives |
78dcb895ca22ffd59196d9e034d5a0a791fc9d5a | saifazmi/learn | /languages/python/sentdex/intermediate/25_argsAndKwargs.py | 1,800 | 4.75 | 5 | # Args and Kwargs
'''
' The idea behind *args and **kwargs is that there may be times when you
' have a function and you want to be able to handle an unknown number of
' arguments. The *args will handle for any number of parameters, and **kwargs
' will handle for any number of keyword arguments (hence kwargs)
'
' One can think of *args as a list and **kwargs as a dictionary
'''
blog_1 = "I am so awesome."
blog_2 = "Cars are cool."
blog_3 = "Aww look at my cat!!"
site_title = "My Blog"
## *args parameters
def blog_posts(title, *args):
print(title)
for post in args:
print(post)
print("#### ARGS ####")
blog_posts(blog_1) # pass one argument
blog_posts(blog_1, blog_2, blog_3) # or more than one
blog_posts(site_title, blog_1, blog_2, blog_3) # can also pass specific parameter
## **kwargs parameters
def blog_posts(title, **kwargs):
print(title)
for p_title, post in kwargs.items():
print(p_title, post)
print("#### KWARGS ####")
blog_posts(site_title,
blog_1 = "I am so awesome.",
blog_2 = "Cars are cool.",
blog_3 = "Aww look at my cat!!")
## *args AND **kwargs parameters
def blog_posts(title, *args, **kwargs):
print(title)
for arg in args:
print(arg)
for p_title, post in kwargs.items():
print(p_title, post)
print("#### ARGS and KWARGS ####")
blog_posts(site_title,
'1', '2', '3',
blog_1 = "I am so awesome.",
blog_2 = "Cars are cool.",
blog_3 = "Aww look at my cat!!")
# Another way of using *args
import matplotlib.pyplot as plt
def graph_operation(x, y):
print("function that graphs {} and {}".format(str(x), str(y)))
plt.plot(x,y)
plt.show()
x1 = [1, 2, 3]
y1 = [2, 3, 1]
graph_me = [x1, y1]
graph_operation(*graph_me)
|
856662727f4170afbcda80e088e00481011f3363 | SBartonJr3/ClassBarton | /Python/loops 2/hex.py | 180 | 4.0625 | 4 | #Stephen Barton Jr
#Python Programming, hex
#22 APR 2019
def main():
decimal = int(input("Enter a number: "))
if decimal > 0:
print(hex(decimal))
main()
|
96f886f1b3a356b87d688e3b2b4e4cc81004bf62 | COD3BOY/probablyscripts | /CPlusPlusCopy.py | 797 | 3.546875 | 4 | #!/usr/bin/python
import sys
import os.path
def get_camel_case(name, first=True):
parts = name.split('_')
s = ''
cap = first
for part in parts:
if cap:
s += part[0].upper()
s += part[1:]
else:
cap = True
s += part
return s
in_file, out_file = sys.argv[1:3]
in_base = os.path.splitext(os.path.split(in_file)[-1])[0]
out_base = os.path.splitext(os.path.split(out_file)[-1])[0]
replacements = {
get_camel_case(in_base): get_camel_case(out_base),
in_base.upper(): out_base.upper(),
in_base: out_base}
contents = open(in_file, 'r').read()
for old_s, new_s in replacements.iteritems():
contents = contents.replace(old_s, new_s)
output = open(out_file, 'w')
output.write(contents)
output.close()
|
e5d84b41b7320ca7263187b9dfd37005f227a931 | duanxian158/aotocode | /python9/homework_0807/human_vs_machine.py | 2,821 | 3.640625 | 4 | #5.人和机器猜拳游戏写成一个类,有如下几个函数
# 1)函数1:选择角色1 曹操 2张飞 3 刘备
# 2)函数2:角色猜拳 1 剪刀 2 石头 3 布 玩家输入一个1-3的数字
# 3)函数3:电脑出拳 随机产生1个1-3的数字,提示电脑出拳结果
# 4)函数4:角色和机器出拳对战,对战结束后,
# 最后出示本局对战结果。。。赢。。。输,然后提示用户是否继续?按继续,按n退出
# 5):最后结束的时候输出结果 角色赢几局 电脑赢几局,平局几次 游戏结束
import random
class HumanVsMachine:
def ChooseRole(self):#选择角色
role_dict={'1':'曹操','2':'张飞','3':'刘备'}
while True:
role_num = input('请输入数字选择你的角色:1 曹操 2张飞 3 刘备')
if role_num in('1','2','3'):
role_name=role_dict[role_num]
break
else:
print('你输入的角色错误,请重新输入')
continue
return role_name#返回我所选择的角色
def Human(self,role_name):#角色出拳 形参 你调用这个函数时 需要传参
fist_dict={'1':'剪刀','2':'石头','3':'布'}
fist_num=input('{0}请出拳'.format(role_name))
try:
print('{0}出拳为:{1}'.format(role_name,fist_dict[fist_num]))
except Exception as e:
print('出错了:%s'%e)
else:
return int(fist_num)
def Machine(self):
fist_dict = {'1':'剪刀','2':'石头','3':'布'}
fist_num=random.randint(1,3)
print('电脑出拳为:{0}'.format(fist_dict[str(fist_num)]))
return fist_num
def human_vs_machine(self):
role_name=self.ChooseRole()#确定你选择的角色名
human_win=0#角色赢
machine_win=0#机器赢
drwa_num=0#平局
while True:
human_fist=self.Human(role_name)
machine_fist=self.Machine()
#1 剪刀 2 石头 3 布
#1-3 2-1 3-2
if human_fist-machine_fist==-2 or human_fist-machine_fist==1:
human_win+=1
print('恭喜{0}赢了本局!'.format(role_name))
elif human_fist-machine_fist==0:
drwa_num+=1
print('本局打平')
else:
machine_win+=1
print('很遗憾{0}输了,电脑赢了!'.format(role_name))
yes_or_no=input('是否要继续?按y继续,按n退出')
if yes_or_no=='n':
break
#结束对战后 出结果
print('{0}赢了{1}局,电脑赢了{2}局,平局{3}'.format(role_name,human_win,machine_win,drwa_num))
if __name__ == '__main__':
HumanVsMachine().human_vs_machine() |
9c2ad16186dd90db2c361f3123a95c2b828ea270 | linhx13/leetcode-code | /code/729-my-calendar-i.py | 488 | 3.5625 | 4 | class MyCalendar:
def __init__(self):
self.events = []
def book(self, start: int, end: int) -> bool:
for i in range(len(self.events)):
if (self.events[i][0] <= start < self.events[i][1]
or self.events[i][0] < end <= self.events[i][1]) \
or (start <= self.events[i][0] < end
or start < self.events[i][1] <= end):
return False
self.events.append((start, end))
return True
|
a07fe3712a602ac3f15ca6a2e13e19aeb768aa1d | cravingdata/List-of-Divisors | /PracticePython_Exc4_Divisors_0-11.py | 268 | 4.09375 | 4 | number = int(raw_input("Enter a number between 0 and 11 to find its list of divisors: "))
x = []
for divisor in range (1, 11):
if number % divisor == 0:
answer = int(divisor)
x.append(answer)
print x
#finding list of divisors up to 10.
|
70ee472e83fd595b413c38da5f61b5b4fd6745ee | ThomasZumsteg/project-euler | /problem_0076.py | 472 | 3.578125 | 4 | #!/usr/bin/python
"""http://projecteuler.net/problem=76"""
from time import time
from progressbar import ProgressBar
def main():
num = 100
print changes(num, range(1,num))
def changes(amount, coins):
ways = [0] * (amount + 1)
ways[0] = 1
p = ProgressBar()
for coin in p(coins):
for j in range(coin, amount + 1):
ways[j] += ways[j-coin]
return ways[amount]
if __name__ == "__main__":
start = time()
main()
print "That took %f seconds" %(time() - start)
|
d2755dae3aaf7986eaf1d51f2c5cae03333fbe1d | vikil94/python_fundamentals1 | /exercise1.py | 131 | 3.84375 | 4 | # print(2 + 3)
print(2)
print(3)
print(2 + 3)
name1 = "Betty"
name2 = "Bella"
print("Hello {}, hello {}!".format(name1, name2))
|
0b7d8d00fe54ad8eea9351056e78b44c7a3b3665 | choudharynidhi2908/Random_Forest | /Random_Forest_Company_Data.py | 2,229 | 3.5 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
df=pd.read_csv("E:\\Data Science\\Assignments\\Python code\\Decision Trees\\Company_Data.csv")
df=pd.get_dummies(df,columns=['ShelveLoc','Urban','US'],drop_first=True)
df.loc[df.Sales<=10,'Sales']='No'
df.loc[df.Sales !='No','Sales']='Yes'
train,test=train_test_split(df,test_size=0.3)
model=RandomForestClassifier(n_estimators=100)
model.fit(train.iloc[:,1:12],train.iloc[:,0])
#To find train and test accuracy
train_acc=np.mean(model.predict(train.iloc[:,1:12])==train.iloc[:,0])
test_acc=np.mean(model.predict(test.iloc[:,1:12])==test.iloc[:,0])
acc=[]
for i in range(100,200,2):
model=RandomForestClassifier(n_estimators=i)
model.fit(train.iloc[:,1:12],train.iloc[:,0])
train_acc=np.mean(model.predict(train.iloc[:,1:12])==train.iloc[:,0])
test_acc=np.mean(model.predict(test.iloc[:,1:12])==test.iloc[:,0])
acc.append([train_acc,test_acc])
import matplotlib.pyplot as plt # library to do visualizations
# train accuracy plot
plt.plot(np.arange(100,200,2),[i[0] for i in acc],"ro-")
# test accuracy plot
plt.plot(np.arange(100,200,2),[i[1] for i in acc],"bo-")
plt.legend(["train","test"])
###############################################################################################
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
df=pd.read_csv("E:\\Data Science\\Assignments\\Python code\\Decision Trees\\Company_Data.csv")
df=pd.get_dummies(df,columns=['ShelveLoc','Urban','US'],drop_first=True)
df.loc[df.Sales<=10,'Sales']='No'
df.loc[df.Sales != 'No','Sales']='Yes'
X=df.iloc[:,1:12]
y=df.iloc[:,0]
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)
model=RandomForestClassifier(n_estimators=100)
model.fit(X_train,y_train)
y_pred=model.predict(X_test)
from sklearn.metrics import confusion_matrix,accuracy_score,classification_report
accuracy_score(y_test,y_pred)
confusion_matrix(y_test,y_pred)
classification_report(y_test,y_pred)
|
687fb99d1330227787dc14569a810944374ece86 | lancezlin/Python-Program | /removePunctuation.py | 317 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 30 23:52:09 2015
@author: Lance
"""
# Capitalization and punctuation removing function
import re
def removePunctuation(text):
return re.sub(r'[a-zA-Z0-9\s]+', '', text).lower().strip()
print removePunctuation('u= what')
print removePunctuation(' hello world ! ')
|
d53146d8e7715a8d25568078f20a4c3f35c927ab | alorozco53/ialab | /Minimax/bin/minimax.py | 1,463 | 3.984375 | 4 | #!/usr/bin/python
import argparse
from game import *
"""
This is the main script that executes the program
:author AlOrozco53:
"""
def parse_args():
"""
Parses the tic-tac-toe state stored in the file whose name
is indicated as argument
:return state_matrix: a matrix representation of the tic-tac-toe state
:return player: true iff current player to make a move is Max
"""
parser = argparse.ArgumentParser(description='Parse inputs.')
parser.add_argument('-state', help='State of the game to be read.')
parser.add_argument('-player',
help='Player to make the move in the current grid.',
default='max')
args = parser.parse_args()
# build the matrix
state_matrix = []
ignore = ['\t', '\n', ' ']
with open(args.state, 'r') as state_file:
for line in state_file:
state_matrix.append([ch for ch in line if ch not in ignore])
return state_matrix, args.player != 'max'
def main():
"""
Main method
"""
state_to_check, player = parse_args()
print('state matrix read:')
print(str(State(player, state_to_check)))
print('the next player to move is:', ('Max' if not player else 'Min'))
tree = TicTacToeTree(player, state_to_check)
print('building the tree...')
tree.build_tree()
print('computing the minimax decision...')
print(tree.minimax_decision())
if __name__ == '__main__':
main()
|
08f83c62f6d6ee4dcf827afc8e11ae5a6fb26219 | pacis32/Data-Structure-and-Algorithm-Problem-Solutions | /HackerRank/diagSum.py | 521 | 4.0625 | 4 | # Given a square matrix, calculate the absolute difference between the sums of its diagonals.
# For example, the square matrix is shown below:
def diagonalDifference(arr):
leftDiagSum = 0
rightDiagSum = 0
step = 0
for i in range(len(arr)):
leftDiagSum += arr[step][step]
step += 1
stepBack = len(arr[0]) - 1
step = 0
for i in range(len(arr)):
rightDiagSum += arr[step][stepBack]
stepBack -= 1
step += 1
return abs(leftDiagSum - rightDiagSum)
|
12ec809e8608ee36f2f32fdb8c126c4a569c8f74 | shayan-ys/Prisoners-Dilemma-Tournament | /strategies.py | 4,532 | 3.78125 | 4 | from random import random
plays_in_a_game = 10
class Prisoner:
score = 0
games_played = 0
name = 'Abstract'
@staticmethod
def strategy(*args, **kwargs):
"""
Based on given information, works on a strategy to make a decision about next move
:return: True to Co-Operate and False to Defect
"""
return True
def __str__(self):
if self.games_played:
return self.name + ' (' + str(int(self.score / self.games_played * 100)) + ' { ' + str(
self.score) + '/' + str(self.games_played) + ' })'
else:
return self.name + ' (newbie)'
def __repr__(self):
return self.__str__()
class PrisonerCoOp(Prisoner):
name = 'Co-Operate'
@staticmethod
def strategy(*args, **kwargs):
return True
class PrisonerDefect(Prisoner):
name = 'Defect'
@staticmethod
def strategy(*args, **kwargs):
return False
class PrisonerCoinFlip(Prisoner):
name = 'Coin-Flip'
@staticmethod
def strategy(*args, **kwargs):
return random() < 0.5
class PrisonerTitForTat(Prisoner):
name = 'Tit-for-Tat'
@staticmethod
def strategy(*args, **kwargs):
if kwargs['opponent_history']:
return kwargs['opponent_history'][-1]
return True
class PrisonerGrudge(Prisoner):
name = 'Grudge'
@staticmethod
def strategy(*args, **kwargs):
if kwargs['opponent_history']:
if False in kwargs['opponent_history']:
return False
return True
class PrisonerTitForTwoTat(Prisoner):
name = 'Tit-for-Two-Tat'
@staticmethod
def strategy(*args, **kwargs):
if kwargs['opponent_history']:
try:
if not kwargs['opponent_history'][-1] and not kwargs['opponent_history'][-2]:
return False
except IndexError:
return True
return True
class PrisonerBackAndForth(Prisoner):
name = 'Back-and-Forth'
@staticmethod
def strategy(*args, **kwargs):
if len(kwargs['opponent_history']) % 2:
return False
return True
class PrisonerJOSS(Prisoner):
# Tit-for-Tat but once in a while defect
name = 'JOSS'
@staticmethod
def strategy(*args, **kwargs):
if kwargs['opponent_history']:
if random() < 0.15:
return False
return kwargs['opponent_history'][-1]
return True
class PrisonerTitForTatExceptLast(Prisoner):
# Tit-for-Tat except the very last move: defect
name = 'Tit-for-Tat-except-last-defect'
@staticmethod
def strategy(*args, **kwargs):
if kwargs['opponent_history']:
if len(kwargs['opponent_history']) == plays_in_a_game - 1:
return False
else:
return kwargs['opponent_history'][-1]
return True
class PrisonerTester(Prisoner):
# This strategy have the ability to identify tit-for-tat or tit-for-two-tat opponent and play so as it can win
name = "Tester"
opponent_type = 'Unknown'
def strategy(self, *args, **kwargs):
if self.opponent_type == 'Not-nice':
return PrisonerDefect.strategy(*args, **kwargs)
op_history = kwargs['opponent_history']
if op_history and len(op_history) <= 5:
if len(op_history) == 1 or len(op_history) == 2:
if not op_history[-1]:
self.opponent_type = 'Not-nice'
return False
if len(op_history) == 3:
if op_history[-1]:
self.opponent_type = 'Tit-for-Two-Tat'
else:
self.opponent_type = 'Tit-for-Tat'
return True
if len(op_history) == 4:
if op_history[-1]:
self.opponent_type = 'CoOp'
return False
if len(op_history) == 5:
if not op_history[-1]:
self.opponent_type = 'Grudge'
if self.opponent_type == 'Tit-for-Tat':
return PrisonerTitForTatExceptLast.strategy(*args, **kwargs)
if self.opponent_type == 'Tit-for-Two-Tat':
return PrisonerBackAndForth.strategy(*args, **kwargs)
if self.opponent_type == 'CoOp':
return PrisonerDefect.strategy(*args, **kwargs)
if self.opponent_type == 'Grudge':
return PrisonerDefect.strategy(*args, **kwargs)
return True
|
11f494cb8415253daed09363672c0fe95f8ee6c8 | kami39/practice | /pythonTest/re/sub.py | 254 | 3.625 | 4 | #-*- coding:UTF-8 -*-
import re
s="i say, hello world,!too"
p = re.compile(r'(\w+) (\w+)')
#下标引用
# print(p.subn(r'\2 \1',s))
print(p.subn(r'\g<2> \1',s))
'''
#别名引用
p = re.compile(r'(\w+) (?P<id1>\w+)')
print(p.subn(r'\g<id1> \1',s))
''' |
6886434da8de94421b210ce3ffb9daafd97940de | jviriato/grammar-parser | /main.py | 1,043 | 3.671875 | 4 | #!/usr/bin/env python3
import argparse
from Grammar import Grammar
from Automata import Automata
def main():
parser = argparse.ArgumentParser(
description='Argumentos para entrada de arquivo e palavra')
parser.add_argument('-f','--filename', help='Input filename', required=False)
parser.add_argument('-w','--word', help='Input word', required=False)
args = parser.parse_args()
if args.filename:
grammar_path = args.filename
else:
grammar_path = 'gramatica_exemplos/gramatica_exemplo_loop.txt'
with open(grammar_path, 'r') as gf:
grammar = gf.readline().rstrip()
g = Grammar(grammar)
ehValido = g.validateGrammar()
if args.word:
word = args.word
else:
word = input('Digite a palavra a ser validada: ')
g.recognize(word)
if ehValido:
dfa = Automata(start_state = g.startSymbol)
dfa.convertGrammar(g)
dfa.convertER()
print('A ER gerada é: ')
print(dfa.ER)
if __name__ == "__main__":
main()
|
35b798be96a44cb7ec3e209c010fa8264d018074 | sanchyy/CTF_writeups | /picoCTF2019/scripts/numbers.py | 295 | 3.640625 | 4 | #!/usr/bin/env python
code = [16, 9, 3, 15, 3, 20, 6, '{', 20, 8, 5, 14, 21, 13, 2, 5, 18, 19, 13, 1, 19, 15, 14, '}']
init = 65 - 1 # 'A' position in ascii table
for elem in code:
if type(elem) == int:
print(chr(init+elem), end='')
else:
print(elem, end='')
print()
|
ca19c9bd2d60692a82035063059c331fc9095034 | Grozly/python_basics | /lesson_4/task_5.py | 1,386 | 4.15625 | 4 | # Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
# Подсказка: использовать функцию count() и cycle() модуля itertools.
# Обратите внимание, что создаваемый цикл не должен быть бесконечным.
# Необходимо предусмотреть условие его завершения.
# Например, в первом задании выводим целые числа, начиная с 3,
# а при достижении числа 10 завершаем цикл. Во втором также необходимо предусмотреть условие,
# при котором повторение элементов списка будет прекращено.
from itertools import count, cycle
for i in count(int(input('Введите стартовое число: '))):
if i > 10: # Задаем границу цикла
break
print(i)
lst = ['A', 'B', 'C', '1', '2', '3']
my_count = 0
for i in cycle(lst):
if my_count > 11:
break
print(i)
my_count += 1
|
9d85de3a93b3f1cbc7f82afcdaae0a43b919db31 | ky-koz/pythonProjects | /CodingDrills/phonebook/phonebook_func.py | 12,083 | 4.09375 | 4 | #
# Python: 3.8.0
#
# Author: Kyla M. Kozole
#
# Purpose: The Tech Academy- Python Course, Phonebook Demo. Demonstrating OOP,
# Tkinter GUI module, using Tkinter Parent and Child relationships.
#
import os
from tkinter import *
from tkinter import messagebox
import tkinter as tk
import sqlite3
import phonebook_main
import phonebook_gui
def center_window(self, w, h): # pass in the tkinter fram(master) reference and the w and h
# get the user's screen width and height
screen_width = self.master.winfo_screenwidth() # naming it screen_width
screen_height = self.master.winfo_screenheight()
# calculate x and y coordinates to paint the app centered on the user's screen
x = int((screen_width/2) - (w/2))
y = int((screen_height/2) - (h/2))
centerGeo = self.master.geometry('{}x{}+{}+{}'.format(w, h, x, y))
return centerGeo
# catch if the user clicks on the windows upper-right 'X' to ensure they want to close
def ask_quit(self):
if messagebox.askokcancel("Exit program", "Okay to exit application?"): # tkinter messagebox: window {title/name}{message}
# this closes app
self.master.destroy()
os._exit(0) # program releases memory; os defined method
#===============================================================
def create_db(self): # name it create_db and pass in self
conn = sqlite3.connect('db_phonebook.db') # connect and then create this db
with conn:
cur = conn.cursor()
cur.execute("CREATE TABLE if not exists tbl_phonebook( \
ID INTEGER PRIMARY KEY AUTOINCREMENT, \
col_fname TEXT, \
col_lname TEXT, \
col_fullname TEXT, \
col_phone TEXT, \
col_email TEXT \
);")
# You must commit() to save changes and close the db connection
conn.commit()
conn.close()
first_run(self)
def first_run(self):
# data = ('John', 'Doe', 'John Doe', '111-111-1111', 'jdoe@email.com') ### This is in the video but not in the code
conn = sqlite3.connect('db_phonebook.db')
with conn:
cur = conn.cursor() # cur becomes an sqlite3 reference
cur,count = count_records(cur)
if count < 1:
cur.execute("""INSERT INTO tbl_phonebook (col_fname,col_lname, \
col_fullname,col_phone, col_email) VALUES (?,?,?,?,?)""", \
('John', 'Doe', 'John Doe', '111-111-1111', 'jdoe@email.com'))
conn.commit()
conn.close()
def count_records(cur):
count = ""
cur.execute("""SELECT COUNT(*) FROM tbl_phonebook""") # passing the sqlite cursor fn
count = cur.fetchone()[0] # extract the data from the cur command
return cur,count
#Select item in ListBox
def onSelect(self,event):
# calling the event is the self.lstList1 widget
varList = event.widget # whatever is triggering the event
select = varList.curselection()[0] # the index of our selection
value = varList.get(select) # get the text of the index number
conn = sqlite3.connect('db_phonebook.db')
with conn:
cursor = conn.cursor() #sqlite3 cursor object
cursor.execute("""SELECT col_fname,col_lname,col_phone,col_email \
FROM tbl_phonebook WHERE col_fullname = (?)""", [value]) # only if matches the f/lname from the value(list)
varBody = cursor.fetchall()
# This returns a tuple and we can slice it into 4 parts using data[] during the iteration
for data in varBody:
# accessing different parts of the tuple that is returned
self.txt_fname.delete(0,END) # delete the text box to clear it
self.txt_fname.insert(0,data[0]) # insert the new info into the empty box
self.txt_lname.delete(0,END)
self.txt_lname.insert(0,data[1])
self.txt_phone.delete(0,END)
self.txt_phone.insert(0,data[2])
self.txt_email.delete(0,END)
self.txt_email.insert(0,data[3])
def addToList(self):
# these are built-in functions
var_fname = self.txt_fname.get()
var_lname = self.txt_lname.get()
var_fname = var_fname.strip() # remove any blank spaces before or after the user's entry
var_lname = var_lname.strip()
var_fname = var_fname.title() # create capital letter at beginning of word
var_lname = var_lname.title()
var_fullname = ("{} {}".format(var_fname,var_lname)) # format we want in our listbox, will combine and normalize name into a fullname
print("var_fullname: {}".format(var_fullname))
var_phone = self.txt_phone.get().strip()
var_email = self.txt_email.get().strip()
if not "@" or not "." in var_email:
print("Incorrect email format!!!")
if (len(var_fname) > 0 ) and (len(var_lname) > 0 ) and (len(var_phone) > 0) and(len(var_email) > 0): # enforces user to provide both names
conn = sqlite3.connect('db_phonebook.db')
with conn:
cursor = conn.cursor()
# check the db for existence of the fullname, if so, we will alert user and disregard request
cursor.execute("""SELECT COUNT(col_fullname) FROM tbl_phonebook \
WHERE col_fullname = '{}'""".format(var_fullname))
count = cursor.fetchone()[0]
chkName = count
if chkName == 0:
print("chkName: {}".format(chkName))
cursor.execute("""INSERT INTO tbl_phonebook (col_fname,col_lname,col_fullname, \
col_phone,col_email) VALUES (?,?,?,?,?)""",(var_fname,var_lname,var_fullname, \
var_phone,var_email))
self.lstList1.insert(END, var_fullname) # update into list box
onClear(self) # automate clearing all text boxes at once
else:
messagebox.showerror("Name Error","'{}' already exists in the database! Please \
choose a different name.".format(var_fullname))
onClear(self)
conn.commit() # save data in db
conn.close()
else:
messagebox.showerror("Missing Text Error","Please ensure that there is data in all four fields.")
def onDelete(self): # to delete something in the database
var_select = self.lstList1.get(self.lstList1.curselection()) # Listbox's selected value: get the listbox1's cursor selection
conn = sqlite3.connect('db_phonebook.db')
with conn:
cur = conn.cursor()
# check count to ensure that this is not the last record in
# the db... cannot delete last record or we will get an error
cur.execute("""SELECT COUNT(*) FROM tbl_phonebook""")
count = cur.fetchone()[0]
if count > 1: # is >1 then we know there are more than one user in the db
confirm = messagebox.askokcancel("Delete Confirmation","All information associated with, \
({}) \nwill be permenantly deleted from the database. \n\nProceed with the deletion request?" \
.format(var_select))
if confirm:
conn = sqlite3.connect('db_phonebook.db')
with conn:
cursor = conn.cursor()
cursor.execute("""DELETE FROM tbl_phonebook WHERE col_fullname = '{}'""".format(var_select))
onDeleted(self) # call the function to clear all of the textboxes and the selected index of listbox
# onRefresh(self) # update the listbox of the changes
conn.commit()
else:
confirm = messagebox.showerror("Last Record Error", "({}) is the last record in the database \
and cannot be deleted at this time. \n\nPlease add another first before you can delete ({})." \
.format(var_select,var_select))
conn.close
def onDeleted(self):
# clear the text in these textboxes
self.txt_fname.delete(0,END)
self.txt_lname.delete(0,END)
self.txt_phone.delete(0,END)
self.txt_email.delete(0,END)
# onRefresh(self) # update the listbox of the changes
try:
index = self.lstList1.curselection()[0]
self.lstList1.delete(index)
except IndexError:
pass
def onClear(self):
# clear the text in these textboxes
self.txt_fname.delete(0,END)
self.txt_lname.delete(0,END)
self.txt_phone.delete(0,END)
self.txt_email.delete(0,END)
def onRefresh(self):
# (re)Populate the listbox, coinciding with the db
self.lstList1.delete(0,END) # delete everything in the listbox
conn = sqlite3.connect('db_phonebook.db')
with conn:
cursor = conn.cursor()
cursor.execute("""SELECT COUNT (*) FROM tbl_phonebook""")
count = cursor.fetchone()[0]
i = 0
while i < count: # this is a control, if you do more loops than the count you will produce an error
cursor.execute("""SELECT col_fullname FROM tbl_phonebook""") # fullname is the value we put in our listbox
varList = cursor.fetchall()[i]
for item in varList:
self.lstList1.insert(0,str(item)) # take the item from the list and put it in the listbox
i = i + 1
conn.close()
def onUpdate(self): # to update info or make changes
try:
var_select = self.lstList1.curselection()[0] # index of the list selection
var_value = self.lstList1.get(var_select)# list selecion's text value
except:
messagebox.showinfo("Missing selection","No name was selected from the list box. \nCancelling \
the Update request.")
return # go back and return to normal fn
# the user will only be allowed to update changes for phone and emails.
# for name changes, the user will need to delete the entire record and start over.
var_phone = self.txt_phone.get().strip() # normalize the data to maintain db integrity
var_email = self.txt_email.get().strip()
if (len(var_phone) > 0) and (len(var_email) > 0): # ensure that there is data present
conn = sqlite3.connect('db_phonebook.db')
with conn:
cur = conn.cursor()
# count records to see if the user;s changes are already in
# the db... ,meaning, there are no changes to update.
cur.execute("""SELECT COUNT(col_phone) FROM tbl_phonebook WHERE col_phone = '{}'""".format(var_phone))
count = cur.fetchone()[0]
print(count)
cur.execute("""SELECT COUNT(col_email) FROM tbl_phonebook WHERE col_email = '{}'""".format(var_email))
count2 = cur.fetchone()[0] # where we're getting the return value back
print(count2)
if count == 0 or count2 == 0: # if proposed changes are not already in the db, then proceed
response = messagebox.askokcancel("Update Request","The following changes ({}) and ({}). \
\n\nProceed with the update request?".format(var_phone,var_email,var_value))
print(response)
if response: # if the user responds with okay then proceed with conn
with conn:
cursor = conn.cursor()
cursor.execute("""UPDATE tbl_phonebook SET col_phone = '{0}',col_email = '{1}' WHERE \
col_fullname = '{2}'""".format(var_phone,var_email,var_value))
onClear(self)
conn.commit()
else:
messagebox.showinfo("Cancel request","No changes have been made to ({}).".format(var_value))
else:
messagebox.showinfo("No changes detected","Both ({}) and ({}) \nalready exist in the database \
for \n\nYour update request request has been cancelled.".format(var_phone, var_email))
onClear(self) # clear the textbox
conn.close()
else:
messagebox.showerror("Missing information","Please select a name from the list. \nThen edit \
the phone or email information.")
onClear(self)
if __name__ == "__main__":
pass # don't run anything, just pass
|
0b6b789d7600c62384b19509ece3150427352a30 | ardakkk/Algorithms-and-Data-Structures | /leetcode/19-remove-nth-node-from-end-of-list.py | 736 | 3.765625 | 4 | # Definition for singly-linked list.
# Time: O(n) We traverse thru the Linked List once.
# Space: O(1) We always use two nodes, regardless of size of LL.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy_head = ListNode("placeholder")
dummy_head.next = head
slow = dummy_head
fast = dummy_head
for _ in range(n):
fast = fast.next
# Move slow and fast up one at a time, until fast is last node
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy_head.next |
c24b7b25ed28da616fa92114ea9bb3067672a8fa | tinbaj/FileParser-Cloud | /Packages/UtilFunctions/Exceptions.py | 472 | 3.65625 | 4 | # Exceptions.py
"""
This is a file which contains class to print user defined exception
"""
class MyError(Exception):
def __init__(self, exceptionName: str, exceptionString: str):
self.exceptionName = exceptionName
self.exceptionString = exceptionString
def __str__(self):
return repr(self.exceptionName, self.exceptionString)
def __repr__(self):
return '{0} Exception : {1}'.format(self.exceptionName, self.exceptionString) |
0138a3c358ce0e8e9c956654f69f130b017a7f98 | Arif-Badhon/Python_-Code | /Random_Code/Character_input.py | 438 | 4.34375 | 4 | #Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
#Input
name = input("Insert your name: ")
age = int(input("Insert your age: "))
#Code to get the year when he or she will turn to 100 years old
year = (100 - age) + 2019
year = str(year)
#Print the command
print(name + "you will be 100 years old in " + year) |
7f68dd1ba7b4137ff69858923b52f6d902378fc7 | TwoBitN8/code_workout | /2/dicionary-sample.py | 1,165 | 3.625 | 4 | #! /usr/bin/env python
from __future__ import print_function
import argparse
import os
def get_dictionary_list(dct_filename):
dct_filename = os.path.realpath(dct_filename)
if not dct_filename:
return False
else:
with open(dct_filename) as f:
dct = f.readlines()
return dct
def count_words(dct, prefix):
num = 0
for i in dct:
if i.startswith(prefix):
num += 1
return num
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-D',
'--dictionary_file',
help='Linux dictionary file. Default: %(default)s',
default='/usr/share/dict/american-english')
parser.add_argument('-p',
'--prefix',
help='The word prefix to count. Default=%(default)s',
default='tim')
args = parser.parse_args()
dct_list = get_dictionary_list(args.dictionary_file)
prefix_count = count_words(dct_list, args.prefix)
print('{prefix} {num}'.format(prefix=args.prefix, num=prefix_count))
if __name__ == '__main__':
main()
|
842b6b5c5c401e95d0971abd1803580cfb115c83 | Milstein-Corp/exercises | /reverse-string/main.py | 1,621 | 3.703125 | 4 | # Definition for singly-linked list.
class Solution(object):
def reverseStringd(self, s):
"""95 percentile runtime"""
n = int(len(s)//2)
for i in range(n):
s[i], s[-i-1] = s[-i-1], s[i]
return s
def reverseString(self, s):
"""95 percentile runtime"""
i, j = 0, len(s)-1
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return s
if __name__ == '__main__':
s = ["r", "a", "c", "e", "c", "a"]
actual = Solution.reverseString(Solution, s.copy())
print("input: " + str(s))
print("actual: " + str(actual))
print("desired: " + str(s[::-1]))
assert actual == s[::-1]
print()
s = ["r", "a", "c", "e", "c", "a", "b"]
actual = Solution.reverseString(Solution, s.copy())
print("input: " + str(s))
print("actual: " + str(actual))
print("desired: " + str(s[::-1]))
assert actual == s[::-1]
print()
s = ["r", "a"]
actual = Solution.reverseString(Solution, s.copy())
print("input: " + str(s))
print("actual: " + str(actual))
print("desired: " + str(s[::-1]))
assert actual == s[::-1]
print()
s = ["r"]
actual = Solution.reverseString(Solution, s.copy())
print("input: " + str(s))
print("actual: " + str(actual))
print("desired: " + str(s[::-1]))
assert actual == s[::-1]
print()
s = []
actual = Solution.reverseString(Solution, s.copy())
print("input: " + str(s))
print("actual: " + str(actual))
print("desired: " + str(s[::-1]))
assert actual == s[::-1]
print()
|
de28ec0b26ef3435bff089cdc061ff26d49d1e07 | KartikeySharma/programming | /Python/SPOJsolutions/spoj_fact_Z(N).py | 266 | 3.9375 | 4 | # your code goes here
def Z(n):
summ = 0
while(n//5>=1):
summ+=n//5
n=n//5
return summ
t=int(input())
while t:
p = int(input())
print(Z(p))
t-=1
#source :http://www.purplemath.com/modules/factzero.htm
#source :https://en.wikipedia.org/wiki/Trailing_zero
|
46a79f91ba841349fcf0c4dc52633aec6202ab50 | webmedic/booker | /src/utils.py | 2,218 | 3.90625 | 4 | # -*- coding: utf-8 -*-
import os
import string
import re
def slugify(value):
"""Converts to lowercase, removes non-alpha chars
and converts spaces to hyphens"""
value = re.sub('[^\w\s-]', '', value).strip().lower()
return re.sub('[-\s]+', '-', value)
def validate_ISBN10(isbn):
"""
Validate ISBN10 code. Returns the ISBN or False if is not valid.
"""
isbn = isbn.replace("-", "").replace(" ", "")
if len(isbn) == 10 and not [x for x in isbn if x not in (
string.digits + "X")]:
total = 0
for i in range(9):
total += int(isbn[i]) * (10 - i)
z = (11 - (total % 11)) % 11
if (z == 10 and isbn[-1] == 'X') or ("%d" % z == isbn[-1]):
return isbn
else:
return False
def validate_ISBN13(isbn):
"""
Validate ISBN13 code. Returns the ISBN or False if is not valid.
"""
# El chequeo para ISBN de 13 digitos sale de:
# ref:
# http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-13
isbn = isbn.replace("-", "").replace(" ", "")
if len(isbn) == 13 and not [x for x in isbn if x not in string.digits]:
i = 1
total = 0
for n in isbn[:-1]:
total = total + i * int(n)
if i == 1:
i = 3
else:
i = 1
check = 10 - (total % 10)
if check == int(isbn[-1]):
return isbn
else:
return False
def validate_ISBN(isbn):
"""
Validate ISBN13 or ISBN10 code. Returns the ISBN or False if any is valid.
"""
return validate_ISBN10(isbn) or validate_ISBN13(isbn)
SCRIPTPATH = os.path.abspath(os.path.dirname(__file__))
BASEPATH = os.path.expanduser(os.path.join('~', '.aranduka'))
BOOKPATH = os.path.join(BASEPATH, 'ebooks')
COVERPATH = os.path.join(BASEPATH, 'covers')
PLUGINPATH = [os.path.join(BASEPATH, 'plugins'),
os.path.join(SCRIPTPATH, 'plugins')]
for P in [SCRIPTPATH, BASEPATH, BOOKPATH, COVERPATH] + PLUGINPATH:
if not os.path.isdir(P):
os.makedirs(P)
VALID_EXTENSIONS = ['epub', 'fb2', 'mobi', 'pdf', 'txt',
'lit', 'html', 'htm', 'cbz', 'cbr', 'cb7']
|
c1b60f6560ebfbba9efe35cd99cb30086d81aedc | jamesmold/learning | /aoc2a.py | 513 | 3.546875 | 4 | from collections import Counter
fhand = open("aoc2.txt")
lines = [x.strip() for x in fhand] #removes the new lines from the input file aoc2.txt
def part2():
for line1 in lines: #nested for loop - takes the first line...
for line2 in lines: #then the first line again, followed by the 2nd, 3rd etc - then restarts by taking the 2nd line and the first
x = ''.join(a for a, b in zip(line1, line2) if a == b)
if len(x) == len(line1) - 1:
return x
print(part2()) |
8b2a23cb9e43c372cf117d0ed1d1dc1bed3eefdb | bala4rtraining/python_programming | /python-programming-workshop/test/pythondatastructures/class/use_repr_method.py | 740 | 4.40625 | 4 |
#Repr. This accesses the __repr__ method from a class. Repr stands for
#"representation." It converts an object into a string representation.
#Here we display Snake instances in a special way.
#Tip: We return a string from the repr method. The print method automatically
#calls an object's __repr__ method.
#And: We can call repr to force the __repr__ method to be used. This lets us
#store the representation string in a variable.
#Python program that uses repr
class Snake:
def __init__(self, type):
self.type = type
def __repr__(self):
return "Snake, type = " + self.type
# Create Snake instance.
# ... Print its repr.
s = Snake("Anaconda")
print(s)
# Get repr of Snake.
value = repr(s)
print(value)
|
e92ecb4a1dee3319e4a9cfeafea06e101408d292 | chaoswang/iUsePython | /basic/basic012.py | 659 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-12-24 21:44:13
# @Author : chaoswang (263050006@qq.com)
# @Link : https://github.com/chaoswang/
# @Version : $Id$
try:
int('abc')
except Exception as e:
print('出错啦:' + str(e))
else:
print('没有任何异常')
finally:
print('结束')
try:
f = open('data.txt', 'w')
for each_line in f:
print(each_line)
except OSError as e:
print('出错啦:' + str(e))
finally:
f.close()
# 用with后不需要处理文件关闭,程序会自动关闭资源
try:
with open('data.txt', 'w') as f:
for each_line in f:
print(each_line)
except OSError as e:
print('出错啦:' + str(e))
|
c51fa88dc1121dd9836af67a74c51360300cbf06 | ashokmeghvanshi/CP-CIPHER-Assignments | /Day-04 Leetcode Stacks And Queue/Valid Parentheses.py | 615 | 4.125 | 4 |
def IsValid(string):
stack=[]
for i in string:
if i in ['(','{','[']: stack.append(i)
else:
if not stack:
return False
stacktop=stack.pop()
if stacktop=='(':
if i!=')':
return False
if stacktop=='{':
if i!='}':
return False
if stacktop=='[':
if i!=']':
return False
if len(stack)>0:
return False
return True
print(IsValid('{}(){[()]}'))
print(IsValid('{}(()]}'))
|
1324d7ce5c956701adfc81570d6c1eacafa4620f | crowddynamics/crowddynamics-research | /data_analysis/recursive_mean.py | 1,869 | 3.859375 | 4 | import numpy as np
def recursive_mean(data, chunk):
"""
Calculate mean of data array recursively by averaging a "chunk" of the data.
Parameters
----------
data : array, float
Input data
chunk : integer
Size of chunk
Returns
-------
time_sample_average : array
Data array averaged over time.
"""
# Return the largest integer smaller or equal to the division of the first dimension of data array and chunk size.
divider = np.floor_divide(data.shape[0], chunk)
# Computes the remainder complementary to the floor_divide function.
remainder = np.remainder(data.shape[0], chunk)
# Initialize array that is returned.
time_sample_average = np.zeros((data.shape[1], data.shape[2]), dtype=np.float16)
# Calculate mean of data array recursively by taking averaging a "chunk" of the data.
for zzz in range(0,divider+1):
# If remainder only left, calculate take the average of the remainder.
if zzz == divider:
if remainder == 0:
break
elif remainder == 1:
temp_mean = data[chunk * zzz + remainder - 1, :, :]
else:
temp_mean = np.mean(data[chunk * zzz:chunk * zzz + remainder -1, :, :], axis=0, dtype=np.float16)
time_sample_average = (time_sample_average * chunk * zzz + temp_mean * remainder) /\
(chunk * zzz + remainder)
else:
if chunk == 1:
temp_mean = data[chunk * zzz, :, :]
else:
temp_mean = np.mean(data[chunk * zzz:chunk * (zzz+1)-1, :, :], axis=0, dtype=np.float16)
time_sample_average = (time_sample_average * chunk * zzz + temp_mean * chunk) / \
(chunk * (zzz + 1))
return time_sample_average
|
75be0cdb27de9783299fa819fe3f7690e735c7c4 | sheindyfr/Least-Squares-Rule | /main.py | 1,940 | 4 | 4 | '''
--------------------------------------------------------
Description: running several examples of approximating a
function in an interval by a function basis
1) Fourier serias
2) any basis
Authors: Ayala Barazani & Sheindy Frenkel
Date: 09/03/2021
Files: numerical_integration.py
linear_systems.py
least_squares.py
main.py
Dependencies: numpy, matplotlib
--------------------------------------------------------
'''
from least_squares import *
import matplotlib.pyplot as plt
import numpy as np
def create_fourier_basis():
# Fourier serias
a1 = lambda x: 1/math.sqrt(2*math.pi)
a2 = lambda x: (1/math.sqrt(math.pi))*math.cos(x)
a3 = lambda x: (1/math.sqrt(math.pi))*math.cos(x)
return [a1, a2, a3]
def create_basis():
a1 = lambda x: 1
a2 = lambda x: math.cos(x)
a3 = lambda x: math.cos(3*x)
return [a1, a2, a3]
def create_func1():
f = lambda t: abs(t)
return f
def create_func2():
f = lambda t: t**2 + abs(t)
return f
def get_approx_func(basis, coefficient):
ff = lambda x: calculate_approximate(x, basis, coefficients)
return ff
def graph(func, x_range, cl='r--'):
y_range=[]
for x in x_range:
y_range.append(func(x))
plt.plot(x_range, y_range, cl)
return
def plot_graphs(f, ff):
rs=1.0
r=np.linspace(-rs*np.pi,rs*np.pi,80)
graph(ff,r,cl='r-')
graph(f,r,cl='b--')
plt.axis('equal')
plt.show()
if __name__ == "__main__":
basis = create_fourier_basis()
f = create_func1()
coefficients, error = least_squares(basis, f, -math.pi, math.pi)
print(f'\nERROR: {error}')
ff = get_approx_func(basis, coefficients)
plot_graphs(f, ff)
basis = create_basis()
f = create_func2()
coefficients, error = least_squares(basis, f, -math.pi, math.pi)
print(f'\nERROR: {error}')
ff = get_approx_func(basis, coefficients)
plot_graphs(f, ff) |
55cfdaa7859a1031f894683344cf29a265d518c6 | PSquared0/Assessment_Classes | /assessment.py | 2,716 | 4.6875 | 5 | """
Part 1: Discussion
1. What are the three main design advantages that object orientation
can provide? Explain each concept.
Encapsulation:
where the complexity of the created object is hidden. It helps us understand what
the function for that class does easily wihtout having to look at all the
code and keeps our code for that object simple. An analogy would be knowing how to
drive a car without knowing how it works.
Abstraction:
It refers to presenting essential features without including
the background details or specifcs.
Polymorphism:
Creating a function with the same name that can execute different functions
depending on the class.
2. What is a class?
A class is like a module you can call with the (dot) operator. you can group
together a bunch of functions (or methods) and data and then you can access them.
3. What is an instance attribute?
When you instantiate the class by calling the function you are creating as
an instance attribute. while class attributes belong to the class, instance
attributes belong the instance specifcially.
4. What is a method?
a funtion that is defined in eht class definition
5. What is an instance in object orientation?
a specifc object of a class.
6. How is a class attribute different than an instance attribute?
Give an example of when you might use each.
While class attributes belong to the class, instance
attributes belong the instance specifcially. The visual difference is that
when you are calling the class attribute you are using self (self.attribute) and when you call the
instance you replace self with the name of the instance (instance_name.attribute).
"""
# Parts 2 through 5:
class Student(object):
def __init__(self, first_name, last_name, address):
self.first_name = first_name
self.last_name = last_name
self.address = address
class Question(object):
def __init__(self, question, answer):
self.question = question
self.answer = answer
def show_question(self, question, correct_answer):
print self.question,
answer = raw_input("Enter answer here:")
return self.correct_answer == answer
class Exam(object):
def __init__(self, name):
self.name = name
self.question = []
def add_question(self, question, correct_answer):
new_question = (question, correct_answer)
self.question.append(new_question)
def admin(self, question, score):
score = 0
for question in Question:
if question.show_question == True:
score = score + 1
return score
|
76236997c1f6f0ab8006efbd0c28ae95c6a92348 | fastso/learning-python | /lib/traversal/bit_traversal/bit_traversal.py | 151 | 3.703125 | 4 | n = int(input())
for i in range(2 ** n):
temp = list()
for j in range(n):
if (i >> j) & 1:
temp.append(j)
print(temp)
|
9edd50218a5e567cf3b11ee1946205e8a171557b | jwu424/Leetcode | /MergeIntervals.py | 645 | 3.828125 | 4 | # Given a collection of intervals, merge all overlapping intervals.
# 1. Create a temp variable and compare each elem with its previous one.
# Time: O(N), Space: O(N)
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) <= 1:
return intervals
intervals.sort()
res = []
temp = intervals[0]
for elem in intervals[1:]:
if temp[-1] >= elem[0]:
temp = [temp[0], max(temp[-1], elem[-1])]
else:
res.append(temp)
temp = elem
res.append(temp)
return res
|
d33ebbfe91aae4585b013f95995bc63cce8fd580 | KAVILSHAH1101/Extra_m | /practical10/p10_02.py | 714 | 3.921875 | 4 | class Person:
count=0;
def __init__(self):
print("default constructor callled...");
Person.count=Person.count+1;
def input(self,name,age):
self.name=name;
self.age=age;
def display(self):
print("name=",self.name);
print("age=",self.age);
@classmethod
def clmethod(cls):
return ' number of objects=',format(Person.count);
@staticmethod
def stmethod():
print("number of objects in class=",Person.count);
p1=Person();
p1.input("mansi",21);
print(p1.display());
p2=Person();
p2.input("priya",25);
print(p2.display());
print(Person.clmethod());
Person.stmethod();
|
a8ecbb89b15e22a9d6587c8429704f234f3cce9e | samineup0710/geneses_pythonassignment3rd | /checkingstring.py | 649 | 3.953125 | 4 | userinput = input("enter a input in strings:")
import re
"""set counters"""
upp=0
sc =0
num = 0
"""checking and counting"""
for ch in userinput:
if (ch>='a'and ch<='z'):
low = low+1
if(ch>='A' and ch<='Z'):
upp = upp+1
if re.match("^[!@#$%^&*()_]*$", ch): #regex checking special character pattern
sc = sc+1
if re.match("^[0-9]", ch):
num = num+1
print("The num of lowercase char in string is {}".format(low))
print("The num of uppercase char in string is {}".format(upp))
print("The num of special char in string is {}".format(sc))
print("The num of digitnumber in string is {}".format(num))
|
b9dc899e85ceda8e6f6df36057724ea64fa42eaf | LKHUUU/SZU_Learning_Resource | /计算机与软件学院/Python程序设计/实验/实验3/problem5.py | 601 | 3.953125 | 4 | def is_almost_symmetric(list1):
if list1 == list1[::-1]:
return False, None, None
for i in range(len(list1)):
for j in range(i+1, len(list1)):
temp = list1[:]
temp[i], temp[j] = temp[j], temp[i]
if temp == temp[::-1]:
return True, i, j
return False, None, None
list1 = [1, 2, 2, 3, 7, 1]
bool, i, j = is_almost_symmetric(list1)
if bool:
print("{}是“几乎对称”列表,交换第{}和第{}个元素".format(list1, i+1, j+1))
else:
print("{}不是“几乎对称”列表".format(list1))
|
60b16a5a9bc85e0f320aff3a2df9025f6fa0518a | DarrenChiang/Python-2016 | /HW16/Pascal.py | 1,301 | 3.8125 | 4 | def pascal(rows, items = [1], iteration = 1):
printRow(rows, items)
items.insert(0, 0)
items.insert(len(items), 0)
if iteration < rows:
nItems = []
for i in range(len(items)):
if i < len(items) - 1:
nItems.append(items[i] + items[i + 1])
pascal(rows, nItems, iteration + 1)
def printRow(rows, items):
length = rows * 2 - 1
cItems = []
for i in range(len(items)):
cItems.append(items[i])
if i < len(items) - 1:
cItems.append(0)
void = int((length - len(cItems)) / 2)
if rows <= 5:
for i in range(void):
cItems.insert(0, " ")
cItems.insert(len(cItems) , " ")
for i in range(len(cItems)):
if cItems[i] == 0:
cItems[i] = " "
else:
for i in range(void):
cItems.insert(0, " ")
cItems.insert(len(cItems) , " ")
for i in range(len(cItems)):
if cItems[i] == 0:
cItems[i] = " "
else:
cItems[i] = " " + str(cItems[i])
if len(cItems[i]) < 3:
cItems[i] += " "
for i in cItems:
print(i, end = "")
print()
pascal(int(input("How many rows? ")))
|
527b6b770bc678a1ca809579e3076fe00ae685a9 | lidongdongbuaa/leetcode2.0 | /链表/链表排序与划分/328. Odd Even Linked List.py | 1,861 | 4.34375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/11/4 9:13
# @Author : LI Dongdong
# @FileName: 328. Odd Even Linked List.py
''''''
'''
题目分析
1.要求:Given a singly linked list, group all odd nodes together followed by the even nodes.
Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place.
The program should run in O(1) space complexity and O(nodes) time complexity.
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on .
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
2.理解:把合并后的奇数位的node放在合并后的偶数位的node之前,只能改变next,不能用list存储法
3.类型:链表转置
4.方法及方法分析:奇偶合并法
time complexity order: 奇偶合并法O(N)
space complexity order: 奇偶合并法O(1)
'''
'''
奇偶合并法
思路:head指向3/5/7;headnext指向2/4/6
方法:及时保存head.next;及时保存头节点;改变next指向
边界条件:head = None, head.next = None, head.next.next = None
time complex: O(N)
space complex: O(1)
易错点:while head.next and head.next.next 不是or
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if head == None or head.next == None or head.next.next == None:
return head
prev_head = head
prev_next_head = head.next
while head.next and head.next.next:
next_head = head.next
head.next = head.next.next
next_head.next = next_head.next.next
head = head.next
head.next = prev_next_head
return prev_head
|
caee4aa75dbf8f1863969e82f96394c47f1c74af | JeonJe/Algorithm | /백준/Bronze/11328. Strfry/Strfry.py | 159 | 3.515625 | 4 | n = int(input())
for _ in range(n):
fr, to = map(list,input().split())
fr.sort()
to.sort()
print("Possible" if fr == to else "Impossible") |
a9bcc769d46070914a62215980f370cf5d680e76 | bendanwwww/myleetcode | /code/lc38.py | 1,538 | 3.671875 | 4 | """
给定一个正整数 n(1 ≤ n ≤ 30),输出外观数列的第 n 项。
注意:整数序列中的每一项将表示为一个字符串。
「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。前五项如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221
第一项是数字 1
描述前一项,这个数是 1 即 “一个 1 ”,记作 11
描述前一项,这个数是 11 即 “两个 1 ” ,记作 21
描述前一项,这个数是 21 即 “一个 2 一个 1 ” ,记作 1211
描述前一项,这个数是 1211 即 “一个 1 一个 2 两个 1 ” ,记作 111221
示例 1:
输入: 1
输出: "1"
解释:这是一个基本样例。
示例 2:
输入: 4
输出: "1211"
解释:当 n = 3 时,序列是 "21",其中我们有 "2" 和 "1" 两组,"2" 可以读作 "12",也就是出现频次 = 1 而 值 = 2;类似 "1" 可以读作 "11"。所以答案是 "12" 和 "11" 组合在一起,也就是 "1211"。
"""
class Solution(object):
def countAndSay(self, n):
res = '1'
for i in range(1, n):
l = res[0]
num = 1
resTmp = ''
for x in range(1, len(res)):
if res[x] == l:
num+= 1
else:
resTmp+= str(num) + l
l = res[x]
num = 1
resTmp+= str(num) + l
res = resTmp
return res
s = Solution()
res = s.countAndSay(3)
print(res) |
46a1be52095cdafd0182572c7fc1a9ca9aa72e79 | namit-c/T-Rex_Acceleration | /src/Final_Version/Model/Score.py | 2,174 | 3.828125 | 4 | """@package docstring
Documentation for this module.
The player score class
Author: Dev^(enthusiases)
This class is responsible for the score of the player during the game session.
"""
from time import time
##
# @file Score.py
# @brief This is a class used to keep track of the player's score
class Score():
## @brief Constructor that initializes different fields required to track the
# player score. The parameters about the score (high score, current score,
# and previous score) are set to 0.
def __init__(self):
self.__high_score = 0
self.__current_score = 0
self.__previous_score = 0
self.__score_boost = 0
# Constant for the score boost
self.__SCORE_BOOST_VAL = 100
self.__SCALE_FACTOR = 5
## @brief Method to retrieve the current score of the game
# @return the current score of the game
def get_current_score(self):
return self.__current_score
## @brief Method that updates the current score
# @param start_time the time the current game starts
# @return the current and previous score after the score has been updated
def update_score(self, start_time):
self.__previous_score = self.__current_score
# Updating the current score based on current time and scale factor
self.__current_score = round((time()-start_time) * self.__SCALE_FACTOR + self.__score_boost*self.__SCORE_BOOST_VAL)
# Updating the high score if the current score is greater
if self.__current_score > self.__high_score:
self.__high_score = self.__current_score
return self.__current_score, self.__previous_score
## @brief Method to retrieve the high score of the current game session
# @return the high score of the current game session
def get_score(self):
return self.__high_score
## @brief Method to change the current score and score boost to 0 for the next game
def reset_score(self):
self.__current_score = 0
self.__score_boost = 0
## @brief Method to indicate the score boost powerup is acquired
def boost(self):
self.__score_boost += 1 |
75ffa459ce02e3a717fd2d0860d3eafc544d061c | Shinakshi09/Python | /09_votes_report.py | 313 | 4.15625 | 4 | """ Voter's Report """
print("_______Voter's Report_________")
name = input("Please enter your name here : ")
age = int(input("Please enter your age here : "))
if age>18:
print(name + " " + "can vote in the election")
else :
print(" I am sorry" + " " + name + " Please wait till you are 18 Years old" |
023a80819a9e0289d1ed39af8a942801262e8436 | RodrigoMoro3736/Python | /ex054.py | 387 | 3.796875 | 4 | import time
anoAtual = time.localtime().tm_year
maior = 0
menor = 0
anoNascimento = 0
for c in range(1, 8):
anoNascimento = int(input('Digite o ano de nascimento: '))
if (anoAtual - anoNascimento) >= 21:
maior += 1
elif (anoAtual - anoNascimento) < 21:
menor += 1
print(f'{menor} pessoas são menores de 21 anos!\n{maior} pessoas são maiores de 21 anos!')
|
1847ab49fe4bf8f67c367a67b7fb605518ffad11 | Chiedu99/HelloWorld | /hello.py | 959 | 4.625 | 5 | #Chiedu Nduka-eze
#Friday, September 16
import math
import turtle
print("This program will calculate the acute angle of two different and connected coordinates starting from the origin.")
#this allows the user to input his coordinates
x1 = int(input("insert the first x coordinate:"))
y1=int(input("insert first y coordinate:"))
x2 = int(input("insert the second x coordinate:"))
y2 = int(input("insert the second y coordinate:"))
#these are the slopes of the two lines that are created
m1 = (y1 / x1)
m2 = (y2 - y1) / (x2 - x1)
print(m1)
print(m2)
#This makes the turtle draw the lines the user inputs
turtle.goto(x1 , y1)
turtle.goto(x2 , y2)
#This the the trigonometry that we use to calcluate the created angle in radians
tangent = (abs(m2 - m1)) / (1 + m1 * m2)
print(tangent)
math.atan(tangent)
#This changes the radians we calculated to degrees
angleInDegrees = (tangent) * 180 / math.pi
print(angleInDegrees)
turtle.write(angleInDegrees)
turtle.done()
|
6a0bfa9bed4cd7722562af75d35851f5839c2c18 | boisvert42/npr-puzzle-python | /2018/1021_beermouth.py | 918 | 3.828125 | 4 | #!/usr/bin/python
'''
NPR 2018-10-21
https://www.npr.org/2018/10/21/659245659/sunday-puzzle-find-the-missing-link
Take the 9 letters of BEER MOUTH. Arrange them in a 3x3 array so that
the three lines Across, three lines Down, and both diagonals spell
common 3-letter words. Can you do it?
'''
import sys
sys.path.append('..')
import nprcommontools as nct
import itertools
#%%
common_words = set(x.upper() for x in nct.get_common_words(source='definitions'))
WORD = 'BEERMOUTH'
for arr in itertools.permutations(WORD,len(WORD)):
s = ''.join(arr)
s1,s2,s3 = s[:3],s[3:6],s[6:9]
if s1 in common_words and s2 in common_words and s3 in common_words:
t = []
for i in range(3):
t1 = s1[i] + s2[i] + s3[i]
t.append(t1)
if t[0] in common_words and t[1] in common_words and t[2] in common_words:
print('{0}\n{1}\n{2}'.format(s1,s2,s3))
print()
|
cd3003fc2e16cc40ba0721ce44207bcdffdaeef5 | khushboobajaj25/Python | /Testing/list.py | 644 | 3.9375 | 4 | nums = [10, 20, 30, 40]
print(nums)
nums.insert(2, 35)
print(nums)
del(nums[1])
print(nums)
nums.remove(40)
print(nums)
print(nums[-1])
nums = [23, 25, 38]
print(nums.append(45))
names = ["Anisha", "Khushboo", "Karan"]
mil = [nums, names]
print(mil)
# print(nums.pop(1))
del(nums[2:])
print(nums)
nums.extend([16, 5, 54])
print(nums)
print(min(nums))
print(max(nums))
print(sum(nums))
nums.sort()
print(nums)
# nums.clear()
# print(nums)
new = nums.copy()
print(new)
print(nums.count(25))
print(nums.index(54))
nums.reverse()
print(nums)
print(nums.__contains__(25))
print(nums.__getitem__(2))
nums.__delitem__(2)
print(len(nums))
|
be3ae721da2dd0f2049954d75c4e28ecf9810ccd | mhdaimi/club_manager | /3PinAuth/ThreePinAuth.py | 4,317 | 3.609375 | 4 | import sqlite3
class ThreePinAuth():
def __init__(self):
pass
def check_database(self):
self.conn = sqlite3.connect("pin_database.db")
self.cur = self.conn.cursor()
self.cur.execute("Create table IF NOT EXISTS pins (Id INT, pin INT, last_used TEXT )")
self.conn.commit()
self.cur.execute("Create table IF NOT EXISTS failed_tries (pin_id INT)")
self.conn.commit()
self.cur.execute("Create table IF NOT EXISTS account_details (email TEXT, password TEXT)")
self.conn.commit()
def check_if_3_pin_enabled(self):
query="Select * from pins"
self.cur.execute(query)
recs = self.cur.fetchall()
if len(recs) == 0:
print "3 pin authentication not enabled"
print recs
elif len(recs) == 3:
print "3 pin authentication enabled"
self.data = recs
def pin_to_ask(self):
next_pin=0
first_use_check=0
last_used_pin=0
self.check_if_3_pin_enabled()
for each_rec in self.data:
last_used = each_rec[2].encode("utf-8")
print each_rec, last_used
if last_used == "Yes":
last_used_pin = each_rec[0]
next_pin = last_used_pin + 1
if next_pin >= 3 :
next_pin = 0
break
else:
first_use_check += 1
if first_use_check == 3:
return self.data[next_pin][1], next_pin, ""
else:
return self.data[next_pin][1], next_pin, last_used_pin
def ask_pin(self):
pin,pin_id,last_pin_id = self.pin_to_ask()
i=0
while (i < 3):
i+=1
user_pin = int(raw_input("Enter your PIN (%d)" %int(pin_id+1)))
if user_pin == pin:
print "Success"
if not last_pin_id:
args = [" ",0]
else:
args = [" ",last_pin_id]
sql = "Update pins SET last_used=? where Id=?"
self.cur.execute(sql,args)
self.conn.commit()
#
sql = "Update pins SET last_used=? where Id=?"
args = ["Yes",pin_id]
self.cur.execute(sql,args)
self.conn.commit()
break
else:
print "False PIN, Try again!"
else:
self.incorrect_tries(pin_id,last_pin_id)
def incorrect_tries(self, pin_id,last_pin_id):
sql = "insert into failed_tries VALUES (?) "
args=[pin_id]
self.cur.execute(sql,args)
self.conn.commit()
args = [" ",last_pin_id]
sql = "Update pins SET last_used=? where Id=?"
self.cur.execute(sql,args)
self.conn.commit()
sql = "Update pins SET last_used=? where Id=?"
args = ["Yes",pin_id]
self.cur.execute(sql,args)
self.conn.commit()
self.check_invalid_tries()
def check_invalid_tries(self):
query="Select * from failed_tries"
self.cur.execute(query)
recs = self.cur.fetchall()
print recs
if len(recs) == 2:
print "2 invalid tries found, please use id to unlock!"
self.use_id_to_unlock()
print recs
else:
self.ask_pin()
def use_id_to_unlock(self):
print "Use ID"
email = raw_input("Enter email id")
password = raw_input("Enter Password")
query = "Select * from account_details"
self.cur.execute(query)
recs = self.cur.fetchall()
if email == recs[0] and password == recs[1]:
query="Delete from failed_tries"
self.cur.execute(query)
self.conn.commit()
else:
print "Kuch toh gadbad hai!"
def main(self):
self.check_database()
self.check_invalid_tries()
#self.ask_pin()
pin3 = ThreePinAuth()
pin3.main() |
8127c10cc30eea1ff8749e7af4f46868d063fe01 | mahikkaaa/python_practice | /conditional_statement.py | 1,083 | 4.15625 | 4 | #conditional statement
#program to check if the entered number is even or not
x = int(input("enter any number"))
s=x/2
print(s)
if (x%2==0):
print("the entered number is even")
if(x%2!=0):
print("the entered number is not even")
#program to check the passcode
a=["apple", "banana"]
x = input("enter the name of any fruit")
if (x==a[0]):
print("access given")
if (x==a[1]):
print("access given")
if (x!=a[1] and x!=[0]):
print("access denied")
#program to compare strings irrespective of their case(upper, lower)
a=["apple"]
b=a[0].capitalize()
c=input("enter the name of any fruit")
d=c.capitalize()
if (b==d):
print("you got it right")
if (b!=d):
print("better luck next time")
dictionary = {"a":"apple", "b":"banana", "c":"camel"}
d = input("enter any alphabet of your choice from a to c")
print(dictionary[d])
#number to character
a=int(input("enter any ascii value"))
m=chr(a)
print(m)
#character to number
k=input("enter any alphabet irrespective of upper case or lower case")
d=ord(k)
print(d)
|
49df72dc4ebac2c58c66be5f5bfa0812403db67d | Aeilko/Advent-of-Code-2020 | /day21/solution.py | 3,208 | 3.5 | 4 | import re
from utils.file import read_file_content
def solve_part1(inp: str) -> int:
inp = inp[:-1].split("\n")
ingredients = set()
allergens = {}
occurences = {}
for line in inp:
(ingredient, allergen) = re.search("([\w+ ]+)+ \(contains (\w+[, \w+]+)\)", line).groups()
ingrs = set(ingredient.split(" "))
allers = allergen.split(", ")
for i in ingrs:
ingredients.add(i)
if i in occurences:
occurences[i] = occurences.get(i) + 1
else:
occurences[i] = 1
for a in allers:
if a in allergens:
allergens.get(a).append(ingrs)
else:
allergens[a] = [ingrs]
impossible = ingredients
for a in allergens:
poss = set(ingredients)
for i in allergens.get(a):
poss = poss.intersection(i)
for p in poss:
impossible.remove(p)
r = 0
for i in impossible:
r += occurences.get(i)
return r
def solve_part2(inp: str) -> int:
inp = inp[:-1].split("\n")
ingredients = set()
allergens = {}
for line in inp:
(ingredient, allergen) = re.search("([\w+ ]+)+ \(contains (\w+[, \w+]+)\)", line).groups()
ingrs = set(ingredient.split(" "))
allers = allergen.split(", ")
for i in ingrs:
ingredients.add(i)
for a in allers:
if a in allergens:
allergens.get(a).append(ingrs)
else:
allergens[a] = [ingrs]
found = set()
translation = {}
while len(found) != len(allergens):
for a in allergens:
poss = set(ingredients)
for i in allergens.get(a):
poss = poss.intersection(i)
poss = poss-found
if len(poss) == 1:
word = poss.pop()
found.add(word)
translation[a] = word
sorted_translations = sorted(list(translation))
result = []
for s in sorted_translations:
result.append(translation.get(s))
return ",".join(result)
def test_part1():
inp = read_file_content("inputs/test")
answer = int(read_file_content("inputs/ans1"))
result = solve_part1(inp)
if result == answer:
print("Test successful")
else:
print("Test unsuccessful: " + str(result) + ", expected: " + str(answer))
def test_part2():
# There are no tests for part 2 in this case, but our answer was correct the first time, oh well.
inp = read_file_content("inputs/test")
answer = read_file_content("inputs/ans2")
result = solve_part2(inp)
if result == answer:
print("Test successful")
else:
print("Test unsuccessful: " + str(result) + ", expected: " + str(answer))
if __name__ == '__main__':
inp = read_file_content("inputs/input")
print(" --- Part 1 --- ")
test_part1()
print("Part 1 result:\t" + str(solve_part1(inp)))
print("\n --- Part 2 ---")
test_part2()
print("Part 2 result:\t" + str(solve_part2(inp)))
|
772e616498642e2dedd3180e9454b52ec987b32a | sebov/scikit-rough | /src/skrough/unique.py | 4,298 | 4.0625 | 4 | """Unique-related operations.
The :mod:`skrough.unique` module delivers helper functions for unique-related
computations. Currently all operations are simple wrappers around :func:`numpy.unique`
but they are here to provide interfaces that the rest of the code uses.
"""
from typing import Tuple
import numpy as np
def get_rows_nunique(x: np.ndarray) -> int:
"""Compute the number of unique rows.
Compute the number of unique rows. Degenerated tables are handled accordingly,
i.e., a table with no columns has 1 unique rows if only it has at least one row,
otherwise it is ``0``.
Args:
x: Input data table.
Returns:
Number of unique rows.
"""
return np.unique(x, axis=0).shape[0]
def get_uniques_positions(values: np.ndarray) -> np.ndarray:
"""Get positions of first occurrences of unique values.
Get positions/indices for which unique values in the input array appear for the
first time. The indices are reported in the order corresponding to the ascending
order of unique values, i.e., the first index indicates the first occurrence of the
lowest unique value, the second index indicates the first occurrence of the second
lowest unique value, etc.
Args:
values: Input array.
Returns:
The positions/indices of the input array for which unique values (reported in
ascending order) appear for the first time.
Examples:
>>> get_uniques_index(np.array([1, 2, 3]))
array([0, 1, 2])
>>> get_uniques_index(np.array([3, 2, 1]))
array([2, 1, 0])
>>> get_uniques_index(np.array([1, 1, 1]))
array([0])
>>> get_uniques_index(np.array([1, 1, 2, 1]))
array([0, 2])
>>> get_uniques_index(np.array([2, 2, 1, 2]))
array([2, 0])
>>> get_uniques_index(np.array([]))
array([])
"""
_, idx = get_uniques_and_positions(values)
return idx
def get_uniques_and_positions(values: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Get unique elements of an array and indices of first occurrences of these values.
Get unique elements (reported in ascending order) of the input array ``values``
along with the positions/indices in the input array for which unique values appear
for the first time.
Args:
values: Input array.
Returns:
Result is a 2-element tuple consisted of the following elements
- unique values (reported in ascending order) of the input array
- position/indices in the input array for which unique values appear for the
first time
Examples:
>>> get_uniques_and_positions(np.array([2, 7, 1, 8, 2, 8, 1]))
(array([1, 2, 7, 8]), array([2, 0, 1, 3]))
>>> get_uniques_and_positions(np.array([3, 3, 2, 1, 3]))
(array([1, 2, 3]), array([3, 2, 0]))
>>> get_uniques_and_positions(np.array([1, 3, 3, 2]))
(array([1, 2, 3]), array([0, 3, 1]))
"""
uniques, uniques_index = np.unique(values, return_index=True)
return uniques, uniques_index
def get_uniques_and_compacted(values: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Get unique values and compacted version of an input array.
Get unique elements (reported in ascending order) together with a compacted version
of the input array ``values``. The compacted array is consisted of indices of the
unique values that can be used to reconstruct the original array.
Args:
values: Input array.
Returns:
Result is a 2-element tuple consisted of the following elements
- unique values (reported in ascending order) of the input array
- compacted version of the input array in the form of indices of unique values
that can be used to reconstruct the original input array
Examples:
>>> get_uniques_and_compacted(np.array([1, 2, 3]))
(array([1, 2, 3]), array([0, 1, 2]))
>>> get_uniques_and_compacted(np.array([3, 2, 1]))
(array([1, 2, 3]), array([2, 1, 0]))
>>> get_uniques_and_compacted(np.array([33, 11, 33, 33, 22]))
(array([11, 22, 33]), array([2, 0, 2, 2, 1]))
"""
uniques, uniques_inverse = np.unique(values, return_inverse=True)
return uniques, uniques_inverse
|
b7ec110e4c23b53cf72a78bce2274bc606fcc2d5 | zingzheng/LeetCode_py | /135Candy.py | 866 | 3.546875 | 4 | ##Candy
##There are N children standing in a line. Each child is assigned a rating value.
##You are giving candies to these children subjected to the following requirements:
##Each child must have at least one candy.
##Children with a higher rating get more candies than their neighbors.
##What is the minimum candies you must give?
##
##2015年9月21日 13:54:40 AC
##zss
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
can=[1]*len(ratings)
for i in range(1,len(ratings)):
if ratings[i-1]<ratings[i]:
can[i]=can[i-1]+1
print(can)
for i in range(len(ratings)-2,-1,-1):
if ratings[i+1]<ratings[i] and can[i]<=can[i+1]:
can[i]=can[i+1]+1
print(can)
return sum(can)
|
49e0d904854b85d800633292f0477680f98c571a | ARUNDHATHI1234/Python | /co1/program14.py | 120 | 3.984375 | 4 | n=int(input("enter a number:"))
s=str(n)
nn=s+s
nnn=s+s+s
temp=n+int(nn)+int(nnn)
print("the valueof n+nn+nnn is:",temp) |
a5cf9c2f1b3500b798f1e8b323686a6d9a635ba0 | epasseto/pyprog | /UdacityProgrammingLanguage/Course/src/M4_PouringProblem.py | 2,975 | 3.71875 | 4 | #! /usr/bin/python
# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="epasseto"
__date__ ="$08/05/2012 08:20:53$"
import doctest
#write notes with your class items and function items and automatically run out this tests
class Test: """
>>> successors(0, 0, 4, 9)
{(0, 9): 'fill Y', (0, 0): 'empty Y', (4, 0): 'fill X'}
>>> successors(3, 5, 4, 9)
{(4, 5): 'fill X', (4, 4): 'X<-Y', (3, 0): 'empty Y', (3, 9): 'fill Y', (0, 5): 'empty X',
>>> successors(3, 7, 4, 9)
{(4, 7): 'fill X', (4, 6): 'X<-Y', (3, 0): 'empty Y', (0, 7): 'empty X', (3, 9): 'fill Y',
>>> pour_problem(4, 9, 6)
[(0, 0), 'fill Y', (0, 9), 'X<-Y', (4, 5), 'empty X', (0, 5), 'X<-Y', (4, 1), 'empty X', (0
## What problem, with X, Y, and goal < 10, has the longest solution?
## Answer: pour_problem(7, 9, 8), with 14 steps
>>> def num_actions(triplet): X, Y, goal = triplet; return len(pour_problem(X, Y, goal)) //
>>> def harness(triplet): X, Y, goal = triplet; return num_actions((X, Y, goal)) - max(X,
>>> max([(X, Y, goal) for X in range(1, 10) for Y in range(1, 10)
... for goal in range(1, max(X, Y))], key=num_actions)
(7, 9, 8)
>>> max([(X, Y, goal) for X in range(1, 10) for Y in range(1, 10)
... for goal in range(1, max(X, Y))], key=hardness)
(7, 9, 8)
>>> pour_problem(7, 9, 8)
[(0, 0), 'fill Y', (0, 9), 'X<-Y', (7, 2), 'empty X', (0, 2), 'X<-Y', (2, 0), 'fill Y, (2
"""
def pour_problem(X, Y, goal, start=(0,0)):
#X and Y are the capacity of glasses
#(x,y) is current fill levels and represents a state
#The goal is a level that can be in either glass
#start at start state and follow successors until we reach the goal
#keep track of frontier and previously explored
#fail when no frontier
if goal in start:
return [start]
explored = set() #set of states whe have visited
frontier = [[start]] #ordered list of paths we have blazed
while frontier:
path = frontier.pop(0) #pull element of the begin of the frontier
(x, y) = path[-1] #last state in the first paht of the frontier
for (state, action) in successors(x, y, X, Y).items():
if state not in explored:
explored.add(state)
path2 = path + [action, state]
if goal in state:
return path2
else:
frontier.append(path2)
return Fail
Fail = []
def successors(x, y, X, Y):
#return a dict of {state:action} pairs describing
#what can be reached from the (x, y) state, and how
assert x <= X and y <= Y #(x, y) is glass levels; X and Y are glass sizes
return {((0, y+x) if y+x<=Y else (x-(Y-y), y+(Y-y))):'X->Y',
((x+y, 0) if x+y<=X else (x+(X-x), y-(X-x))):'X<-Y',
(X, y):'fill X', (x, Y):'fill Y',
(0,y):'empty X', (x, 0):'empty y'}
print doctest.testmod() #TestResults(failed=0, attempted=9) |
b0ce2ad95582f41d4d910c5fd74d37fa688b39a9 | WASSahasra/sclPython | /Select. Not Select 1st.py | 157 | 4 | 4 | x=int(input("Enter Mark 1 "))
y=int(input("Enter Mark 2 "))
if x>=50 and y>=50:
print("You Are Selected")
else:
print("You Are Not Selected")
|
ec1d5f0d7640ba2c4a02f8af0be210943b6bfac6 | mutheefrank/python_exercises | /hw1 exercises/loops.py | 1,867 | 3.984375 | 4 | # Muthee Francis
# loops.py
# Oct 18, 2015
# Exercise 2.2
# imports
from __future__ import division
# part 1 ( A program that prints decimals)
def decimalEquivalents():
my_numbers = range(2,11)
#round the decimals to two decimal places and print
for x in my_numbers:
print round( (1/x), 2)
# Part 2 (A program that prompts for a number and loops to zero)
def loopInput():
user_number = raw_input ('Please enter a number : ')
try:
val = int(user_number)
if val < 0 :
print 'please enter a positive number'
elif val > 50 :
print 'The number is too big, enter a small number'
else:
print str(val) + '\n'
while (val):
val = val - 1
print (val)
print ''
except ValueError:
print('please enter a number')
# part 3 (A program that calculates exponentials)
def calculateExponent():
try:
base = int(raw_input('Please enter a base : '))
expo = int(raw_input('Please enter an exponent : '))
for i in range(0, expo):
print (base ** expo)
expo = expo - 1
print (base ** expo)
except ValueError:
print 'Please enter a number'
# Part 4 (program that lets the user enter an even number)
def evenNumber():
try:
while True:
user_number =float(raw_input('Please a number divisible by two : '))
print type (user_number)
if (user_number % 2) != 0 :
print 'Sorry !!! Please try again'
else:
print 'Congratulations !!! You entered a number divisible by two'
break
except ValueError:
print 'Please enter a number'
#function calls
#decimalEquivalents()
#loopInput()
calculateExponent()
#evenNumber()
|
b36f5d7806f2e4d271fec57bcd561291fa319beb | pedrolucas-correa/ies-python-lists | /Lista3/Lista 3 - Q. 24.py | 255 | 3.859375 | 4 | prim = int(input("Digite um número: "))
c = 0
for n in range(1, prim + 1):
if prim % n == 0:
c += 1
else:
continue
if c == 2:
print("{} é primo.".format(prim))
else:
print("{} não é primo.".format(prim))
|
49053d3584156b71bccf92404d0069573ff4dddb | janlee1020/Python | /processCookies2019.py | 2,579 | 3.8125 | 4 | #Janet Lee
#Lab M3
#processCookies.py
#Obtain information from the file cookieSales.txt.
#Print how many kids there are and their names.
#Print the total number of Samoas sold.
#From a line already read from a file, place the different
# pieces of data in well named variables of a good type.
def getCookieData(aLine):
aList=aLine.split()
name=aList[0] + ' ' + aList[1]
samoas=int(aList[3]) #notice int
thinm=int(aList[2])
shortb=int(aList[4])
return name,thinm,samoas,shortb
def main():
#open the input file
infile=open("cookieSales2019.txt","r")
#read the file into a list inputList
inputList=infile.readlines()
#compute how many kids there are
numLines=len(inputList)
numKids=numLines-2
print("There are " + str(numKids) + " kids selling cookies.") #notice str
for i in range(numLines):
print(inputList[i].rstrip())
#print(inputList[i])
#close and reopen to be back at the beginning of the file
infile.close()
infile=open("cookieSales2019.txt","r")
#read and ignore the header and the blank line
infile.readline()
infile.readline()
#print the names of all the kids and compute the Samoas sales.
sumThinm=0
sumSamoas=0
sumShortb=0
for line in infile:
name, thinm, samoas, shortb = getCookieData(line)
sumThinm=sumThinm+thinm
sumSamoas=sumSamoas + samoas #notice int
sumShortb=sumShortb+shortb
print(name, "sold", thinm, "boxes of Thin Mint Cookies,", samoas, "boxes of Samoa Cookies, and", shortb, "boxes of Shortbread Cookies sold")
#print the final total
print("There were {0} boxes of Thin Mints sold.".format(sumThinm))
print("There were {0} boxes of Samoas sold.".format(sumSamoas))
print("There were {0} boxes of Shortbreads sold.".format(sumShortb))
#close the file
infile.close()
main()
##There are 3 kids selling cookies.
##Name Thin Mints Samoas Shortbreads
##
##Susie Fong 10 3 5
##Megan LaPlant 30 20 55
##Shoban Freeman 45 15 0
##Susie Fong sold 10 boxes of Thin Mint Cookies, 3 boxes of Samoa Cookies, and 5 boxes of Shortbread Cookies sold
##Megan LaPlant sold 30 boxes of Thin Mint Cookies, 20 boxes of Samoa Cookies, and 55 boxes of Shortbread Cookies sold
##Shoban Freeman sold 45 boxes of Thin Mint Cookies, 15 boxes of Samoa Cookies, and 0 boxes of Shortbread Cookies sold
##There were 85 boxes of Thin Mints sold.
##There were 38 boxes of Samoas sold.
##There were 60 boxes of Shortbreads sold.
|
7ad2013870722e0368f2bb45b59e53c9c06fae70 | yellowmarlboro/leetcode-practice | /s_python/925_long_pressed_name.py | 1,741 | 3.65625 | 4 | """
925. 长按键入
你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。
你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。
示例 1:
输入:name = "alex", typed = "aaleex"
输出:true
解释:'alex' 中的 'a' 和 'e' 被长按。
示例 2:
输入:name = "saeed", typed = "ssaaedd"
输出:false
解释:'e' 一定需要被键入两次,但在 typed 的输出中不是这样。
示例 3:
输入:name = "leelee", typed = "lleeelee"
输出:true
示例 4:
输入:name = "laiden", typed = "laiden"
输出:true
解释:长按名字中的字符并不是必要的。
提示:
name.length <= 1000
typed.length <= 1000
name 和 typed 的字符都是小写字母。
"""
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
idx = 0
idy = 0
while idy != len(typed) - 1 or idx != len(name) - 1:
if typed[idy] == name[idx]:
idx = idx + (1 if idx < len(name) - 1 else 0)
idy = idy + (1 if idy < len(typed) - 1 else 0)
else:
if idx == 0:
return False
elif typed[idy] != name[idx-1]:
return False
else:
idy = idy + (1 if idy < len(typed) - 1 else 0)
print(idx, idy)
if name[idx] == typed[idy]:
return True
else:
return False
if __name__ == "__main__":
s = Solution()
s.isLongPressedName(
"pyplrz",
"ppyypllr"
) |
72781200e80468bae21ef5cce46b65e87ba24668 | starkworld/SSW-567 | /HW01_traingles.py | 2,448 | 4.3125 | 4 | import unittest
def classify_triangle(a, b, c):
"""
Method that Classifies the triangle based on the sides given
"""
intersection = {a, b, c} & {a, b, c}
is_right_triangle = a ** 2 + b ** 2 == c ** 2
triangle_class = 'Invalid Triangle'
if a <= 0 or b <= 0 or c <= 0:
return triangle_class
if is_right_triangle:
triangle_classification = 'Right Angle Triangle'
elif len(intersection) == 1:
triangle_classification = 'Equilateral Triangle'
elif len(intersection) == 2:
triangle_classification = 'Isosceles Triangle'
else:
triangle_classification = 'Scalene Triangle'
return triangle_classification
class TriangleClassification(unittest.TestCase):
"""
Testing Classify triangle method
Unittest class
"""
def test_classify_equilateral_triangles(self):
"""
Testcases for equilateral triangle
"""
self.assertEqual(classify_triangle(1, 1, 1), 'Equilateral Triangle')
self.assertEqual(classify_triangle(10, 10, 10), 'Equilateral Triangle')
def test_classify_isosceles_triangles(self):
"""
Testcases classify isosceles triangle
"""
self.assertEqual(classify_triangle(65, 65, 130), 'Isosceles Triangle')
self.assertEqual(classify_triangle(2, 3, 3), 'Isosceles Triangle')
self.assertEqual(classify_triangle(4, 6, 4), 'Isosceles Triangle')
def test_classify_scalene_triangles(self):
"""
Testcases scalene triangle
"""
self.assertEqual(classify_triangle(1, 2, 3), 'Scalene Triangle')
self.assertEqual(classify_triangle(7, 6, 3), 'Scalene Triangle')
self.assertEqual(classify_triangle(67, 87, 90), 'Scalene Triangle')
def test_classify_right_triangles(self):
"""
Testcases classify right triangle
"""
self.assertEqual(classify_triangle(3, 4, 5), 'Right Angle Triangle')
self.assertEqual(classify_triangle(5, 12, 13), 'Right Angle Triangle')
self.assertEqual(classify_triangle(8, 15, 17), 'Right Angle Triangle')
def test_classify_invalid_triangle(self):
"""
Testcases classify
"""
self.assertEqual(classify_triangle(-10, -10, -10), 'Invalid Triangle')
def main():
"""invokes the triangle method"""
classify_triangle(3, 3, 1)
if __name__ == '__main__':
unittest.main(exit=False, verbosity=2)
|
7b95eaa2ffcdfda181b86ce70182cd0f4aad4716 | ShaneyMantri/Algorithms | /Array/Summary_Ranges.py | 1,244 | 3.671875 | 4 | """
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
"""
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
if len(nums)==0:
return []
if len(nums)==1:
return [str(nums[0])]
res = []
st = 0
en = 0
n = len(nums)
while en<(n-1):
if nums[en]==(nums[en+1]-1):
en+=1
else:
if st==en:
res.append(str(nums[st]))
else:
res.append(str(nums[st])+"->"+str(nums[en]))
en+=1
st = en
if (nums[-1]-1)==nums[-2]:
res.append(str(nums[st])+"->"+str(nums[-1]))
else:
res.append(str(nums[-1]))
return res
|
09ebbae5da29ed44c090da2faf1c20b873867469 | GMwang550146647/network | /python基本语法/1.基本方法/1.2.类与对象/1.类与对象基础.py | 819 | 4.09375 | 4 | #执行顺序
#1.创建一个变量
#2.内存中创建一个新对象
#3.执行类代码块中的代码(只在类中定义),例如下面的"name1='gmwangPublic'"
#4.__init__(self)方法执行
#5.将对象id赋值给变量
class Student():
#定义该对象的方法,这个是各个类共享的(也就是每个类都能修改)
name1='gmwangPublic'
#特殊方法(带__开头和结尾的),不需要自己调用,__init__函数是构建函数
def __init__(self,name="gmwangSelf"):
#这个name是每个对象各自不同的name
self.name=name
def getName(self):
print(self.name1)
s1=Student()
#类外可以定义该对象的附加属性
s1.name2='gmwang'
print(s1.name2)
#调用类的属性和方法
s1.getName()
print(s1.name1)
print(isinstance(s1,Student)) |
e1459190c86c9b4b4b8d393784f517fcd1de175f | WenqinSHAO/path_change_alert | /pathpattern.py | 2,500 | 3.609375 | 4 | class PathPattern(object):
"""Class for path pattern.
Attributes:
pid2path (dict): {pid(int): path(list of strings)};
dictionary mapping paris id to the IP path that it takes
ordered_path (list): a list of tuples (pid, path) ordered by pid
ordered_pid (list): ordered pids
hash_code (int): hash value of ordered_path
is_complete (boolean): tells if the path pattern contains all the 16 paris id
"""
def __init__(self, dict):
"""
Args:
dict: supposed to be a dictionary {pid(int): path(list of strings)}
"""
self.pid2path = dict
self.ordered_path = self.__get_path_ordered()
self.ordered_pid = self.__get_pid_ordered()
self.hash_code = self.__calc_hash()
self.is_complete = self.__is_complete()
def update(self, dict):
"""Update the path pattern with given pid path pairs.
Args:
dict: supposed to be a dictionary {pid(int): path(list of strings)}
"""
for pid, path in dict.iteritems():
self.pid2path[pid] = path
self.ordered_path = self.__get_path_ordered()
self.ordered_pid = self.__get_pid_ordered()
self.hash_code = self.__calc_hash()
self.is_complete = self.__is_complete()
def __calc_hash(self):
"""calculate the hash code for the path pattern"""
return hash(str(self.ordered_path))
def __get_path_ordered(self):
"""form ordered paths"""
return sorted(self.pid2path.items(), key=lambda s: s[0])
def __get_pid_ordered(self):
"""form ordered pid list"""
return sorted(self.pid2path.keys())
def __is_complete(self):
"""verify if the paris ids contained in the path pattern is complete"""
return self.ordered_pid == range(16)
def identical_full(self, pptn):
"""verify if given path pattern is equal to the local one.
Args:
pptn (PathPattern): the one that is compared to the local one
"""
return self.hash_code == pptn.hash_code
def fit_partial(self, pptn):
"""Test if all the paths in given path pattern fit with the local one.
Args:
pptn (PathPattern): the one that is compared to the local one
"""
flag = True
for tup in pptn.ordered_path:
if tup not in self.ordered_path:
flag = False
break
return flag
|
7d26c4d1d15bd7d0c0c760a8988b164b9fa6495b | denis-kitaev/python-project-lvl1 | /brain_games/games/progression.py | 763 | 3.578125 | 4 | import random
from brain_games.engine import run
INTRO = 'What number is missing in the progression?'
START_ELEMENT_RANGE = 1, 9
STEP_RANGE = 2, 8
LENGTH_RANGE = 5, 10
def get_progression(start, step, length):
return list(range(start, start + step * length, step))
def get_question_and_answer():
progression = get_progression(
start=random.randint(*START_ELEMENT_RANGE),
step=random.randint(*STEP_RANGE),
length=random.randint(*LENGTH_RANGE),
)
missing_index = random.randint(0, len(progression) - 1)
answer = progression[missing_index]
progression[missing_index] = '..'
question = ' '.join(map(str, progression))
return question, str(answer)
def run_game():
run(INTRO, get_question_and_answer)
|
1d8c0a25ac941c239c35a18028ff94f671cd0afc | BluecatCN/AdvAlgoProject | /wako/test.py | 1,380 | 3.59375 | 4 | import sys
def modifyDisMat(disMat, cityNum):
x = [] #行
y = [] #列
for i in range(cityNum): #全ての変数を最大化にする
x.append(sys.maxsize)
y.append(sys.maxsize)
#各行の最小を求める
for i in range(cityNum): #行
for j in range(cityNum): #列
if disMat[i][j] < x[i]:
x[i] = disMat[i][j]
print("i:"+str(i)+" 最小:" +str(x[i]))
if x[i] == sys.maxsize:
x[i] = 0
#各行を最小の数で引く
for i in range(cityNum):
for j in range(cityNum):
if disMat[i][j] != sys.maxsize:
print("dismat:" +str(disMat[i][j])+" - "+str(x[i]))
disMat[i][j] -= x[i]
print("結果 dismat:" +str(disMat[i][j]))
print("途中 dismat: "+str(disMat))
print("--------------------------------")
#各列の最小を求める
for i in range(cityNum):
for j in range(cityNum):
if disMat[j][i] < y[i]:
y[i] = disMat[j][i]
print("i:"+str(i)+" 最小:" +str(y[i]))
if y[i] == sys.maxsize:
y[i] = 0
#各列を最小の数で引く
for i in range(cityNum):
for j in range(cityNum):
if disMat[j][i] != sys.maxsize:
print("dismat:" +str(disMat[j][i])+" - "+str(y[i]))
disMat[j][i] -= y[i]
print("結果 dismat:" +str(disMat[j][i]))
print("cost: "+str(sum(x)+sum(y)))
print("newDisMat: "+str(disMat))
disMat = [[1, 2, 9, 10], [30, 67, 1, 29], [98, 1, 32, 45], [4, 5, 1, 7]]
modifyDisMat(disMat, 4) |
c73774ea9102e279fa2fc648b8a1634827ad9e34 | lxh1997zj/Note | /廖雪峰python3教程/OOP/day3/command.py | 372 | 3.6875 | 4 | # !/usr/bin/env python3
# -*- coding:utf-8 -*-
# 首先你有一个command.py文件,内容如下,这里我们假若它后面还有100个方法
class MyObject(object):
def __init__(self):
self.x = 9
def add(self):
return self.x + self.x
def pow(self):
return self.x * self.x
def sub(self):
return self.x - self.x
def div(self):
return self.x / self.x
|
077b97046a240dae85130d8c8f130a630bb82741 | AFRIKAKORPS1/homework2 | /homework2.py | 667 | 3.8125 | 4 | import math
class Point:
def points(self, x=(0, 0)):
return x
class Polyline:
def __init__(self, polyList=[]):
self.polyList = polyList
def calcLine(self, polyline):
return
class Polygon:
def __init__(self):
array = []
def makePoly(self, array):
print 'ayy'
class Point1:
x = 0.0
y = 0.0
def __init__(self, x= 0.0, y=0.0):
self.x = x
self.y = y
def distance(self, point):
return math.sqrt((point.x-self.x)**2+(point.y-self.y)**2)
p1=Point1()
p1.x = 1
p1.y = 2
p2 = Point1(3, 4)
print p1.distance(p2)
test = Point()
print test.points((3, 4))
|
cc4b276ad810e5c62f387e8cca329aa872dadc54 | Timur1986/work-with-FILE | /io_w.py | 450 | 4.0625 | 4 | # Скопировать весь текст и записать его в новый файл
x = input('Укажите имя файла, который Вы хотите скопировать: ')
y = input('Введите новое имя скопированного файла: ')
name1 = open(x, 'r')
name2 = open(y, 'w')
name2.write(name1.read())
name1.close()
name2.close()
print('Копирование файла завершено!')
|
3da96eba8223961bd87ed52181fb24fff00b6df2 | prudhvi9666/Homomorphic_Algo | /Libraries/generate_keys.py | 3,629 | 4.03125 | 4 | import random
def generate_LCM(p, q):
"""
give lcm of p and q
p is first prime number -1
q is second prime number -1
"""
return p *q // generate_gcd(p, q)[0]
def generate_gcd(a, b):
"""
returns (g, x, y) according to the Extended Euclidean Algorithm
such that, ax + by = g
"""
if a == 0:
return (b, 0, 1)
else:
g, y, x = generate_gcd(b % a, a)
return (g, x - (b // a) * y, y)
def multi_inverse(lcmvalue, n):
"""
returns x: multiplicative inverse of a
such that, a * x = 1 (mod modu)
"""
g, x, y = generate_gcd(lcmvalue, n)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % n
def Generate_privatekey(m, n, result):
"""
PrivateKey object contains λ(_lambda) and μ(_mu)
in accordance to the Paillier Cryptosystem
args:
m: a prime number
n: another prime number
result: product of p and q
attributes:
λ(_LCM): lowest common multiple of m-1 and n-1
μ(_mu): modular multiplicative inverse of λ and result
"""
_LCM = generate_LCM(m - 1, n - 1)
_multiInversevalue = multi_inverse(_LCM, result)
return _LCM, _multiInversevalue
def Generate_publickey(result):
"""
Public Key object contains result and x
in accordance to the Paillier Cryptosystem
args:
result: product of two equal lenght prime numbers
attributes:
result: product of two primes
x: a random number such that,
nsq = result * result
multiplicative order of x in result^2 is a multiple of result
"""
result = result
nsq = result * result
x = result + 1
return result, x, nsq
def Main_fun(m=757, n=787):
"""
This function is used to generate the public and private keys based on M,n values
m and n are two prime numbers with same size
function returns the genearted keys as tuples
"""
result = m * n
return Generate_publickey(result), Generate_privatekey(m, n, result)
def Encryption(pub_key, text):
"""
Encryption( pub_key, text)
args:
pub_key: Paillier Public key object
text: number to be encrypted
returns:
encrypted_text: encryption of text
such that encrypted_text = (g ^ text) * (r ^ n) (mod n ^ 2)
where, r is a random number in n such that r and n are coprime
"""
r = random.randint(1, pub_key[0] - 1)
while not generate_gcd(r, pub_key[0])[0] == 1:
r = random.randint(1, pub_key[0])
a = pow(pub_key[1], text, pub_key[-1])
b = pow(r, pub_key[0], pub_key[-1])
encrypted_text = (a * b) % pub_key[-1]
return encrypted_text
def Decryption(pub_key, pri_key, encrypted_text):
"""
Decryption( pub_key, pri_key, encrypted_text)
args:
pub_key: Paillier Public Key object
pri_key: Paillier Private Key object
encrypted_text: Encrypted Integer which was ecnrypted using the pub_key
returns:
text: decryption of encrypted_text
such that text = L(encrypted_text ^ _lambda) * _mu (mod n ^ 2)
where, L(x) = (x - 1) / n
"""
x = pow(encrypted_text, pri_key[0], pub_key[-1])
L = lambda x: (x - 1) // pub_key[0]
text = (L(x) * pri_key[-1]) % pub_key[0]
return text
def homomorphic_addition(pub_key, a, b):
"""
adds encrypted integer a to encrypted integer b
args:
pub_key
encryption of integer a
encryption of integer b
returns:
encryption of sum of a and b
"""
return (a * b) % pub_key[-1]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.