blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
1802b6697bd667627b2bc2de511340ce52a447e6 | maahn/meteo_si | /meteo_si/wind.py | 1,794 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import numpy as np
# from .constants import *
'''
Functions to deal with wind observations.
'''
def circular_mean(angles):
"""
Compute the arithmetic circular mean, not ignoring NaNs.
Parameters
----------
angles : list or array
The angles for averaging in radians.
Returns
-------
mean : float
The circular mean in radians.
"""
if np.any(np.isnan(angles)):
return np.nan
else:
return nan_circular_mean(angles)
def nan_circular_mean(angles):
"""
Compute the arithmetic circular mean, ignoring NaNs.
Parameters
----------
angles : list or array
The angles for averaging in radians.
Returns
-------
mean : float
The circular mean in radians.
"""
x = np.nansum(np.cos(angles))
y = np.nansum(np.sin(angles))
mean = np.arctan2(y, x)
if mean < 0:
mean = mean + (np.pi*2)
return mean
def circular_mean_deg(angles):
"""
Compute the arithmetic circular mean, not ignoring NaNs.
Parameters
----------
angles : list or array
The angles for averaging in degrees.
Returns
-------
mean : float
The circular mean in degrees.
"""
if np.any(np.isnan(angles)):
return np.nan
else:
return nan_circular_mean_deg(angles)
def nan_circular_mean_deg(angles):
"""
Compute the arithmetic circular mean, ignoring NaNs.
Parameters
----------
angles : list or array
The angles for averaging in degrees.
Returns
-------
mean : float
The circular mean in degrees.
"""
return np.rad2deg(nan_circular_mean(np.deg2rad(angles)))
|
bb6596a279c26e84d18566c30cd0f63e744db861 | hoangminhhuyen/B-i-gi-i-th-c-h-nh-ph-n-t-ch-d-li-u-Pandas | /1.3.py | 617 | 3.609375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
movies = pd.read_csv('movies.csv')
#tách year ra khỏi title
movies["year"] = movies.title.apply(lambda x: x[-5:-1])
#loại bỏ những year NaN
movies.year=pd.to_numeric(movies.year,errors='coerce',downcast='integer')
#print(movies.year)
#tách genres thành 1 list
movies['genre'] = movies.genres.apply(lambda x: x.split('|'))
#print(movies.genre)
#tạo dataframe chỉ chứa genre Drama
movies1=movies[movies.genres.str.contains("Drama")]
#vẽ line Drama qua các năm
movies1.groupby('year').size().plot(kind='line')
plt.show() |
f21b83e43c684b421e42b31c7e7d4180a1672ba5 | Ben1152000/Lost-Continent | /source/mapping/vertex.py | 1,027 | 3.640625 | 4 |
class Vertex():
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def fromDict(vectorDict):
return Vertex(vectorDict["lon"], vectorDict["lat"])
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __neg__(self):
return Vertex(-self.x, -self.y)
def __add__(self, other):
return Vertex(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return self + (-other)
def __abs__(self):
return (self.x * self.x + self.y * self.y) ** 0.5
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
def __mul__(self, other):
return Vertex(self.x * other, self.y * other)
def floor(self):
self.x = int(self.x)
self.y = int(self.y)
if __name__ == "__main__":
v = Vertex(4, 8)
u = Vertex(3, 2)
print("v = " + str(v))
print("u = " + str(u))
print("v + u = " + str(v + u))
print("v - u = " + str(v - u)) |
fe060087457455478d7b6609c0b8b2e765908e20 | mross982/Ordinary_Least_Squares | /FACT-G_OLS.py | 1,646 | 3.5625 | 4 | import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
import matplotlib as plt
df = pd.read_csv('C:\\Users\\mrwilliams\\Documents\\Program_Projects\\Ordinary_Least_Squares\\FACT-G.csv', index_col=0)
# Rescale FACT-G scores to 0 - 100 scale as described in Model 1 on page 3 of Teckle et al.
norm_df = df.copy()
scaled_score = []
max_value = 108
min_value = 0
for Score in norm_df.Score:
scaled_score.append((Score - min_value) / (max_value - min_value) * 100)
norm_df['Scaled_Score'] = scaled_score
print(norm_df.head())
# The X is the predictor variable and the Y is the response
# therefore, X is the FACT-G score and Y is the EQ-5D health-related Quality of life index
# in this instance, the Y is just a possible range from 0 to 1.
# y = df.HRQoL_Index # Response
# y = np.linspace(0, 1, 100)
# x = df.Score # Predictor
# x = sm.add_constant(x) # Adds constant term to the predictor
# print(x.head())
# est = sm.OLS(y,x)
# est = est.fit()
# print(est.summary())
# print(est.params)
# # %pylab inline
# # Pick 100 points equally spaced from the min to the max
# X_prime = np.linspace(x.GNP.min(), X.GNP.max(), 100)[:, np.newaxis]
# X_prime = sm.add_constant(X_prime) # Add a constant as we did before
# # Calculate the predicted values
# y_hat = est.predict(X_prime)
# plt.scatter(X.GNP, y, alpha=0.3) # Plot the raw data
# plt.xlabel("Gross National Product")
# plt.ylabel("Total Employment")
# plt.plot(X_prime[:, 1], y_hat, 'r', alpha=0.9) # adds the regression line
# plt.show()
# # est = smf.ols(formula='Employed ~ GBP', data=df).fit()
# print(est.summary())
|
9feef2ad06703a3f3f7becb72227d7e8d63b70d9 | TechGirl254/Training101 | /exercise2.py | 583 | 4.15625 | 4 |
# tasklist
tasklist=[23,"jane",["Lesson23",560, {"currency":"KES"}],987,(76,"john")]
# Determine the type of variable tasklist using an inbuilt function
# Print KES
print(tasklist[2][2])
# print(tasklist(c))
# Print 560
# Use a function to determine the length of tasklist
print(len(tasklist))
# change 987 to 789 using an inbuilt function
c=(tasklist[3])
c=str(c)
print(int(c [::-1]))
# change name john to jane
# not possible
# You cannot edit a tuple-unless you conver to a list-edit to jane and pop
# github
# DATA STRUCTURES IN PYTHON
# -List
# -Dictionary
# -Tuple
dict. |
b19b91515c63d709dd4a9455213b6cfc7cf38561 | loganpassi/Python | /Algorithms and Data Structures/HW/HW1/distinctNums.py | 1,367 | 4.21875 | 4 | #Logan Passi
#CPSC-34000
#08/27/19
#distinctNums.py
#Write a Python function that takes a sequence of numbers and determines
#if all the numbers are different from each other (that is, they are distinct).
def isDistinct (list, numElem):
count = 0
for i in range(numElem):
currentElem = list[i] #grab a character to compare to the rest of characters
for j in range(numElem):
if currentElem == list[j]: #loop through the rest of characters to check to see if there are duplicates
count += 1
if count > 1:
return False
else:
count = 0
return True
numList = [] #list to hold the numbers
numElements = int(input("Enter in the numbers of elements you wish to input: "))
print("Enter in your numbers")
for i in range(numElements): #loop through the length of the list and append each new character entered
element = int(input())
numList.append(element)
if isDistinct(numList, numElements) == True:
print("The list is distinct!")
else:
print("The list is NOT distinct!")
#Enter in the numbers of elements you wish to input: 5
#Enter in your numbers
#1
#5
#3
#4
#5
#The list is NOT distinct!
#Enter in the numbers of elements you wish to input: 6
#Enter in your numbers
#1
#5
#8
#4
#6
#3
#The list is distinct! |
f14933cf45966998acc73b44d34d7098f9e6011f | akshatvaidya/SocketProgramming | /Client.py | 5,148 | 3.90625 | 4 | # Name - Akshat Vaidya
# Student Id - 1001550684
# importing all the necessary libraries
# socket library is used to create and handle various sockets
# easygui library is used to create gui
# os library is used to get the file list at a specific location
import socket
import easygui
import os
# specifying the host as localhost because the server and clients both reside on the same node
host = socket.gethostname()
port = 80
# A socket is created where the first argument refers to the IPV4 addressing scheme and the second argument refers to the TCP protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect method connects to the server on given host and port
s.connect((host, port))
# The message to be shown to the client upon connection and the title of that window
message = "Enter a username"
title = "Client"
# FieldsList keeps track of all the fields which will be used as input from the user
fieldsList = ["Username"]
# The window is created with the parameters message, title and the input fields
fieldValue = easygui.multenterbox(message, title, fieldsList)
# since the field list has only one field i.e. username, it is sent to the server
s.send(bytes(fieldValue[0], 'utf-8'))
# Menu is shown to the client and client's choice is saved in the variable
choice = easygui.buttonbox('Choose an option:', fieldValue, ["Upload A File", "Check Available Files", "Download A File", "Disconnect"], None, None, "Disconnect")
# This loop will execute as long as the user does not select Disconnect
# Once inside the loop, according to the choice of the user corresponding code will be executed
while choice != "Disconnect":
# if upload is selected then following code block will be executed
if choice == "Upload A File":
# this will notify the server that upload was selected
s.send(bytes('Upload', "utf-8"))
# fileopenbox allows the user to select a particular file from any directory
filename = easygui.fileopenbox()
try:
# filename is sent to the server
s.send(bytes(filename, 'utf-8'))
# file is opened in read in binary mode
f = open(filename, 'rb')
# reading the data from the file and saving it
data = f.read()
# data is sent to the sever
s.send(data)
# Notifying the user after uploading
easygui.msgbox('Done Uploading')
# Redirecting user back to the main menu
choice = easygui.buttonbox('Choose an option:', fieldValue, ["Upload A File", "Check Available Files", "Download A File", "Disconnect"], None, None, "Disconnect")
# if the file does not exist then user will forcefully be redirected to the main menu
except FileExistsError as f:
choice = easygui.buttonbox('Choose an option:', fieldValue, ["Upload A File", "Check Available Files", "Download A File", "Disconnect"], None, None, "Disconnect")
# if check available files is selected then following code block will be executed
elif choice == "Check Available Files":
# listdir(path) method lists all the files present at that particular path which is sent as an argument
easygui.msgbox(os.listdir('C:\\Users\\Akshat Vaidya\\PycharmProjects\\SocketProgramming'), "File List")
# After showing the file list, user is sent back to the main menu
choice = easygui.buttonbox('Choose an option:', fieldValue, ["Upload A File", "Check Available Files", "Download A File", "Disconnect"], None, None, "Disconnect")
# if download is selected then following code block will be executed
elif choice == "Download A File":
# this will notify the server that download is selected
s.send(bytes('Download', "utf-8"))
# after the server is notified that download is selected, server shows a list of available files to the client
# Once client clicks on a file server sends the filename to the client
filename = s.recv(64)
# Here the filename is prefixed with whatever folder client wants the file to be downloaded in
file = "C:\\Users\\Akshat Vaidya\\Downloads\\" + str(filename, "utf-8")
if file:
# now we create a file with the same name and write all the data into it basically making a copy of the file at the server
with open(file, 'wb') as f:
data = s.recv(1024)
f.write(data)
easygui.msgbox('Done Downloading')
f.close()
# client is redirected back to the main menu
choice = easygui.buttonbox('Choose an option:', fieldValue, ["Upload A File", "Check Available Files", "Download A File", "Disconnect"], None, None, "Disconnect")
else:
# if disconnect is selected server is notified of it
s.send(bytes('Disconnect', "utf-8"))
#s.close()
|
2f87f14ad5db4f60ae47913e6c65a44987eeca90 | jacob568/JDJ-1 | /JacobsTestedThings/CmToFtIn/__init__.py | 512 | 4.25 | 4 | #Converts cm reading to feet and inches
def ConvertToFeetAndInch(cm):
if is_number(cm) == False:
return "Incorrect input type, please enter a number"
inches = float(cm) / 2.54
feet = 0
working = True
while working:
if inches >= 12.0:
feet += 1;
inches -= 12.0;
else:
return (str(feet) + "ft " + str(round(inches, 1)) + "in")
working = False
#Checks if the input is a number value
def is_number(s):
try:
float(s)
return True
except ValueError:
return False |
def3fc6198b0b1d7fcbae2a40a1b21c756587a65 | Richard-12/Curso-Python-Objetos | /herencia-funcionesdeprueba(c09).py | 1,583 | 4.09375 | 4 | # Herencia: funciones de prueba.
# Se utilizará el ejemplo anterior
class Calculadora:
def __init__(self, numero):
self.n = numero
self.datos = [0 for i in range(numero)]
def ingresardato(self):
self.datos = [int(input('Ingrese los datos ' + str(i + 1) + ' = ')) for i in range(self.n)]
class op_basicas(Calculadora):
def __init__(self):
Calculadora.__init__(self, 2)
def suma(self):
a, b, = self.datos
s = a + b
print('El resultado de la suma es: ', s)
def resta(self):
a, b, = self.datos
r = a - b
print('El resultado de la resta es: ', r)
class raiz(Calculadora):
def __init__(self):
Calculadora.__init__(self, 1)
def cuadrada(self):
import math
a = self.datos[0]
print('La raíz cuadrade es: ', math.sqrt(a))
ejemplo = op_basicas()
ejemplo.ingresardato()
ejemplo.suma()
ejemplo.resta()
ejemplo_raiz = raiz()
ejemplo_raiz.ingresardato()
ejemplo_raiz.cuadrada()
# isinstance permite verificar la herencia
objeto = op_basicas()
print('objeto es heredero de raiz?: ')
print(isinstance(objeto, raiz))
print('objeto es heredero de op_basicas?: ')
print(isinstance(objeto,op_basicas))
print('objeto es heredero de Calculadora?: ')
print(isinstance(objeto,Calculadora))
#Tambien permite verificar si tenemos una clase hijo pertenece a la clase padre.
print('Calculadora es heredero de op-basicas?: ')
print(issubclass(Calculadora,op_basicas))
print('op-basicas es heredero de Calculadora?: ')
print(issubclass(op_basicas,Calculadora))
|
5a5145897fbb50e675c3e386eb67f4f0c2e3ccaf | arnaudpilato/Wild-Code-School | /France IOI/01 - Fundamentals 1/28 - Construction d'une pyramide.py | 141 | 3.6875 | 4 | coté = 1
bloc = 1
total = 1
for loop in range (8):
coté = coté + 2
bloc = bloc + coté * coté * coté
total = bloc
print (total)
|
34e1f92b0fd6f65ebf0d8e23f951e7d9be380dcc | RShankar/Social-Web-Apps | /Melissa-Serrano/Homework1_Serrano_WebServicesTutorial/WebServicesJSON.py | 2,141 | 3.75 | 4 | import urllib
import json
serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?' #Google Maps API URL used to search for geocode information
while True:
address = raw_input('Enter location: ') #get a location from the user
if len(address) < 1 : break #get out (since no address was entered) and ask the user to Enter Location again
url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address}) #Append the location entered by the user to the Google Maps API URL
print 'Retrieving', url
uh = urllib.urlopen(url) #library function used to open the URL
data = uh.read() #location data retrieved by API
print 'Retrieved',len(data),'characters' #character count for data retrieved
try: js = json.loads(str(data)) #json.loads(parameter) takes a JSON string and gives us a Python Dictionary so we can traverse the data
#retrieved or use square bracket notation to access elements
except: js = None #if there's a problem setting js then set it to None (Null)
if 'status' not in js or js['status'] != 'OK': #When the data is retrieved successfully there is a key-value pair status:OK
print '==== Failure To Retrieve ===='
print data
continue
print json.dumps(js, indent=4) #json.dumps will take a Python object (usually Dictionary) and serialize it to JSON
print 'type(js) = ', type(js)
lat = js["results"][0]["geometry"]["location"]["lat"] #store the latitude
lng = js["results"][0]["geometry"]["location"]["lng"] #store the longitude
print 'lat',lat,'lng',lng
location = js['results'][0]['formatted_address']
print location
#js["results"][0]["address_components"][N]
#where N = 0 is the Locality address component
#N = 1 is the State address component
#N = 2 is the Country address component
#Now we can use the Python Dictionary Format to access the data we need
try: country_code = js["results"][0]["address_components"][3]["short_name"] #get the 2 character country code
except: country_code = None
print 'Country Code: ', country_code
|
3b74ef10692d52565a2bf5a916bd54d277091e7a | Ernjivi/bedu_python01 | /Curso-de-Python/Clase-01/Soluciones/tabla-verdad-not.py | 1,054 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Imprimir la tabla de verdad del operador lógico NOT en la salida estándar
en forma tabular incluyendo operador1 y resultado.
"""
# Variables que definen las dimensiones de la tabla
ancho_ter = 58 # Ancho de la terminal
ancho_op1 = 10 # Ancho del campo del operador 1
ancho_res = 10 # Ancho del campo de resultado
ancho_tabla = ancho_op1 + 3 + ancho_res # El ancho de la tabla se calcula
# Se inicia la impresión de la tabla
print()
print("{:^{}}".format(
"Tabla de verdad de NOT", ancho_tabla).center(ancho_ter))
print(("-" * ancho_tabla).center(ancho_ter))
print("{:{}} | {:{}}".format(
"Operador 1", ancho_op1, "Resultado", ancho_res).center(ancho_ter))
print(("-" * ancho_tabla).center(ancho_ter))
op1 = True
res = not op1
print("{:{}} | {:{}}".format(
str(op1), ancho_op1, str(res), ancho_res).center(ancho_ter))
op1 = False
res = not op1
print("{:{}} | {:{}}".format(
str(op1), ancho_op1, str(res), ancho_res).center(ancho_ter))
print(("-" * ancho_tabla).center(ancho_ter)) |
8166c243d3a7cacb0b3fb3da36c9519837ef98c7 | duanheyun/Dhy | /python_pratice/python_002/python_00/python_bicycle.py | 683 | 3.796875 | 4 | class Bicycle:
def run(self, km):
print(f"一共骑了{km}km")
#bike = Bicycle()
#bike.run(100)
#继承父类
class Ebicycle(Bicycle):
def __init__(self, valume):
self.valume = valume
# 电动车充了多少电
def fill_change(self, vol):
print(f"充了{vol}电")
print(f"充完电之后 还有{vol+self.valume}电")
self.valume = self.valume+ vol
def run(self, km):
e_km = self.valume*10
print(f"{e_km}")
if km <= e_km:
print(f"用电骑行了{km}km")
else:
print(f"用脚骑了{km - e_km}KM")
ebike = Ebicycle(1000)
ebike.fill_change(10000)
ebike.run(10000000) |
6a4ab8f96b7928aa0b0919289095ac6a72691531 | AZ-OO/Python_Tutorial_3rd_Edition | /10章 標準ライブラリめぐり/10.6.py | 1,038 | 3.90625 | 4 | """
10.6 数学
"""
# mathモジュールを使うと、浮動小数点数数学用の下層のCライブラリ関数にアクセスできる
import math
print(math.cos(math.pi / 4)) # <-- 0.7071067811865476
print(math.log(1024, 2)) # <-- 10.0
# randomモジュールは無作為抽出のツールを提供する
import random
print(random.choice(['apple', 'pear', 'banana']))
print(random.sample(range(100), 10)) # 重複なしの抽出 <-- [40, 83, 75, 95, 55, 66, 8, 84, 57, 96]
print(random.random()) # ランダムな浮動小数点 <-- 0.11638404874734021
print(random.randrange(6)) # range(6)からランダムに選んだ整数
# statisticsモジュールは数値データの基本統計量(平均、中央値、分解など)を求めるもの
import statistics
data = [2.75 ,1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
print(statistics.mean((data))) # 平均 <-- 1.6071428571428572
print(statistics.median(data)) # 中央値 <-- 1.25
print(statistics.variance(data)) # 分散 <-- 1.3720238095238095
|
2deb2adada5ca5b43d899b190caa4f161037a5df | sandeepvvs007/Python_code | /dailly.py | 948 | 3.84375 | 4 | one=int(input("please enter first number"))
two=int(input("please enter second number"))
oper=input("please enter A for addition S for substraction M for multiplication D for division and X for exit").casefold()
while oper != "e" :
if oper =="a":
print("sum is {}".format(one+two))
elif oper == "s":
print("difference is {}".format(one-two))
elif oper == "m":
print("product is {}".format(one*two))
elif oper == "d":
print("division result is {}".format(one/two))
else:
print("please enter a valid input")
one=int(input("please enter first number"))
two=int(input("please enter second number"))
oper=input("please enter A for addition S for substraction M for multiplication D for division and X for exit").casefold()
n=int(input("enter the value of n"))
for i in range(n):
print("*"*i)
for i in range(n,0,-1):
print("*"*i)
|
471f9b9faf20539761835e3692620dc1b811f7d5 | beatrizsnichelotto/curso-python-selenium | /Python/if_else.py | 404 | 3.84375 | 4 |
# IF = SE
# "Pai, você comprou pão"
# Resposta == sim ou == não
# Se comprou, ele vai agradecer
# Se não comprou, ele vai chorar
# ELIF = else if - Se não, outra coisa
# ELSE = se não, sem resposta
resposta = input ('Pai, você comprou pão? ')
if resposta == 'sim':
print ('Obrigado Pai')
elif resposta == 'nao':
print ('Chorando')
else:
print('Não foi o que eu perguntei') |
c94ccd0a85e202e31cb7f224cbd56271be9fe8fe | 3232731490/Python | /爬虫笔记/day_02/re_findall.py | 296 | 3.71875 | 4 | #findall(str,begin,end)
#返回一个所有匹配成功子串的列表
#findier(str,begin,end)
#返回一个匹配对象的迭代器对象
import re
pattern= re.compile(r"\d+")
m=pattern.findall("aaa 12345 789")
print(m)
m=pattern.finditer("aaa 123456 789")
for i in m:
print(i.group()) |
dcd9e319696c4f7b27432d87400ca545b0bddfa1 | Renan-S/How-I-Program | /Python/Curso de Python/Dicionarios.py | 742 | 4.1875 | 4 | """
Dicionários {dict}
Em algumas linguagens, os dicionários são chamados de mapas
Dicionário = Coleção de chave/valor
Chaves e valores podem ser de qualquer tipo
Dicionário é representado por {}
#O primeiro string é uma chave e o segundo (após :) um valor
paises = {'br': 'Brasil', 'thai': 'Thailandia', 'py': 'Python'}
print(paises)
print(type(paises))
paises = dict(br= 'Brasil', thai= 'Thailandia', py= 'Python')
print(paises)
print(type(paises))
#Acessando elementos de um dicionário
paises = {'br': 'Brasil', 'thai': 'Thailandia', 'py': 'Python'}
print(paises['py'])
#erro print(paises['eua'])
print(paises.get('thai'))
print(paises.get('eua')) #Tipo - Sem tipo/Vazio/NoneType
"""
|
3b5b07b16c2a955e3cc87aae8ddce46491ef0b82 | boredcactu/data-structures-and-algorithms-python | /data_structures_and_algorithms/data_structures/stacks_and_queues/stacks_and_queues.py | 3,647 | 4.375 | 4 | class Node:
def __init__(self,value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, *value):
"""
it takes any value as an argument and adds a new node with that value to the back of the queue with an O(1) Time performance.
"""
for i in value:
node = Node(i)
# Special case: if empty queue
# f -> 1 <- r
if not self.front and not self.rear:
self.front = node
self.rear = node
else:
old_rear = self.rear
self.rear = node
old_rear.next = self.rear
# front -> 1 -> 2 -> 3 <- rear
def dequeue(self):
"""
it removes the node from the front of the queue, and returns the node’s value.
"""
try:
self.front.value
except AttributeError:
return "empty queue"
else:
temp = self.front
tempp = temp.next
self.front = tempp
return temp.value
def peek(self):
"""
returns the value of the node located in the front of the queue, without removing it from the queue.
"""
try:
return self.front.value
except AttributeError as e:
return f"Empty Queue!!!"
except Exception as e:
return f"Some other exception happened!!! "
def is_empty(self):
"""
returns a boolean indicating whether or not the queue is empty.
"""
if self.front:
return False
else:
return True
class Stack:
def __init__(self):
self.max = 10000
self.top = None
def push(self, *value):
"""
it takes any values as an argument and adds a new node with that values to the top of the stack with an O(1) Time performance.p
"""
for i in value:
node = Node(i)
temp = self.top
self.top = node
self.top.next = temp
def pop(self):
'''
it removes the node from the top of the stack, and returns the node’s value.
'''
try:
result = self.top.value
temp = self.top.next
self.top = temp
return result
except AttributeError:
return "this is empty stack"
def peek(self):
"""
it returns the value of the node located on top of the stack, without removing it from the stack.
"""
try:
return self.top.value
except AttributeError as e:
return "Stack is empty"
def is_empty(self):
'''
it returns a boolean indicating whether or not the stack is empty.n
'''
if self.top:
return False
else:
return True
def getMax(self):
maxx = 0
while self.top:
temp = self.pop()
if temp > maxx:
maxx = temp
return maxx
# pushing 3
# top -> 4 -> 5 -> None
if __name__ == '__main__':
# eaters = Queue()
# # print(eaters.peek())
# eaters.enqueue("Saed","Ahmad")
# # print(eaters.dequeue()) # should return Saed
# print(eaters.front.value) # Saed
# print(eaters.rear.value) # Ahmad
# print(eaters.peek()) # Saed
fruits = Stack()
fruits.push(1)
fruits.push(2)
fruits.push(3)
print(fruits.getMax()) |
52b616788bca2013bcc0cf9f716ad5c0486cf80f | arpitsomani8/Data-Structures-And-Algorithm-With-Python | /Searching/Linear_Search.py | 581 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Arpit Somani
"""
def linear_search(n,x):
element=[]
for i in range(1,n):
element.append(i)
count=0
flag=0
for i in element:
count+=1
if(i==x):
print("Yes! I found my number at position"+str(i))
flag=1
break;
if(flag==0):
print("Number is not found")
print("Number of iterations:"+str(count))
linear_search(50,5)
#This is also a disadvantage of lenear search, if in 1 lakh numbers, i want to find a number which is at last position among 1 lakh, so this will undergo 1 lakh iterations, which is not efficient. |
fa3a3509dda7a2e7e3eb6d373eb5aaee47cab304 | shasafoster/ProjectEuler | /q30_number.py | 625 | 3.8125 | 4 | """
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
"""
from itertools import count
f = lambda str: sum(int(c)**5 for c in str)
result = 0
for i in count(10):
if i == f(str(i)):
result += i
print(i)
if i > 10000000: break
if i % 50000 == 0: print(i)
print(result)
|
67b0152a4fd12efd8a66c91d755ea05347156b0d | 1715439636/professional-python3 | /正则表达式/5_标记.py | 1,879 | 3.625 | 4 | """
作者:文文
正则表达式中的标记
python版本:python3.5
"""
import re
"""
re.IGNORECASE | re.I :忽略大小写
re.DOTALL | re.S : .字符在正常情况下不会匹配换行符,但是使用re.S可以使其匹配换行符
re.MULTILINE | re.M : 多行模式,导致仅能够匹配字符串开始与结束的^和$字符可以匹配字符串内任意行的开始与结束
re.VERBOSE | re.X : 允许复杂的正则表达式以更容易阅读的方式表示。导致所有的空白(除了在字符组中的)被忽略,包括换行符,同时将#当作注释字符
re.DEBUG : 编译正则表达式时将一些调试信息输出到sys.stderr
在python2与python3中,一些字符快捷方式的工作机制存在区别,如\w在python3中匹配几乎所有语言的单词,但是在python2中仅匹配英文字符
所以,为了使re模块强制遵循python2或者python3的标准,可以使用如下两个标记
re.Unicode | re.U :re模块强制遵循python3的标准
re.ASCII | re.A :re模块强制遵循python2的标准
使用多个标记:使用|操作符即可
"""
#output : <_sre.SRE_Match object; span=(0, 6), match='Python'>
print (re.search(r'python','Python is awesome',re.I))
#output : <_sre.SRE_Match object; span=(0, 3), match='foo'>
print (re.search(r'.+','foo\nbar'))
#output : <_sre.SRE_Match object; span=(0, 7), match='foo\nbar'>
print (re.search(r'.+','foo\nbar',re.S))
#output : None
print (re.search(r'^bar','foo\nbar'))
#output : <_sre.SRE_Match object; span=(4, 7), match='bar'>
print (re.search(r'^bar','foo\nbar',re.M))
#output : <_sre.SRE_Match object; span=(0, 8), match='873-2323'>
print (re.search(r"""(?P<first_three>[\d]{3}) # the first three digits
- # a literal hyphen
(?P<last_four>[\d]{4})# the last four code
""",'873-2323',re.X))
|
005bae0f1b808032f5c7e387e0e204de536039c4 | ninehundred1/MiscStuff | /TwitterToMongoDB.py | 3,346 | 3.53125 | 4 | """
Stream live tweets using the twitter API and tweepy. Streams are stored in a mongodb database.
Set filter keywords at bottom.
Stop by interrupting (Ctrl-C) or setting max_tweets
Requires the extra libraries:
pymongo
tweepy
The data is stored in pymongo database:
tweet_db
Collection:
TweetsReceived
"""
import pymongo
import sys
import tweepy
"""
create listener object that processes the stream of tweets of tweepy.StreamListener
created mongodb called:
tweet_db.TweetsReceived
"""
class TweetsStreamListener(tweepy.StreamListener):
def __init__(self, api, max):
#override constructor to init mongodb and the tweepy.StreamListener automatically,
#so no need to do it before
super(tweepy.StreamListener, self).__init__()
try:
self.db = pymongo.MongoClient().tweet_db
print "Connected to MongoDB"
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to MongoDB, reason: %s" % e
self.api = api
self.max_tweets = max
self.counter = 0
#handle all the returns of the stream
def on_connect(self):
print "Connected to a tweet stream!"
#if the listener finds a tweet, save to mongodb
def on_status(self, status):
print str(status.created_at) +": " +status.text.encode("utf-8")
tweet ={}
tweet['text'] = status.text
tweet['created_at'] = status.created_at
tweet['geo'] = status.geo
tweet['source'] = status.source
#insert into collection TweetsReceived
self.db.TweetsReceived.insert(tweet)
self.counter += 1
if self.max_tweets and self.counter > self.max_tweets:
print "Set limit of %s reached" % self.max_tweets
return False
def on_error(self, status_code):
print >> sys.stderr, 'Problem with stream: ', status_code
#continue
return True
def on_timeout(self):
print >> sys.stderr, 'currently timed out..'
return True
def on_limit(self, track):
print "-!- Collection limit hit. {0} matching tweets not delivered".format(track)
#if disconnected by twitter, report and stop
def on_disconnect(self, notice):
print "Disconnected by twitter. Reason: {0}".format(notice['reason'])
return False
if __name__ == "__main__":
"""do twitter authentication here"""
#At http://dev.twitter.com sign up for new application (need twitter account)
consumer_key="PERSONAL, GET FROM TWITTER"
consumer_secret="PERSONAL, GET FROM TWITTER"
# get by https://dev.twitter.com/oauth/overview/application-owner-access-tokens
access_token="PERSONAL, GET FROM TWITTER"
access_token_secret="PERSONAL, GET FROM TWITTER"
#get authorization
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
"""set max tweet n (keep empty if continously, then stop with ctrl+c)"""
max_tweets = 100
#set up the listener and pass in the api and max, db will be created in this object"""
listener = tweepy.streaming.Stream(auth, TweetsStreamListener(api, max_tweets))
"""Set filter about what you want the stream to pick up."""
listener.filter(track=["susi", "manhattan" ], languages=["en"]) |
218bb37891952f08845e09549086bcada21d9915 | JasonBehrend7/Behrend_Jason | /PyLesson_11/TwoPoints.py | 1,181 | 3.96875 | 4 | import math
class Distance:
def __init__ (self, x1, y1, x2, y2):
self.xOne = x1
self.yOne = y1
self.xTwo = x2
self.yTwo = y2
self.distance = 0
def newPoints (self, x1, y1, x2, y2):
self.xOne = x1
self.yOne = y1
self.xTwo = x2
self.yTwo = y2
self.distance = 0
def getDistance (self):
self.distance = math.sqrt((self.xTwo-self.xOne)*(self.xTwo-self.xOne)+(self.yTwo-self.yOne)*(self.yTwo-self.yOne))
return self.distance
def main():
x1 = int(input("Set the first x value: "))
y1 = int(input("Set the first y value: "))
x2 = int(input("Set the second x value: "))
y2 = int(input("Set the second y value: "))
distance = Distance(x1, y1, x2, y2)
print("Distance = {:>0.2f}".format(distance.getDistance()))
print("""
""")
x1 = int(input("Reset the first x value: "))
y1 = int(input("Reset the first y value: "))
x2 = int(input("Reset the second x value: "))
y2 = int(input("Reset the second y value: "))
distance.newPoints(x1, y1, x2, y2)
print("Distance = {:>0.2f}".format(distance.getDistance()))
main()
|
d91dc4ccdf8353e8572c58a2c84e90fa33a13f59 | cheeordie1/Article-Filterer | /nlp/highlight.py | 1,132 | 3.53125 | 4 | """
Usage: python3 highlight.py <user_id> <article_id>
Outputs: a JSON document specifying which paragraphs of the article should be
highlighted based on the user's article history
"""
import psycopg2
import sys
"""
highlight the article based on the user's history using some method
params:
article: string containing article to be highlighted
user_history: list of article strings
"""
def highlight(article, user_history):
# insert method here
pass
user_id = sys.argv[1]
article_id = sys.argv[2]
conn = psycopg2.connect("host=localhost dbname=article-filter_test user=pguser password=dbpass")
cur = conn.cursor()
cur.execute(('SELECT a.text FROM articles a INNER JOIN user_articles ua '
'on a.id=ua.article_id WHERE ua.user_id = %s AND a.id != %s'),
(user_id, article_id))
user_history = []
read_article = cur.fetchone()
while read_article is not None:
user_history.append(read_article[0])
read_article = cur.fetchone()
cur.execute('SELECT a.text From articles a WHERE a.id = %s', article_id)
article = cur.fetchall()[0][0]
result = highlight(article, user_history)
print(result)
|
1c7c6954e44e345c0ff34a26c502ddd65728d60e | prathapSEDT/pythonnov | /Collections/List/Remove.py | 167 | 3.90625 | 4 | myList=['a',4,7,2,9,3,7]
'''
this method is use to remove an element by using the value
remove the first occurance
'''
myList.remove(7)
myList.remove(11)
print(myList) |
8c13059bc98413be841869e72ba6b93a606bff09 | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/296/78458/submittedfiles/testes.py | 153 | 3.953125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
n = int(input("Digite um número: "))
if n%2==0:
print(PAR)
else:
print(ÍMPAR)
|
e8ca86fa465c922f454098f1c1f5f398df28612a | sleighsoft/algorithms | /countingsort.py | 1,164 | 3.875 | 4 | def countingsort(input, key=lambda x: x): # O(n+k) -> k = non-negative value range
"""A 2-pass sort algorithm that is efficient when the number of distinct
keys is small compared to the number of items.
Stable sorting.
Args:
input ([List[int]]): List of positive integers.
key (Callable[[int], int]): Key function that takes an element of input
and outputs a key.
Returns:
List[int]: Sorted list.
"""
# Value range
k = max(input) + 1
# Count occurrence of each value
count = [0 for _ in range(k)]
for x in input: # O(k)
count[key(x)] += 1
# Determine position of value
# position = current_position + number of occurrences
total = 0
for i in range(k): # O(k)
count[i], total = total, count[i] + total
# Build output
output = [0 for _ in range(len(input))]
for x in input: # O(n)
output[count[key(x)]] = x
count[key(x)] += 1 # Shift next position of same value by 1 to the right
return output
if __name__ == "__main__":
print("Countingsort:", countingsort([1, 2, 3, 4, 0, 0, 1, 2, 3, 4, 10, 8, 7]))
|
3b31e658f0721a83498a44704998368ea7025894 | imsreyas7/DAA-lab | /Recursion/matpow.py | 1,049 | 4.15625 | 4 | def print_matrix(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print("\t",matrix[i][j],end=" ")
print("\n")
a=int(input("Enter the power for power of the matrix "))
m = int( input("enter first matrix rows "));
n = int( input("enter first matrix columns "));
array1=[[0 for j in range (0 , n)] for i in range (0 , m)]
result=[[0 for j in range (0 , n)] for i in range (0 , m)]
print ("enter first matrix elements: " )
for i in range(0 , m):
for j in range(0 , n):
array1[i][j]=int (input("enter element "))
def mul(array1,array2):
result2=[[0 for j in range (0 , n)] for i in range (0 , m)]
# i will run throgh each row of matrix1
for i in range(0 , m):
# j will run through each column of matrix 2
for j in range(0 , n):
# k will run throguh each row of matrix 2
for k in range(0 , m):
result2[i][j] += array1[i][k] * array2[k][j]
return result2
result=mul(array1,array1)
for q in range(0,a-2):
result = mul(result,array1)
print_matrix(result)
|
7a8492a30cc6962a05e52ab1a2fecdaffd96ff9e | JosephPress13/CP1404-Early-Pracs | /Loops.py | 322 | 3.984375 | 4 | for i in range(1, 21, 2):
print(i, end=' ')
print()
for i in range(0, 100, 10):
print(i, end=' ')
print()
for i in range(20, 0, -1):
print(i, end=' ')
print()
n = int(input("How many stars would you like? "))
for i in range(0, n):
for i in range(0, i):
print("*", end=" ")
print("*")
print() |
463e5699efe5ec96e680b420539671763a8747b9 | SwetaNikki/Python-Assignment | /DivisibleNumber.py | 486 | 4.125 | 4 | #Write a program which will find all such numbers which are divisible by 7 but are not a
#multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed
#in a comma-separated sequence on a single line.
a = []
def mul():
for i in range(2000,3201):
if (i%7==0) and (i%5!=0):
a.append(str(i))
print ("The number numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 are : ")
mul()
print (','.join(a))
|
2e5f03335fba0c80afb363b756d5c3975f65f9b2 | franklingu/leetcode-solutions | /questions/prime-number-of-set-bits-in-binary-representation/Solution.py | 1,315 | 3.9375 | 4 | """
Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.
(Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.)
Example 1:
Input: L = 6, R = 10
Output: 4
Explanation:
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
9 -> 1001 (2 set bits , 2 is prime)
10->1010 (2 set bits , 2 is prime)
Example 2:
Input: L = 10, R = 15
Output: 5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)
Note:
L, R will be integers L <= R in the range [1, 10^6].
R - L will be at most 10000.
"""
class Solution(object):
def countPrimeSetBits(self, L, R):
"""
:type L: int
:type R: int
:rtype: int
"""
ret = 0
primes = set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31])
for n in xrange(L, R + 1):
ones = [e for e in bin(n)[2:] if e == '1']
if len(ones) in primes:
ret += 1
return ret
|
e6462622f0a865a9d16e244a1a63f3ad1cbf0dbe | sunnyyeti/Leetcode-solutions | /966_Vowel-Spellchecker.py | 2,774 | 4.21875 | 4 | # Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.
# For a given query word, the spell checker handles two categories of spelling mistakes:
# Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist.
# Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow"
# Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow"
# Example: wordlist = ["yellow"], query = "yellow": correct = "yellow"
# Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.
# Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw"
# Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match)
# Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match)
# In addition, the spell checker operates under the following precedence rules:
# When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.
# When the query matches a word up to capitlization, you should return the first such match in the wordlist.
# When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
# If the query has no matches in the wordlist, you should return the empty string.
# Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].
class Solution:
def spellchecker(self, wordlist, queries):
"""
:type wordlist: List[str]
:type queries: List[str]
:rtype: List[str]
"""
wordset = set(wordlist)
pos_dict = {}
devowl_pos_dict = {}
for i,w in enumerate(wordlist):
pos_dict[w.lower()] = min(pos_dict.setdefault(w.lower(),len(wordlist)),i)
devowl = self.get_replaced_word(w.lower())
devowl_pos_dict[devowl] = min(devowl_pos_dict.setdefault(devowl,len(wordlist)),i)
res = []
for q in queries:
if q in wordset:
res.append(q)
elif q.lower() in pos_dict:
res.append(wordlist[pos_dict[q.lower()]])
elif self.get_replaced_word(q.lower()) in devowl_pos_dict:
res.append(wordlist[devowl_pos_dict[self.get_replaced_word(q.lower())]])
else:
res.append("")
return res
def get_replaced_word(self,word):
vowels = {"a","e","i","o","u"}
return "".join("*" if c in vowels else c for c in word ) |
a4d12211caee375656252a5caf18575a006b3891 | mindw96/nalcoding | /mathutil.py | 4,581 | 3.5625 | 4 | import _csv
import os
import PIL.Image
import matplotlib.pyplot as plt
import numpy as np
# 수학적인 계산이 필요한 함수들을 모아둔 파일이다.
def relu(x):
return np.maximum(x, 0)
def relu_derv(y):
return np.sign(y)
def sigmoid(x):
return np.exp(-relu(-x)) / (1.0 + np.exp(-np.abs(x)))
def sigmoid_derv(y):
return y * (1 - y)
def sigmoid_cross_entropy_with_logits(z, x):
return relu(x) - x * z + np.log(1 + np.exp(-np.abs(x)))
def sigmoid_cross_entropy_with_logits_derv(z, x):
return -z + sigmoid(x)
def tanh(x):
return 2 * sigmoid(2 * x) - 1
def tanh_derv(y):
return (1.0 + y) * (1.0 - y)
def softmax(x):
max_elem = np.max(x, axis=1)
diff = (x.transpose() - max_elem).transpose()
exp = np.exp(diff)
sum_exp = np.sum(exp, axis=1)
probs = (exp.transpose() / sum_exp).transpose()
return probs
def softmax_cross_entropy_with_logits(labels, logits):
probs = softmax(logits)
return -np.sum(labels * np.log(probs + 1.0e-10), axis=1)
def softmax_cross_entropy_with_logits_derv(labels, logits):
return softmax(logits) - labels
# csv 파일을 한 줄씩 읽어와서 리스트 형식으로 반환해주는 함수이다.
def load_csv(path, skip_header=True):
with open(path) as csvfile:
csvreader = _csv.reader(csvfile)
headers = None
if skip_header:
headers = next(csvreader, None)
rows = []
for row in csvreader:
rows.append(row)
return rows, headers
'''
원핫인코딩이란 0,1외의 다른 숫자나 문자가 레이블로 주어졌을 때 이름 0과 1로 인코딩해주는 것을 말한다.
예를 들어 1,2,3이 주어진다면 [1,0,0],[0,1,0],[0,0,1] 등으로 바꿔서 표현해줄 수 있다.
'''
# xs 텐서의 값들을 cnt크기의 원-핫 벡터로 변환해주는 함수이다.
def onehot(xs, cnt):
# cnt 크기의 단위 행렬을 선언하고 각 값을 int로 해줌으로써 나중에 발생할지 모르는 충동을 방지한다.
return np.eye(cnt)[np.array(xs).astype(int)]
# 벡터를 문자열로 변환해주는 함수이다.
def vector_to_str(x, fmt='%.2f', max_cnt=0):
# max_cnt가 0이거나 x의 길이가 max_cnt보다 작다면 벡터 그대로 문자열로 반환해준다.
if max_cnt == 0 or len(x) <= max_cnt:
return '[' + ','.join([fmt] * len(x)) % tuple(x) + ']'
# 아니라면 과도하게 긴 문자열의 생성을 막는다.
v = x[0:max_cnt]
return '[' + ','.join([fmt] * len(v)) % tuple(v) + ',...]'
# 이미지를 numpy 배열로 변환해주는 함수이다.
def load_image_pixels(imagepath, resolution, input_shape):
# PIL 라이브러리를 활용해서 이미지 파일을 열어준다.
img = PIL.Image.open(imagepath)
# 이미지의 크기를 전달받은 해상도로 변환한다.
resized = img.resize(resolution)
# 전달받은 형태로 shape을 변환하고 numpy 배열로 변경한다.
return np.array(resized).reshape(input_shape)
# 이미지를 화면에 출력해주는 함수이다.
def draw_images_horz(xs, image_shape=None):
# 출력할 xs의 개수를 구한다.
show_cnt = len(xs)
# 이미지를 출력할 plot의 크기를 설정한다.
# xs의 개수만큼 반복문을 통해 출력할 이미지를 설정한다.
for n in range(show_cnt):
img = xs[n]
if image_shape:
x3d = img.reshape(image_shape)
img = PIL.Image.fromarray(np.uint8(x3d))
axes = plt.subplot(1, show_cnt, n + 1)
axes.imshow(img)
axes.axis('off')
# 이미지들을 화면에 출력한다.
plt.draw()
plt.show()
# 선택 분류의 결과를 출력해주는 함수이다.
def show_select_results(est, ans, target_names, max_cnt=0):
for n in range(len(est)):
pstr = vector_to_str(100 * est[n], '%2.0f', max_cnt)
estr = target_names[np.argmax(est[n])]
astr = target_names[np.argmax(ans[n])]
rstr = '0'
if estr != astr:
rstr = 'X'
print('추정 확률 분포 {} => 추정 {} : 정답 {} => {}'.format(pstr, estr, astr, rstr))
# 특정 폴더에 있는 파일이나 서브 폴더의 이름을 모아 정렬된 형태의 리스트로 반환해주는 함수이다.
def list_dir(path):
# 파이썬 내장 라이브러리인 os를 활용하여 전달 받은 경로에서 파일들의 목록을 리스트로 불러온다.
filenames = os.listdir(path)
# 불러온 리스트를 정렬한다.
filenames.sort()
return filenames
|
6ed9eb4759db5319b23c169fa82af8be70610701 | SnottyJACK/Python_Projects | /Password.py | 393 | 3.765625 | 4 | #Password
#if construction demonstration
print("Добро пожаловать к нам в ООО \"Системы безопасности\".")
print("--Безопасность - наше второе имя\n")
password = input("Введите пароль: ")
if password == "abrakadabra":
print("Доступ открыт")
else:
print("Вы не прошли проверку")
|
1f4471e03e63bc0a35bffda9d588b9bad50b7be8 | D-J-Harris/AdventOfCode2020 | /days/day18.py | 1,567 | 3.609375 | 4 | """Operation Order"""
def act_op(left, right, op):
if op == '+':
return left + right
if op == '*':
return left * right
def evaluate(inp, first):
if first:
ans = 0
operator = ''
for x in inp:
if isinstance(x, int):
if ans == 0:
ans = x
else:
ans = act_op(ans, x, operator)
else:
operator = x
else:
for idx, x in enumerate(inp):
if x == '+':
tmp = int(inp[idx - 1]) + int(inp[idx + 1])
del inp[idx - 1]
inp[idx] = tmp
ans = 1
for num in inp:
if num != '+' and num != '*':
ans *= num
return ans
def get_result(line, first):
subs_count = 0
subs = [[]]
for c in line:
if c == '(':
subs_count += 1
subs.append([])
elif c == ')':
a = evaluate(subs[-1], first)
del subs[-1]
subs_count -= 1
subs[-1].append(a)
else:
if c == ' ':
continue
elif c.isnumeric():
c = int(c)
subs[subs_count].append(c)
return evaluate(subs[0], first)
with open('../inputs/day18.txt', 'r') as f:
ans1, ans2 = 0, 0
for line in f.read().splitlines():
ans1 += get_result(line, first=True)
ans2 += get_result(line, first=False)
print(f'answer to puzzle 1 is {ans1}')
print(f'answer to puzzle 2 is {ans2}')
|
4febab4366ab130c81aeff1658d59882a1be875c | Anjana97/python | /pythondatastructures/listprograms/listprograms.py | 194 | 3.9375 | 4 | list=["java","python","c#","javascript"]
# print(type(list))
# print(list[-1:-4:-1])
# list.append("dart")
# list[1]="ruby"
# for item in list:
# # print(item)
list.insert(2,"c")
print(list) |
7f858f5b83315edc2fd7f94a0790d5439a4c4e74 | Asim-Product-College/CS-1.1-Programming-Fundamentals | /MadLibs/madlibs.py | 3,539 | 3.609375 | 4 | # CS 1.1
# Project: Mad Libs
# Written By: Asim Zaidi
# List of Requirements
# Write madlibs program
#list or string, or some different data structure of stories to change, choose from set of stories.
# ask for 5 user inputs line by line.
# randomize user inputs
# insert mad libs into template and return that to user.
# error check test inputs, what happens if user inputs whitespace only.
# import statements
#Ikey's sick color idea
import colors as c
from time import sleep
import sys
import random
def exiting():
print_slowly("Wow really, okay.. you'll be back though.")
exit()
def print_slowly(text):
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
sleep(0.05)
print('')
# User Questionare Function
def userQuestionare(selectedStory):
adjective1 = input("Tell me an adjective, and click enter. ")
adjective2 = input("Tell me an another adjective, and click enter. ")
noun1 = input("Tell me a noun (plural), and click enter. ")
noun2 = input("Tell me another noun, and click enter. ")
if noun2 == "exit" or noun1 == "exit" or adjective2 == "exit" or adjective1 == "exit":
exiting()
# randomize inputs
nounList = [noun1,noun2]
adjList = [adjective1, adjective2]
random.shuffle(nounList)
random.shuffle(adjList)
if selectedStory=="funny":
print("I have been having the " + adjList[0] + " dreams. I dreampt last night that i looked exactly like the girl from wendys restaurants. I even had a " + adjList[1] + " full of those checkered dresses and nothing else. Some of my other " + nounList[0] + " dreams that I had lately were I was a genie in a " + nounList[1] + " but no one would let me out.")
if selectedStory=="childrens":
print("Today a superhero named captain rainbow came to our school to talk to us about their job. She said the most important skill you need to know to do her job is to be able to laugh around (a) " + adjList[0] + " " + nounList[0] + ". She said it was easy for her to learn her " + nounList[1] + " because she loved how her thoughts were so " + adjList[1] + "!")
if selectedStory=="adult":
print(nounList[0] + " be " + adjList[0] + " like they be " + adjList[1] + " when they're chilling and playing poker with their " + nounList[1] + ".")
# start the story printing
print_slowly(c.green + "Welcome to Mad Libs. Created by " + c.yellow + "Asim Zaidi." + c.end)
print_slowly("Would you like a funny, childrens, or adult MadLib to play with?")
print_slowly("At any time enter 'exit' to quit the cool game.")
# collect the selected story from the user input, by validating the input (if it's A, B, or C. Otherwise, print error and try again)
userStory = ""
isRunning = True
while isRunning==True:
userChoice = input("Enter " + c.blue + "A" + c.end + " for funny\nEnter " +c.blue + "B" + c.end + " for childrens\nEnter " + c.blue + "C" + c.end + " for adults\n")
if userChoice == "exit":
exiting()
if userChoice == "A" or userChoice=="a":
userStory="childrens"
isRunning = False
elif userChoice == "B" or userChoice=="b":
userStory="funny"
isRunning = False
elif userChoice == "C" or userChoice=="c":
userStory="adult"
isRunning = False
else:
print_slowly("Please type in A, B or C. Other inputs are not accepted at this time.")
# after selecting the story from the user, start the questionare
print_slowly(c.magenta+"Okay let's begin.. answer these questions ;)" + c.end)
userQuestionare(userStory)
|
ff646a54d7b5e9b602c5ebe5d223819866659485 | oneTaken/leetcode | /easy/575.py | 262 | 3.53125 | 4 | class Solution:
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
length = len(candies)
kinds = len(set(candies))
return length // 2 if kinds >= length // 2 else kinds
|
6d3cfcec4626a9ba21cd1d113dd4e98f3da75f6f | Llari7/mi_primer_programa | /Calculadora.py | 584 | 4 | 4 |
operacion = input("¿Qué operación deseas realizar? (suma / resta / multiplicación / división): ")
primer_numero = int(input("Primer número: "))
segundo_numero = int(input("Segundo número: "))
if operacion == "suma":
print("Resultado: {}".format(primer_numero + segundo_numero))
elif operacion == "resta":
print("Resultado: {}".format(primer_numero - segundo_numero))
elif operacion == "multiplicación":
print("Resultado: {}".format(primer_numero * segundo_numero))
elif operacion == "división":
print("Resultado: {}".format(primer_numero / segundo_numero))
|
2d72456219249154ae02e5646abf5401e782e78f | zako16/heinold_exercises | /1Basics/2Numbers/2-19.py | 517 | 4.15625 | 4 | """
Write a program that draws “modular rectangles” like the ones below. The user specifies the
width and height of the rectangle, and the entries start at 0 and increase typewriter fashion
from left to right and top to bottom, but are all done mod 10. Below are examples of a 3 × 5
rectangle and a 4 × 8 .
"""
wide = eval(input("Enter wide:"))
high = eval(input("Enter high:"))
count = 0
for i in range(high):
for j in range(wide):
print(count % 10, end=" ")
count += 1
print(end="\n")
|
a36950a2e22c8631111ab36b0dd8c44e4fe44957 | ConstantinescuRachel-zz/PLP | /Problem 2.py | 570 | 3.9375 | 4 | # Define a class which has at least two methods:
# getString: to get a string from console input
# printString: to print the string in upper case.
# Hints:
# Use __init__ method to construct some parameters
class InputOutString:
def __init__(self):
print "Test" #why if I remove this line, I get errors for indented block?
def getString(self):
self.input_var = raw_input("Type a string: ")
def printStringUpperCase(self):
print self.input_var.upper()
myObject = InputOutString()
myObject.getString()
myObject.printStringUpperCase()
|
590628bbd553024a9eb968451cef42cff6c68d86 | VSMourya/Leetcode_Easy | /Best Time to Buy and Sell Stock II.py | 442 | 3.796875 | 4 |
def maxProfit(prices):
stack = []
profit = 0
for price in prices:
if not stack:
stack.append(price)
else:
if stack[-1] > price:
stack[-1] = price
else:
profit += price -stack[-1]
stack[-1] = price
return profit
if __name__ == '__main__':
prices = [7,1,5,3,6,4]
print(maxProfit(prices))
|
69d0b1cd077f8f62db0383eea91f5206c35aafd0 | bferriman/python-learning | /examples/strings1.py | 1,131 | 4.5625 | 5 | # strings can be in single, double, or triple quotes
print(type('3'))
print(type("3"))
print(type('''3'''))
samp_string = "This is a very important string"
print("Length:", len(samp_string))
# reference first char in samp_string
print(samp_string[0])
# reference last char in samp_string
print(samp_string[-1])
# grab slice of samp_string from char 0 (inclusive) to 4 (exclusive)
print(samp_string[0:4])
# a slice from 8 (inclusive) through end of string
print(samp_string[8:])
# from 0 to last char (exclusive) skipping every other char
print(samp_string[0:-1:2])
# reverses characters in string
print(samp_string[::-1])
# concatenation
print("Green " + "eggs")
# repeat a string
print("Hello " * 3)
# convert int to string
num_string = str(4)
# can iterate through string like array with for in, char is just a var name, can be anything
for char in samp_string:
print(char)
# range returns 0 - (len - 1 exclusive), skipping every other number
# so this prints the string in blocks of two chars, omitting last char for odd len strings
for i in range(0, len(samp_string)-1, 2):
print(samp_string[i] + samp_string[i+1])
|
a7a76576a08a327259bb981cb861ded391f56304 | kunzhang1110/COMP9021-Principles-of-Programming | /Quiz/Quiz_8/quiz_8.py | 3,377 | 4.09375 | 4 | # Randomly fills a grid of size 10 x 10 with digits between 0
# and bound - 1, with bound provided by the user.
# Given a point P of coordinates (x, y) and an integer "target"
# also all provided by the user, finds a path starting from P,
# moving either horizontally or vertically, in either direction,
# so that the numbers in the visited cells add up to "target".
# The grid is explored in a depth-first manner, first trying to move north, always trying to keep the current direction,
# and if that does not work turning in a clockwise manner.
#
# Written by Kun Zhang and Eric Martin for COMP9021
import sys
from random import seed, randrange
from array_stack import *
dim = 10
grid = [[0] * dim for _ in range(dim)]
def display_grid():
for i in range(dim):
print(' ', end = '')
for j in range(dim):
print(' ', grid[i][j], end = '')
print()
print()
def explore_depth_first(x, y, target):
def explore(target, path, direction, current_sum, all_directions_copy):
current_pos = path.peek()
next_pos = (current_pos[0] + direction[0],
current_pos[1] + direction[1])
if next_pos in path._data:
return False
if next_pos[0] not in range(dim) or next_pos[1] not in range(dim):
return False
new_sum = current_sum + grid[next_pos[0]][next_pos[1]]
if new_sum > target:
return False
if new_sum == target:
path.push(next_pos)
return True
if new_sum < target:
path.push(next_pos)
all_directions_copy.remove(direction)
all_directions.insert(0, direction)
for direction in all_directions_copy:
if explore(target, path, direction, new_sum, all_directions_copy):
return path
else:
continue
return False
all_directions = [(-1, 0), (0, 1), (1, 0), (0, -1)] # clockwise N, E, S, W
path = ArrayStack()
path.push((x, y))
direction = all_directions[0]
current_sum = grid[x][y]
for direction in all_directions:
if explore(target, path, direction, current_sum, all_directions):
if len(path._data)<2:
return None
else:
return path._data
break
return None
provided_input = input('Enter five integers: ').split()
if len(provided_input) != 5:
print('Incorrect input, giving up.')
sys.exit()
try:
seed_arg, bound, x, y, target = [int(x) for x in provided_input]
if bound < 1 or x < 0 or x > 9 or y < 0 or y > 9 or target < 0:
raise ValueError
except ValueError:
print('Incorrect input, giving up.')
sys.exit()
seed(seed_arg)
# We fill the grid with randomly generated digits between 0 and bound - 1.
for i in range(dim):
for j in range(dim):
grid[i][j] = randrange(bound)
#print('Here is the grid that has been generated:')
#display_grid()
path = explore_depth_first(x, y, target)
if not path:
print('There is no way to get a sum of {} starting '
'from ({}, {})'.format(target, x, y))
else:
print('With North as initial direction, and exploring '
'the space clockwise,\n'
'the path yielding a sum of {} starting from '
'({}, {}) is:\n {}'.format(target, x, y, path))
|
4b3828a25560426b7934056c483a5d798828dbc9 | s3wasser/WATcher | /HTMLScraper.py | 2,187 | 3.828125 | 4 | import urllib2
from bs4 import BeautifulSoup
# Simple HTML scraping and parsing class using the Beautiful Soup Library
# To use, simply instantiate and call getCourseInformationTable to get a
# 2D array of the course information
class HTMLTableParser:
userAgent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
headers = {'User-Agent': userAgent}
def __init__(self, courseNum, subject, termSessionNumber):
self.courseNum = courseNum
self.subject = subject
self.termSessionNumber = termSessionNumber
baseUrl = 'http://www.adm.uwaterloo.ca/cgi-bin/cgiwrap/infocour/salook.pl?'
self.requestUrl = baseUrl + 'sess=' + str(termSessionNumber) + '&subject=' + subject + '&cournum=' + str(courseNum)
# html request to make soup, which returns the HTML webpage format
def getHTMLFromPage(self):
try:
req = urllib2.Request(self.requestUrl, headers=self.headers)
response = urllib2.urlopen(req)
except urllib2.HTTPError, err:
return -1
else:
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
return soup
# The first table on the site always seems to be generalized info about
# the course itself that we don't need. Second table contains all the
# enrollment + course section stuff we need, so we'll return that.
# Not the safest implementation, but this site is old and hasn't changed
# in YEARS, so I'm willing to risk it
def getCourseInfoTable(self, soup):
return soup.findAll('table')[1]
def convertTableTo2DArray(self, table):
result = []
tableHeader = True
allrows = table.findAll('tr')
for row in allrows:
result.append([])
if (tableHeader):
allcols = row.findAll('th') # the first row of the table is all table header tags, so we must differentiate between them
tableHeader = False
else:
allcols = row.findAll('td')
for col in allcols:
thestrings = [unicode(s) for s in col.findAll(text=True)]
thetext = ''.join(thestrings)
result[-1].append(thetext)
return result
def getCourseInformationTable(self):
soup = self.getHTMLFromPage()
courseInfoTable = self.getCourseInfoTable(soup)
courseInfoArray = self.convertTableTo2DArray(courseInfoTable)
return courseInfoArray
|
cdfde67210d0fe5c80ed89b60180a1bb07431908 | msszczep/npr_sunday_puzzle_solutions | /src/python/puzzle_2014-01-19.py | 1,837 | 3.734375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
http://www.npr.org/2014/01/19/263785641/three-bs-bring-you-to-one
Name a famous person whose first and last names together contain four doubled letters -- all four of these being
different letters of the alphabet. Who is it? For example, Buddy Holly's name has two doubled letters, D and L.
"""
def filter_d(d):
count = 0
tripwire = 0
for k, v in d.iteritems():
if k.isdigit():
return False
if v == 2:
count = count + 1
if k == '_' and v == 1:
tripwire = 1
if k.isalpha() == False and k != '_':
return False
if count == 4 and tripwire == 1:
return True
return False
def filter_d_two(d):
for k, v in d.iteritems():
if k.isdigit():
return False
if k == '_' and v != 1:
return False
return True
def get_two_grams(word):
to_return = []
for i in range(len(word) - 1):
to_return.append(word[i:i+2].lower())
return to_return
def filter_two_grams(two_grams):
fours = set()
for t in two_grams:
if t[0] == t[1] and t[0].isalpha():
fours.add(t[0])
if len(fours) == 4:
return True
return False
def get_d(word):
to_return = {}
for char in word.lower():
try:
to_return[char] = to_return[char] + 1
except:
to_return[char] = 1
return to_return
def main():
import sys
fours = set()
words = open('enwiki-20131001-all-titles').readlines()
#words = ['hello', 'world']
for word in words:
word = word[:-1]
d = get_d(word)
two_grams = get_two_grams(word)
if filter_two_grams(two_grams) and filter_d_two(d):
print word
if __name__ == "__main__":
main()
|
0fc986d8da7cd1b7eb6de435b18d7c48bf70e14e | ash/amazing_python3 | /144-fib.py | 164 | 3.828125 | 4 | # Generating and printing
# Fibonacci numbers
# below 100
a, b = 0, 1
while a < 100:
print(a)
a, b = b, a + b
# Notice how nice is
# multiple assignment |
f1a1fcf2223a9c2d62512e0864d98ed8d37447e9 | KatyaKalache/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 172 | 3.90625 | 4 | #!/usr/bin/python3
class MyList(list):
list = []
def print_sorted(self):
MyList.list.append(self)
for i in self.list:
print(sorted(i))
|
039241463202bb8aea84cfebf94514b59807b218 | chen13545260986/hello_python | /4常用模块/json模块.py | 447 | 3.5 | 4 | # 序列化模块
# 序列化--转向一个字符串数据类型
# 序列--字符串
# json:dumps序列化方法,loads反序列化方法
import json
dic = {'k1':'v1'}
str_d = json.dumps(dic)
print(type(str_d), str_d)
dic_d = json.loads(str_d)
print(type(dic_d), dic_d)
# json:dump和load
# f = open('fff', 'w', encoding='utf-8')
# json.dump(dic, f)
# f.close()
f2 = open('fff', 'r', encoding='utf-8')
res = json.load(f2)
print(type(res), res) |
b086a56fd1fc5e28b7c38ba4b7bc798e7a1b16f4 | tantziu/Algorithms_python | /graph_playground.py | 2,194 | 3.71875 | 4 | import collections
def dfs_recursion(graph, node, visited=None):
if visited is None:
visited = set()
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:
dfs_recursion(graph, neighbour, visited)
def bfs_recursion(graph, queue=None, visited=None):
if visited is None:
visited = set()
if queue is None:
queue = ['1']
if queue:
node = queue.pop(0)
print(node)
for neighbour in graph[node]:
if neighbour not in visited:
queue.append(neighbour)
visited.add(neighbour)
bfs_recursion(graph, queue, visited)
def dfs_with_stack(graph, node):
visited = set()
stack = [node]
while stack:
node = stack.pop()
print(node)
if node not in visited:
visited.add(node)
for neighbour in graph[node]:
if neighbour not in visited:
stack.append(neighbour)
def bfs_with_queue(graph, node):
visited = set()
queue = [node]
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
print(node)
if node in graph.keys():
for neighbour in graph[node]:
if neighbour not in visited:
queue.append(neighbour)
def get_adjacency_list(edges):
result = collections.defaultdict(list)
for source, destination in edges:
# if result.get(source) is None:
# result[source] = [destination]
# else:
result[source].append(destination)
return result
def from_adjacency_list_to_tree():
return
def bfs_for_tree():
return
if __name__ == '__main__':
graph = {
'1': ['2', '3'],
'2': ['4', '5'],
'3': ['6'],
'4': [],
'5': ['6'],
'6': []
}
edges = [
(1, 2),
(1, 3),
(2, 4),
(2, 5),
(3, 6),
(5, 6)
]
# dfs_recursion(graph, '1')
# dfs_with_stack(graph, '1')
# bfs_with_queue(graph, '1')
# bfs_recursion(graph)
# print(get_adjacency_list(edges))
|
08780bf97369149720e3b7f9d75a9d714644eff5 | EmlynQuan/Programming-Python | /JZOffer/JZOffer27.py | 565 | 3.59375 | 4 | # coding=utf-8
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def mirrorTree(root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None:
return root
queue = [root]
while queue:
temp = queue[0]
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
node = temp.left
temp.left = temp.right
temp.right = node
queue.pop(0)
return root
|
48a599165d1fd8a8d3714aff112083418703d007 | jeanpierreba/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_base.py | 3,556 | 3.640625 | 4 | #!/usr/bin/python3
""" Unittest for Base class """
import unittest
import os
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
class Test_Base(unittest.TestCase):
""" Class to test the Base class """
def setUp(self):
Base._Base__nb_objects = 0
def test_no_args(self):
base1 = Base()
self.assertEqual(base1.id, 1)
base2 = Base()
self.assertEqual(base2.id, 2)
base3 = Base()
self.assertEqual(base3.id, 3)
def test_numbers(self):
base1 = Base(8)
self.assertEqual(base1.id, 8)
base2 = Base(-1)
self.assertEqual(base2.id, -1)
base3 = Base(12)
self.assertEqual(base3.id, 12)
base4 = Base(0)
self.assertEqual(base4.id, 0)
def test_instance(self):
base1 = Base()
self.assertTrue(isinstance(base1, Base))
rectangle1 = Rectangle(1, 1)
self.assertTrue(isinstance(rectangle1, Base))
square1 = Square(1)
self.assertTrue(isinstance(square1, Base))
def test_to_json(self):
list_none = None
to_json = Base.to_json_string(list_none)
self.assertEqual(to_json, "[]")
self.assertEqual(type(to_json), str)
list_empty = []
to_json = Base.to_json_string(list_empty)
self.assertEqual(to_json, "[]")
self.assertEqual(type(to_json), str)
dict_empty = [{}]
to_json = Base.to_json_string(dict_empty)
self.assertEqual(to_json, "[{}]")
self.assertEqual(type(to_json), str)
dict_ = [{'x': 4, 'y': 5}]
to_json = Base.to_json_string(dict_)
to_str = str(dict_)
self.assertEqual(to_json, to_str.replace("'", "\""))
self.assertEqual(type(to_json), str)
def from_json_string(self):
dict_ = [{'x': 3, 'y': 1}]
to_json = Base.to_json_string(dict_)
from_json = Base.from_json_string(to_json)
self.assertEqual(dict_, from_json)
self.assertEqual(type(to_json), str)
self.assertEqual(type(from_json), list)
list_empty = []
to_json = Base.to_json_string(l1)
from_json = Base.from_json_string(j1)
self.assertEqual(from_json, [])
self.assertEqual(type(to_json), str)
self.assertEqual(type(from_json), list)
def test_create_rectangle(self):
r1 = Rectangle(3, 5)
r1_dictionary = r1.to_dictionary()
r2 = Rectangle.create(**r1_dictionary)
str1 = str(r1)
str2 = str(r2)
self.assertEqual(str1, str2)
self.assertFalse(r1 is r2)
self.assertFalse(r1 == r2)
r1 = Rectangle(5, 2, 1)
r1_dictionary = r1.to_dictionary()
r2 = Rectangle.create(**r1_dictionary)
str1 = str(r1)
str2 = str(r2)
self.assertEqual(str1, str2)
self.assertFalse(r1 is r2)
self.assertFalse(r1 == r2)
def test_create_square(self):
s1 = Square(3)
s1_dictionary = s1.to_dictionary()
s2 = Square.create(**s1_dictionary)
str1 = str(s1)
str2 = str(s2)
self.assertEqual(str1, str2)
self.assertFalse(s1 is s2)
self.assertFalse(s1 == s2)
s1 = Square(2, 3, 5)
s1_dictionary = s1.to_dictionary()
s2 = Square.create(**s1_dictionary)
str1 = str(s1)
str2 = str(s2)
self.assertEqual(str1, str2)
self.assertFalse(s1 is s2)
self.assertFalse(s1 == s2)
if __name__ == "__main__":
unittest.main()
|
15598593efdf061ca0d18701ef611f6af9a44eb1 | CodemanNeil/LearningFromData | /HW2/CoinFlipping.py | 1,328 | 3.625 | 4 | import random
class CoinFlipping:
def __init__(self, numCoins = 1000, numFlips = 10):
self.numCoins = numCoins
self.numFlips = numFlips
self.headFrequency = [0] * self.numCoins
self.flipCoins()
def flipCoins(self):
for coinNumber in range(self.numCoins):
for flipNumber in range(self.numFlips):
# Heads
if random.random() > 0.5:
self.headFrequency[coinNumber] += 1
def getV1(self):
return self.headFrequency[0] / float(self.numFlips)
def getVRand(self):
return random.choice(self.headFrequency) / float(self.numFlips)
def getVMin(self):
return min(self.headFrequency) / float(self.numFlips)
if __name__ == "__main__":
numIterations = 100000
averageV1 = 0
averageVRand = 0
averageVMin = 0
for i in range(numIterations):
coinFlipping = CoinFlipping()
averageV1 += coinFlipping.getV1()
averageVRand += coinFlipping.getVRand()
averageVMin += coinFlipping.getVMin()
averageV1 /= float(numIterations)
averageVRand /= float(numIterations)
averageVMin /= float(numIterations)
print "Average V1: " + str(averageV1)
print "Average Vmin: " + str(averageVMin)
print "Average Vrand: " + str(averageVRand) |
b95b9f02326ea5b5f63158c3af4b8f36b06a946b | solkan1201/Vivace | /code/libs/modos_de_transmissao.py | 511 | 3.609375 | 4 | class SeletorDeModos(object):
def __init__(self, criador):
self.criador = criador
def setModo(self, modo):
"""Função responsável por setar o modo de tranmissao de dados.
"""
self.criador.modo.valor = modo
print('Trocando para modo ' + str(modo) + ' de transmissao!')
if modo == 1:
# Do something
pass
elif modo == 2:
# Do something
pass
else:
# Do nothing
pass |
458389f0c946dd660fd0b7b140caea1d11f2ade2 | iljuhas7/lab-9 | /example_1.py | 1,499 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
school = {'1а': 12, '1б': 24, '2а': 10, '2б': 8, '6a': 25, '6б': 13, '8а': 14, "9б": 12}
while True:
n = input('Введите название операции >>> ')
if n == 'change':
school.update({input(f'Название изменяемого класса: '): int(input(f'Количество учеников '
f'изменяемого класса: '))})
elif n == 'new':
school.update({input(f'Название класса №: '): int(input(f'Количество учеников класса №: '))})
elif n == 'remove':
del school[input(f'Название расформировываемого класса: ')]
elif n == 'print':
print(school)
elif n == 'sum':
print(sum(school.values()))
elif n == "help":
print('\tchange - Изменилось количество учеников:')
print('\tnew - В школе появился новый класс')
print('\tremove - В школе был расформирован (удален) класс')
print('\tprint - Выгрузка данных')
print('\tsum - Число учеников')
print('\texit - Выход')
elif n == 'exit':
break
|
0127de62c5e7a9ca88b7b5968517a8e7be353afa | pisces0009/PythonProgram | /hamburger8.py | 1,812 | 4.0625 | 4 | ##############################################################
# fILE: humberger8.py
# Author: Prasad Kale
# Date: january.24,2018
# Purpose: Nested if statement
##############################################################
# print headings
print("\n ... Hamburger 8 ....")
print("======================\n")
#prompt uses for order
qty = input("\n Enter the number of hamburgers desired ==> ")
hamburgerType = input("\nType? Enter C for cheese, P for plain, or D for double ==> ")
#determine cost of hamburgers
if hamburgerType =='C' or hamburgerType =='c':
cost = 2.79
else:
if hamburgerType == 'P' or hamburgerType == 'p':
cost = 2.05
else:
if hamburgerType =='D' or hamburgerType == 'd':
cost = 3.59
else:
print("Wrong type!Run again!")
cost = 0.0
#endif
#endif
#endif
#calc total
total = cost * float(qty)
#output total cost
print("\nTotal cost is==>",total)
#prompt user for amount tended
amtGiven = input("\nEnter amount tended ==>$")
#calc and print change
change = float(amtGiven) - total
print("\nYour change is ==>$",change)
print("\n...end of job...\n")
#end main
################################################################
OUTPUT:
C:\Users\PRASAD>hamburger8.py
... Hamburger 8 ....
======================
Enter the number of hamburgers desired ==> 10
Type? Enter C for cheese, P for plain, or D for double ==> p
Total cost is==> 20.5
Enter amount tended ==>$50
Your change is ==>$ 29.5
...end of job...
C:\Users\PRASAD>hamburger8.py
... Hamburger 8 ....
======================
Enter the number of hamburgers desired ==> 1
Type? Enter C for cheese, P for plain, or D for double ==> c
Total cost is==> 2.79
Enter amount tended ==>$10
Your change is ==>$ 7.21
...end of job...
#################################################################### |
6e5dd0410247273d961e07c966e47f57c0d30f7e | Erick-ViBe/LeetCodePython | /ArraysAndStrings/longestSubstringWithoutRepeatingCharacters.py | 785 | 4.125 | 4 | """
Given a string s, find the length of the longest substring without repeating characters.
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""
def lengthOfLongestSubstring(s):
n = len(s)
left = 0
rigth = 0
r = 0
m = {}
while left<n and rigth<n:
el = s[rigth]
if el in m:
left = max(left, m[el]+1)
m[el] = rigth
r = max(r, (rigth-left)+1)
rigth += 1
return r
if __name__ == '__main__':
x = 'abaacad'
r1 = lengthOfLongestSubstring(x)
y = 'abcabcbb'
r2 = lengthOfLongestSubstring(y)
print(r1)
print('**********************')
print(r2)
|
8157fe73d2fb6760b575f87a89f368ce1819f72c | PeterSzasz/GraphApp | /utilities/delaunay.py | 8,805 | 3.5625 | 4 | # delaunay triangulation
from math import sqrt
import numpy as np
from utilities.node_generator import NodeGeneratorBase
from core.graph import Node,Edge, Graph
class Triangle(Graph):
'''
helper class for delaunay triangulation
the Bowyer-Watson algorithm uses it mostly
'''
def __init__(self):
super().__init__()
self.addNode(Node(0,0))
self.addNode(Node(0,0))
self.addNode(Node(0,0))
def __str__(self):
return str(f"<A:{self.getA()} B:{self.getB()} C: {self.getC()}>")
def addNode(self, node: Node):
if len(self.nodes) == 3:
self.setC(self.nodes[1])
self.setB(self.nodes[0])
self.setA(node)
else:
super().addNode(node)
def setA(self, node: Node):
self.nodes[0] = node
def setB(self, node: Node):
self.nodes[1] = node
def setC(self, node: Node):
self.nodes[2] = node
def getA(self) -> Node:
return self.nodes[0]
def getB(self) -> Node:
return self.nodes[1]
def getC(self) -> Node:
return self.nodes[2]
def checkNode(self, node):
if node == self.getA() or \
node == self.getB() or \
node == self.getC():
return True
else:
return False
def getAB(self) -> Edge:
return Edge(self.getA(),self.getB())
def getBC(self) -> Edge:
return Edge(self.getB(),self.getC())
def getCA(self) -> Edge:
return Edge(self.getC(),self.getA())
def nextEdge(self) -> Edge:
yield self.getAB()
yield self.getBC()
yield self.getCA()
def checkEdge(self, edge) -> bool:
if edge == self.getAB() or \
edge == self.getBC() or \
edge == self.getCA():
return True
else:
return False
class Delaunay(NodeGeneratorBase):
'''
Class for generating the Delaunay triangluation on given coordinates.
https://en.wikipedia.org/wiki/Delaunay_triangulation
'''
def __init__(self) -> None:
super().__init__()
def generate(self, nodes: list[Node]) -> tuple[list[Edge],list[Edge]]:
'''
Bowyer-Watson algorithm
https://en.wikipedia.org/wiki/Bowyer%E2%80%93Watson_algorithm
Args:
nodes (list[Node]): list of individual points that the
delaunay triangulation should run on
Returns:
list[Edge]: list of edges (point pairs) that
'''
delaunay_result: list[Edge] = []
voronoi_result: list[Edge] = []
voronoi_data = {}
if not nodes:
return delaunay_result, voronoi_result
triangulation: list[Triangle] = []
super_triangle = Triangle()
# TODO: should calculate min-max points and set accordingly
super_triangle.setA(Node(500,10000))
super_triangle.setB(Node(10000,-10000))
super_triangle.setC(Node(-10000,-10000))
triangulation.append(super_triangle)
for node in nodes:
bad_triangles = []
for tri in triangulation:
A = (tri.getA().x(),tri.getA().y())
B = (tri.getB().x(),tri.getB().y())
C = (tri.getC().x(),tri.getC().y())
# get circumcircle center and radius
cc_x, cc_y, cc_r = self.calcCircleMidpoint(A,B,C)
diff_x = cc_x - node.x()
diff_y = cc_y - node.y()
diff_length = sqrt(diff_x*diff_x + diff_y*diff_y)
if diff_length < cc_r:
# new point is within circumcircle
bad_triangles.append(tri)
# TODO: should store cc center for Voronoi
vor_node = Node(int(cc_x),int(cc_y))
vor_node.data = {"center_node": node}
voronoi_data[tri] = vor_node
polygon = []
for tri1 in bad_triangles:
# find bounding edges of polygonal hole
# around new point
for edge in tri1.nextEdge():
shared = False
for tri2 in bad_triangles:
if tri1 == tri2:
continue
if tri2.checkEdge(edge):
shared = True
if not shared:
polygon.append(edge)
for tri in bad_triangles:
# remove invalidated triangles
triangulation.remove(tri)
for edge in polygon:
# re-triangulate the polygonal hole
newTri = Triangle()
newTri.setA(edge.n1())
newTri.setB(edge.n2())
newTri.setC(node)
triangulation.append(newTri)
for tri in triangulation:
# create return edge package,
# except edges connected to big helper triangle
if tri.checkNode(super_triangle.getA()) or \
tri.checkNode(super_triangle.getB()) or \
tri.checkNode(super_triangle.getC()):
continue
delaunay_result.append(tri.getAB())
delaunay_result.append(tri.getBC())
delaunay_result.append(tri.getCA())
# create voronoi
A = (tri.getA().x(),tri.getA().y())
B = (tri.getB().x(),tri.getB().y())
C = (tri.getC().x(),tri.getC().y())
# get circumcircle center and radius
cc_x, cc_y, cc_r = self.calcCircleMidpoint(A,B,C)
voronoi_node = Node(int(cc_x),int(cc_y))
voronoi_node.data = {"sites":{tri.getA(),tri.getB(),tri.getC()}}
voronoi_result.append(voronoi_node)
voronoi_result = list(set(voronoi_result))
delaunay_result = list(set(delaunay_result))
return delaunay_result, voronoi_result
def generate_circlecheck(self, nodes: list[Node]) -> list[Edge]:
# a brute force version
# generate edges:
# iterate through list of nodes and generates the circles (midpoints)
# checks if there are any other node inside the circle
# if not the circle is valid and the nodes should be connected
# generate nodes:
# iterate through list of nodes and generates the circles
# ...
pass
def calcCircleMidpoint(self, point1: tuple, point2: tuple, point3: tuple) -> tuple:
'''
Gives the midpoint and radius of a circle that passing through 3 points.
- first calculates two midpoints (M1,M2),
- then with the bisector lines' equations on these points
- L1 line perpendicular to P2-P1 line and intersects M1:
L1 = M1 + T[0] * V1
- L2 line perpendicular to P3-P1 line and intersects M2:
L2 = M2 + T[1] * V2
- it calculates the intersection of these lines which give us a variable (T)
- inserting this (T) variable in one of the line equations
it gives the circle's midpoint
Args:
point1 ([type]): first point on circle's circumference
point2 ([type]): second point on circle's circumference
point3 ([type]): third point on circle's circumference
Return:
circle's midpoint x, y and radius
'''
# rotation matrix
theta = np.radians(90)
rot = np.array([(np.cos(theta), -np.sin(theta)),(np.sin(theta), np.cos(theta))])
P1 = np.array(point1)
P2 = np.array(point2)
P3 = np.array(point3)
# M1 midpoint between P2 and P1
M1 = P1 + (P2 - P1)/2
# V1
V1 = ((P2 - P1) @ rot)
# M2 midpoint between P3 and P1
M2 = P1 + (P3 - P1)/2
# V2
V2 = ((P3 - P1) @ rot)
# solve(L1 = L2) -> midpointC
T = np.linalg.solve(np.array([(V1[0],-V2[0]),(V1[1],-V2[1])]),
np.array([(M2[0]-M1[0]),(M2[1]-M1[1])]))
# with T this gives us the intersection point of L1 and L2
L2 = M2 + T[1] * V2
# circles radius
radius = np.linalg.norm([L2-P1])
return L2[0],L2[1],radius
if __name__ == "__main__":
triang = Delaunay()
res = triang.calcCircleMidpoint((1,2), (4,2), (2,4))
print(f"circumcircle method: {res}")
res = triang.generate([Node(1,2),Node(2,2),Node(5,5),Node(4,8)])
print(f"delaunay edges: {res}")
tri = Triangle()
print(tri)
tri.addNode(Node(1,1))
print(tri)
tri.addNode(Node(2,2))
print(tri)
tri.addNode(Node(3,2))
print(tri)
tri.addNode(Node(4,2))
print(tri)
tri.setB(Node(5,1))
print(tri) |
06415239b46083595089cc2d8d285b535f00e39f | RifasM/Python-Lab | /1st Cycle Experiments/Program11.py | 304 | 4.15625 | 4 | """
Write a program to compare two numbers without using relational operator
"""
a, b = map(int, input("Enter two numbers: ").split())
if not a ^ b == 0:
print("Not equal")
else:
print("Equal")
"""
OUTPUT
Enter two numbers: 3 52
Not equal
Enter two numbers: 50 50
Equal
""" |
d77bc91ff9be04185bc84499636ed6e423cd3e97 | knpatil/learning-python | /src/bank_account.py | 951 | 3.734375 | 4 | class BankAccount:
def __init__(self, name):
self.name = name
self.balance = 0.00
self.transaction_fee = 0.00
def deposit(self, amount):
if amount > 0:
self.balance += amount
def withdraw(self, amount, transaction_fee=0.00):
if transaction_fee < 0:
self.transaction_fee = 0.00
if transaction_fee > 0: # not negative
self.transaction_fee = transaction_fee
amt_to_withdraw = amount + self.transaction_fee
if amt_to_withdraw < 0:
return
if amt_to_withdraw > self.balance:
return
self.balance = self.balance - amt_to_withdraw
ba = BankAccount("abc")
ba.deposit(40)
print("balance=", ba.balance)
ba.withdraw(10)
print("balance=", ba.balance)
ba.withdraw(10,0.5)
print("balance=", ba.balance)
ba.withdraw(10,1.5)
print("balance=", ba.balance)
ba.withdraw(4,-1.5)
print("balance=", ba.balance) |
0c4d0cf9b68c22a0a5ea739f7812e21f0841b3fa | prnanda/python | /CodeAcademy/Reverse_String.py | 305 | 4.15625 | 4 | def reverse(input):
reversed = ""
i = len(input)-1
while i >=0:
reversed = reversed + input[i]
i-=1
return reversed
choice = "y"
while choice == "y":
input1 = raw_input("Please enter a string: ")
input1 = str(input1)
print reverse(input1)
choice = raw_input("Continue?") |
bfc9e0b68dd518ee4bd6006d26121d62f30efb1b | congyingTech/Basic-Algorithm | /old-leetcode/older/SumofTwoIntegers371.py | 766 | 3.515625 | 4 | class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
MASK = 0x100000000
#max_int是long int的最大值
MAX_INT = 0x7FFFFFFF
def add(a,b):
if b==0:
return a
#1.获得个位数的值
num1 = (a^b) % MASK
#2.获得进位值,按位与只有1&1时,才为1,然后左移一位,可以获得进位
num2 = ((a&b)<<1) % MASK
return self.getSum(num1, num2)
res = add(a,b)
if res <= MAX_INT:return res
else:return res | (~MASK+1)
if __name__ == "__main__":
s = Solution()
print(s.getSum(-3,-6)) |
edd4bba64ee5e7849db135b0353468ff68f1a755 | Sreeram225/internsearch | /doublelinkedlist.py | 1,112 | 4 | 4 | class Node:
def __init__(Node, data):
Node.data = data
Node.next = None
Node.prev = None
def insertNodestart(head, newNode):
newNode.next = head
head.prev = newNode
newNode.prev=None
head=newNode
return head
def insertmiddle(head, newNode):
temp = head
while (temp.data != 'c'):
temp = temp.next
duplicate= temp.next
temp.next = newNode
newNode.prev = temp
newNode.next = duplicate
duplicate.prev = newNode
return head
def insertend(head, newNode):
temp = head
while (temp.next != None):
temp = temp.next
temp.next = newNode
newNode.prev = temp
newNode.next = None
return head
def printList(head):
temp = head
while (temp):
print(temp.data)
temp = temp.next
head = Node('a')
nodeB = Node('b')
nodeC = Node('c')
nodeD = Node('d')
head.next = nodeB
nodeB.next = nodeC
nodeC.next = nodeD
nodeB.prev=head
nodeC.prev=nodeB
nodeD.prev=nodeC
head=insertNodestart(head,Node("E"))
#head=insertmiddle(head,Node("E"))
#head = insertend(head, Node("E"))
printList(head)
|
d8c78922fe0316d16ca2c7dce5a39ba901e71ac6 | mike-peterson04/dataStructures | /linkedlist.py | 922 | 4.09375 | 4 | from node import Node
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def append_node(self, data):
node = Node(data)
if self.head is None:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def prepend_node(self, data):
node = Node(data)
if self.head is None:
self.head = node
self.tail = node
else:
node.next = self.head
self.head = node
def contains (self, data):
if self.head is None:
print("linked list is currently empty")
else:
temp = self.head
while temp.data != data:
if temp.next is not None:
temp = temp.next
else:
return False
return True
|
e934414e4bae0e27a3347af8808e30d60cb60ca0 | Dharani379/BEST-ENLIST-Internship | /functions.py | 658 | 4.09375 | 4 | #Creating a function for getting input from userand doing folloeing atmatic operations
a= int(input("Enter the value:"))
b= int(input("Enter the value:"))
import math
def Dharani(a,b):
c=a+b
d=a-b
x=a*b
y=a/b
return c,d,x,y
print(Dharani(a,b))
#Creating a function covid()'''2nd task'''
def covid(patient_name,body_temparature):
if body_temparature<str(0):
default = str(98)
print("Patient name is:",patient_name,"Body temparature is:",default)
else:
print("Patient name is:",patient_name,"Body temparature is:",body_temparature)
covid("Mahanati","")
covid("Mahanati","99")
|
9d4beef6220fa029242f81f2d6b2eec8e68890b0 | AbdallahHemdan/Python-Solutions | /Basic Data Types/Lists.py | 516 | 3.765625 | 4 | if __name__ == '__main__':
N =int(input())
l = []
for i in range(0,N):
t = input().split()
if t[0]=="insert" :
l.insert(int(t[1]),int(t[2]))
elif t[0]=="print":
print (l)
elif t[0]=="remove" :
l.remove(int(t[1]))
elif t[0]=="append" :
l.append(int(t[1]))
elif t[0]=="sort" :
l.sort()
elif t[0]=="pop" :
l.pop()
elif t[0]=="reverse" :
l.reverse()
|
54cdd75d750d2aad61b3cdc07aede2145f6938d7 | nsid10/Project-euler | /problems/046.py | 567 | 3.984375 | 4 | def primality(n):
if type(n) != int:
raise TypeError("argument must be of type 'int'")
if n == 2:
return True
if n < 2 or n % 2 == 0:
return False
for i in range(3, int(n**0.5 + 1), 2):
if n % i == 0:
return False
return True
def gold(n):
for i in range(1, int((n / 2)**0.5) + 1):
if primality(n - 2 * (i**2)):
return True
return False
i = 1
while True:
i += 2
if primality(i):
continue
elif gold(i):
continue
else:
break
print(i)
|
5a588dc31c921258087cb172fc9d66f3733215df | Smitharry/HackerrankTasks | /src/AngryProfessorSolution.py | 703 | 3.84375 | 4 | def is_professor_angry(threshold, arrival_times) :
'''Print if class is cancelled.'''
if count_arrival_on_time(arrival_times) < threshold :
print('YES')
else :
print('NO')
def count_arrival_on_time(arrival_times):
'''Count number of students who arrived on time'''
students_on_time = list(filter(lambda time : time <= 0, arrival_times))
return len(students_on_time)
if __name__ == '__main__':
number_of_cases = int(input())
for case in range(number_of_cases):
case_info = input().split()
threshold = int(case_info[1])
arrival_times = list(map(int, input().rstrip().split()))
is_professor_angry(threshold, arrival_times)
|
51018b88511838475ff3fbbd47b0249ced3e6516 | DiogenesGois/Estudos-de-Python | /Aprendendo_Python/3Loops/Ex6Maior.py | 186 | 4.15625 | 4 | # maior dos 5 numeros
maior = 0
for i in range(5):
numero = int(input("Insira um numero\n"))
if numero > maior:
maior = numero
print("O maior numero foi: ", maior) |
81242b6c3011333a94e2568540fdcf6ad9739d7c | ngothuyhoa/Python_Exercises | /Exercise_1/exercise2.py | 238 | 4.1875 | 4 | celsius = input('Enter Celsius is Digit: ')
while (celsius.isalpha() or celsius == ''):
celsius = input('Wrong!! Please enter celsius is digit: ')
fahrenheit = (float(celsius)*9)/5 +32
print('{}C = {}F'.format(celsius, fahrenheit)) |
9625ab768c1d0140920804d643a116fc17023201 | thedatazen/DataEngineering | /2-Algo & Sys Design/4-LC/344 Reverse String.py | 1,053 | 4.46875 | 4 | '''
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
'''
'''
It is very tempting in Python just to use reverse() function, but I think it is not fully honest solution.
Instead, we go from the start and the end of the string and swap pair of elements. One thing, that we need to do is to stop at the middle of our string. We can see this as simplified version of two points approach, because each step we increase one of them and decrease another.
Complexity: Time complexity is O(n) and additional space is O(1).
'''
class Solution:
def reverseString(self, s):
for i in range(len(s)//2): s[i], s[-i-1] = s[-i-1], s[i]
|
adc84918a1c7758382c83a906ed9ec7ac33f69bf | luzap/mt | /tournament/utils.py | 285 | 3.578125 | 4 | import random
def gen_code(name):
"""Generates a code for the school based upon initials and a random number, to avoid any potential cheating."""
words = name.split(" ")
code = "".join([word[0:1].upper() for word in words]) + str(random.randint(1, 571))
return code
|
6e4ae1ac72d902bf48aac52019942e701ceca5f5 | habibor144369/python-all-data-structure | /list-pop.py | 180 | 3.703125 | 4 | # pop in list---
list = ['Mango', 'Banana', 'Orange','Avocado', 'Apple', 'Pineapple', 'Peach', 'Melon',]
item = list.pop()
item2 = list.pop(2)
print(item)
print(item2)
print(list)
|
e7fa698b4767519971cb2d2b0c094e6123fdb5ff | TusharDimri/Python | /OOPS 4.py | 3,131 | 4.125 | 4 | # Class Methods inn Python
class Fender:
instruments_no = 1
def __init__(self, argument_name , argument_role, argument_net):
self.name = argument_name
self.role = argument_role
self.net = argument_net
def help(self):
return f"Name is {self.name},role is {self.role} & net worth is {self.net} million$"
@classmethod # This is a Decorator
def changeinstrno(cls, newno):
# The purpose of this class method is to change value of class variable but it can be used for many other tasks
cls.instruments_no = newno # The argument cls takes class as an argument (like self, which takes an object)
kurt = Fender("Kurt Cobain", "Singer & Guitarist", 200)
clap = Fender("Eric Clapton", "Singer & Guitarist", 300)
print(Fender.instruments_no)
Fender.changeinstrno(2) # Changing the class variable using class
print(Fender.instruments_no)
print(kurt.instruments_no)
kurt.changeinstrno(3) # Changing class variable using an Object
print(kurt.instruments_no)
# NOTE:- We can changed class variable using an object with the help of the class method we defined earlier
# Class Methods as alternative Constructors:-
class Fender:
instruments_no = 1
def __init__(self, argument_name, argument_role, argument_net):
self.name = argument_name
self.role = argument_role
self.net = argument_net
def help(self):
return f"Name is {self.name},role is {self.role} & net worth is {self.net} million$"
@classmethod
def from_str(cls, string):
# fruscinte = string.split(",")
# return cls(fruscinte[0],(fruscinte[1]),(fruscinte[2])) [this returns te line:- Fender(frusciante[0], frusciante[1], frusciante[2]) ]
# shortcut for above 2 lines of code
return cls(*string.split(",")) # *string returns a tuple/arg(checks args and kwargs)
kurt = Fender("Kurt Cobain", "Singer & Guitarist", 200)
clap = Fender("Eric Clapton", "Singer & Guitarist", 300)
frus = Fender.from_str("John Frusciante,Guitarist,8")
"""
previous three lines of code create three different instances(kurt, clap and frus).Respectively,first two instances are
created using method __init__ but the instance "frus" is created using classs method from "_str"
"""
print(Fender.help(frus))
"""
NOTE:-
1. Normal methods in Python OOPS like 'help' and '__init__' method are methods which have self(instance of the class) as
the default argument. They are mostly used in cases where we need to modify or use the objects of the class
2. Class methods in Python OOPS like from_str are methods which use cls(class) as the default argument.They are used when
we directly want to use our class inside the class. GThey can be used as alternative constructors where they are named
conventionally as 'from_---' where '---' is the format from which they are parsed.
3. Static methods in Python OOPS like print_str (OOPS 5) are methods which take neither self(instances of class) and cls
(class itself) as an argument but are logically related to the class
Now it is up to us to use these 3 different methods of class when needed and appropriately.
""" |
5c57174a12d23cabd7ee2502edf5847490bb4454 | zedudedaniel/IntroProgramming-Labs | /lab04/guessing_game.py | 657 | 3.96875 | 4 | #Have the user guess the animal
#Keep repeating until they get it correct
def main():
animal = "tardigrade"
while (True):
guess = input("Guess the animal! ").lower()
if (guess[0] == "q"):
print("Seeya!")
break
elif (guess == animal):
print("Correct!")
likeanimal = input("Do you like them? y/n ").lower()
if (likeanimal == "y"):
print("I see you are a man of culture as well.")
else:
print("Thomas has never seen such bullshit before.")
break
else:
print("Incorrect! Try again.")
main()
|
a7b0cc430144db3e44123ac267768bd54e5b317c | maxlauhi/webapps | /coroutine.py | 1,075 | 3.859375 | 4 | #!/usr/bin/python
#coding:utf-8
'''生产一个跳到消费者手上,给消费者消费,
消费完后把消息告诉生产者,生产者接收到消费者消费完的消息,打印出来后继续生产
问题:要把生产者生产和消费者消费两个子程序放在一个线程里,用协程的方式执行。
'''
import time
# 消费者
def consumer():
r = ''
while True:
n = yield r
# 如果N=0就代表没有生产,也就没有消费返回空值就可以
if not n:
return
# 打印正在消费第几个的消息
print ('[CONSUMER] Consuming %s...' % n)
# 要1s的时间来消费, 并保存消费完成的消息
time.sleep(1)
r = '200 OK'
# 生产者
def produce(c):
c.next()
n = 0
while n < 5:
n = n + 1 # 生产下一个
print ('[PRODUCER] Producing %s...' % n)
# 把生产完第几个的消息告诉消费者,并接收消费情况
r = c.send(n)
# 接收销售情况的消息,并打印出来
print ('[PRODUCER] Consumer return: %s' % r)
c.close()
if __name__=='__main__':
c = consumer()
produce(c) |
3628946e406d89b414ae4b4b03235236356e16a3 | nmeripo/Data-Structures-and-Algorithms | /LeetCode/Sorting And Searching/Merge_k_Sorted_Linked_Lists.py | 1,068 | 4.03125 | 4 | # Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from heapq import *
ListNode.__lt__ = lambda self, n2: self.val < n2.val
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
# Time Complexity : O (n * log k)
heads = [head for head in lists if head]
heapify(heads)
result = None
cur_node = None
while heads:
min_node = heappop(heads)
if not result:
result = cur_node = ListNode(min_node.val)
else:
cur_node.next = ListNode(min_node.val)
cur_node = cur_node.next
if min_node.next:
heappush(heads, min_node.next)
return result
|
bcfcf23d95bf6cbbf484f149efd65959179ea56b | JDPowell648/Code | /Intro to Computing/planner.py | 5,644 | 3.9375 | 4 | '''
Author: Joshua Powell
File: planner.py
Description: A by-the-hour planner for daily and weekly use
'''
from random import randint
def makeList(inputList):
for index in range(0,24):
inputList.append([index, "unscheduled", False])
return inputList
class planner():
def __init__(self):
self.weekDict = {"monday":makeList([]),"tuesday":makeList([]),"wednesday":makeList([]),"thursday":makeList([]),"friday":makeList([]),"saturday":makeList([]),"sunday":makeList([])}
def schedule(self):
event = str(input("What are you scheduling? (enter anything) "))
day = str(input("What day would you like to schedule this event? ")).lower()
while day not in ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]:
day = str(input("Please enter a valid day: ")).lower()
self.check(day)
time = int(input("What time is this event? (24 hour clock, input an integer 0-23) "))
while time not in range(0,24):
time = int(input("Please enter a valid time (24 hour clock, input an integer 0-23) "))
length = int(input("How many hours long is this event? "))
while time + length > 24:
print("This event is longer than your day! Please try again. ")
length = int(input("How many hours is this event? "))
if self.weekDict[day][time][2] == False:
if day in self.weekDict:
self.weekDict[day][time][1] = event
self.weekDict[day][time][2] = True
if length > 1:
for index in range(0,length):
if self.weekDict[day][time + index][2] == False:
self.weekDict[day][time + index][1] = event
self.weekDict[day][time + index][2] = True
print("The event has been successfully scheduled\n")
else:
print("Time time is already scheduled with:", self.weekDict[day][time][1])
def unschedule(self):
day = str(input("What day are you unscheduling on? ")).lower()
while day not in ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]:
day = str(input("Please enter a valid day: ")).lower()
self.check(day)
hour = int(input("What hour would you like to unschedule? (24 hour clock, input an integer 0-23) "))
while hour not in range(0,24):
hour = int(input("Please enter a valid time (24 hour clock, input an integer 0-23) "))
self.weekDict[day][hour][1] = "unscheduled"
self.weekDict[day][hour][2] = False
print("The event has been successfully unscheduled\n")
def check(self,day):
print(str(day), "looks like:")
for index in range(0,24):
hour = [str(index) + ":00", self.weekDict[day][index][1]]
print(hour)
def weekCheck(self):
print("Your week looks like:")
for index in range(0,24):
hour = [str(self.weekDict["saturday"][index][1]),str(self.weekDict["monday"][index][1]),
str(self.weekDict["tuesday"][index][1]), str(self.weekDict["wednesday"][index][1]),
str(self.weekDict["thursday"][index][1]), str(self.weekDict["friday"][index][1]),str(self.weekDict["sunday"][index][1])]
print(hour)
def tip(self):
tipList = ["Write down long term goals to keep direction in life!","Write down short term goals to keep direction in working hours!","Remember to relax! 8 hours of sleep every day is ideal.",
"Delegate easier tasks to other people to avoid time wasting!","Do harder work during the most productive times of the day!","Time management is the best way to reduce stress.",
"Time management raises the quality of life.","People tend to wrongly assume how long a task will take, and usually don't recall management failures.","Procrastination is a form of stress management, but\nTime Management lowers stress to a higher degree.",
"Time management originated in the industrial revolution.","Keep a to-do list!","Make sure to watch your schedule!","Don't waste time!","Time management lowers stress to a higher degree than leisure activities."]
int = randint(0,len(tipList) - 1)
print("\nTip: " + tipList[int] + "\n")
def __str__(self):
return str(self.weekDict)
plan = planner()
print("This program is a by-the-hour planner for the week!\n\nEnter a command in the console below to get started.\n\nUnique instructions will be given when a command is executed to\nguide you through the process.\n")
while True:
userInput = str(input("Commands: \ns = schedule an event!\nu = unschedule an event!\nd = check a day's schedule\nw = check the week's schedule\nt = Get a time management tip!\nx = quit \n\nWhat would you like to do? "))
if userInput == "s":
plan.schedule()
elif userInput == "u":
plan.unschedule()
elif userInput == "d":
day = str(input("What day are you checking? ")).lower()
while day not in ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]:
day = str(input("Please enter a valid day: ")).lower()
plan.check(day)
elif userInput == "w":
print("Each column is a day of the week, Sunday-Saturday")
plan.weekCheck()
elif userInput == "t":
plan.tip()
elif userInput == "x":
break
else:
print("That is not a valid command!\n")
|
4821ff6c1538a35235010ed53729f71044dd9ceb | kks4866/pyworks | /exercise/test02.py | 1,220 | 3.75 | 4 | # 1번문제
국어 = 80
영어 = 75
수학 = 55
sum = 국어+영어+수학
Average = sum/3
print("평균 점수 : ", Average)
#2번문제
num = 13
print(13%2)
n=13
if n%2==0:
print("짝수")
else:
print("홀수")
#3번문제
pin = "881120-1068234"
yyyymmdd = pin[0:6]
num = pin[7:]
print(yyyymmdd)
print(num)
#4번문제
pin ="881120-2068234"
gender = pin[7]
print(gender)
if gender == "1":
print("남자입니다")
else:
print("여자입니다")
#5번 문제
a = "a:b:c:d"
b = a.replace(':','#')
print(b)
#6번 문제
a = [1,3,5,4,2]
a.sort()
a.reverse()
print(a)
#7번 문제
a = ['Life','is','too','short']
result = " ".join(a)
print(result)
#split() 예제
msg='Life is too short'
msg = msg.split() #구분기호 : 공백
print(msg)
s ="a:b:c"
s = s.split(':')
print(s)
#8번 문제
a = (1,2,3)
a = a +(4,)
print(a)
#9번 문제
a= dict()
print(a)
a['name']='python'
print(a)
a[('a')]='python'
#print(a)
#a[[1]]='python'
print(a)
a[250]='python'
print(a)
#10번 문제
a={'A':90,'B':80,'C':70}
result=a.pop('B') #추출
print(a)
print(result)
#11번 문제
a=[1,1,1,2,2,3,3,3,4,4,5]
aSet= set(a)
b= list(aSet)
print(b)
#12번 문제
a=b=[1,2,3]
a[1]=4
print(b)
|
f36d48d011af9f55ff819fe5287e9b9ba019aaba | chenhuang/leetcode | /minDistance.py | 2,157 | 3.890625 | 4 | #! /usr/bin/env python
'''
Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
https://oj.leetcode.com/problems/edit-distance/
'''
class Solution:
# @return an integer
# DP problem:
# word1 -> word2,
# if i != j:
# steps[i][j] = min(steps[i-1][j] + 1 delete,
# steps[i][j-1] + 1 insert,
# steps[i-1][j-1] + 1 replace)
def minDistance_1(self, word1, word2):
steps = []
length = max(len(word1),len(word2))
steps = [[] for i in range(length)]
if word1[0] == word2[0]:
steps[0][0] = 0
else:
steps[0][0] = 1
for i in range(1,len(word2)):
steps[0].append(steps[0][i-1]+1)
for i in range(1,len(word1)):
steps[i].append(i)
for i in range(1,length):
steps[i].append(i) #Deletion
steps[0].append(i) #Insertion
for i in range(1, len(word1)):
for j in range(1, len(word2)):
if word1[i] == word2[j]:
steps[i].append(steps[i-1][j-1])
else:
steps[i].append(min(steps[i-1][j]+1, steps[i][j-1]+1, steps[i-1][j-1]+1))
print steps
return steps[len(word1)-1][len(word2)-1]
def minDistance(self, word1, word2):
distance = [[i] for i in range(len(word1)+1)]
distance[0] = [i for i in range(len(word2)+1)]
for i in range(1, len(word1)+1):
for j in range(1, len(word2)+1):
deletion = distance[i-1][j]+1
addition = distance[i][j-1]+1
substitution = distance[i-1][j-1]
if word1[i-1] != word2[j-1]:
substitution += 1
distance[i].append(min(deletion, addition, substitution))
return distance[-1][-1]
if __name__ == "__main__":
s = Solution()
print s.minDistance("acd","abcd")
|
1d8ede60bf87c32854abd0e7eacb816ff62ef617 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/318/decode.py | 514 | 3.59375 | 4 | import base64
import csv
from typing import List # will remove with 3.9
def get_credit_cards(data: bytes) -> List[str]:
"""Decode the base64 encoded data which gives you a csv
of "first_name,last_name,credit_card", from which you have
to extract the credit card numbers.
"""
temp_list = []
for each_name in base64.standard_b64decode(data).splitlines():
cc = each_name.decode('utf-8').split(',')[2]
if cc.isnumeric():
temp_list.append(cc)
return temp_list
|
3ec4aaab7ed5932237eea35205b80555323048e2 | Vozsco/DLA | /randomAtRadius.py | 528 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 8 17:24:56 2020
@author: User
"""
"""
Function that generates the random pos, at the specified Radius
INPUT = Radius, Xseed, Yseed
OUTPUT = [x,y] pos
"""
import random
import numpy as np
def randomAtRadius(Radius, Xseed, Yseed):
theta = 2*np.pi*random.random() #generate random theta
x=int(Radius*np.cos(theta))+Xseed #use trig to transfer into X
y=int(Radius*np.sin(theta))+Yseed #find Y coordinate
pos=[x, y] #save locaction
return pos |
94c12d886508919eb1c1c8b5b1e8ddf9eec44fd7 | agforero/SI-PLANNING | /Plans/CSCI121S2AGF-2.27.py | 1,664 | 4.3125 | 4 | '''
- Testing code?
- If one thing causes an error in one place, it'll cause errors everywhere.
- Make a Python function to find the max in a list. Generate the list using
import random
ls = []
for i in range(10):
ls.append(random.randint(1,10))
Define it findMax(). What argument(s) will you need?
- Do the same thing, but find the minimum instead.
- Write a function that checks if a number is prime. Plan out for a bit how
you'd do this, either by writing out an approach on the board or by talking
it over with me or a partner.
- Write a function to flip the sign of an integer. If the input is -9, have the
function return 9 instead.
- Write a function to print out all Fibonacci numbers up to argument n.
'''
import random
ls = []
for i in range(10):
ls.append(random.randint(1,25))
print(ls)
def findMax(ls):
max = 0
for i in ls:
if i > max:
max = i
return max
def findPrime(n):
for i in range(2,10):
x = n % i
if x == 0 and not x == i:
return False
else:
return True
def findPrime2(n):
x = 2
for i in range(n-2):
if n % x == 0:
return False
return True
def fib(n):
x = 1
y = 1
sum = 0
while (sum < n):
sum = x + y
x = y
y = sum
return sum
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
def main():
print("Maximum:" , findMax(ls))
print("29 is prime????? ", findPrime(29))
print("123 is prime????? ", findPrime2(123))
print("fib(200): ", fib(200))
print(fact(10))
main() |
0c49e3bf2d1cb32853b34faacee2fd0c857b55fd | Critisys/Simple-fashion-classification-with-mnist | /main.py | 1,541 | 3.765625 | 4 | import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
# we load images data from mnist
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# CHange data to the correct format
train_images = train_images / 255.0
test_images = test_images / 255.0
num_classes = 10
train_labels = keras.utils.to_categorical(train_labels, num_classes)
test_labels = keras.utils.to_categorical(test_labels, num_classes)
# Our model for classification
model = keras.Sequential([
keras.layers.Flatten(input_shape = (28,28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(num_classes,activation = 'softmax')
])
model.compile(loss=tf.keras.losses.categorical_crossentropy,optimizer = keras.optimizers.SGD(lr= 0.3),metrics=['accuracy'])
#We dont want to add more layer because it will cause our model to overfit
model.fit(train_images,train_labels,epochs = 20)
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
predictions = model.predict(test_images)
plt.figure()
plt.imshow(train_images[1])
plt.colorbar()
plt.grid(False)
plt.show()
print("Our prediction for the second image is " + class_names[np.argmax(predictions[1])])
|
fa8ebc9816975b98c0e09bc9f06de3ee881aa89d | abbasmalik514/30_Days_Coding_Challenge_HackerRank | /Day_01_Data_Types/Day1_script.py | 545 | 3.78125 | 4 | i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.
int_num = 0
double_num = 0.0
string = ''
# Read and save an integer, double, and String to your variables.
int_num = int(input())
double_num = float(input())
string = str(input())
# Print the sum of both integer variables on a new line.
print(i+int_num)
# Print the sum of the double variables on a new line.
print(d+double_num)
# Concatenate and print the String variables on a new line
# The 's' variable above should be printed first.
print(s+string)
|
917bad5bb0ceccbc4c5c7c9c46421b83d4a59d4f | nikonoff16/learn2code | /KGU - Basic Python/viel_21.py | 1,099 | 3.59375 | 4 | # countries = {'Russia', 'China', 'Korea'}
# Autos = {
# 'Toyota':{'Russia', 'Korea'},
# 'Toyamatokanava': set(),
# 'Mazda': {'Russia', 'China', 'Korea'}
# }
count = int(input('Какое количество автомобильных марок вы собираетесь внести: '))
countries = set()
autos = {}
while count != 0:
auto_seria = input('Введите имя марки: ')
auto_import = input('Введите страны экспорта через пробел: ')
if auto_import == '':
autos[auto_seria] = set()
else:
autos[auto_seria] = set(auto_import.split(' '))
countries = countries.union(autos[auto_seria])
count -= 1
# print(countries, autos)
for mark in autos:
if not autos[mark]:
print(mark, 'не поставляется никуда')
elif autos[mark] == countries:
print(mark, 'поставляется во все страны')
else:
where_imp = countries.intersection(autos[mark])
print(mark, 'поставляется в', ', '.join(list(where_imp)))
|
9e15b81b015e9bd5c7328128b7a6738612d82849 | hubinyes/python | /matplot/matplot.py | 409 | 3.65625 | 4 | import matplotlib.pyplot as plt
x_values = list(range(1,100))
y_values = [x**2 for x in x_values]
#plt.plot(xvalues,yvalues,linewidth=5)
plt.title("hello plt",fontsize=25)
plt.xlabel("value")
plt.ylabel("square")
plt.tick_params(axis='both',labelsize=15)
#plt.axis([0,110,0,1100])
plt.scatter(x_values,y_values,s=50,edgecolors='none',c=y_values,cmap=plt.get_cmap('Blues'))
plt.savefig("plot.png")
plt.show() |
7b2b6c4d09e15c38f8f094b4ca493165a784a272 | loganyu/leetcode | /problems/670_maximum_swap.py | 896 | 4.09375 | 4 | '''
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
Example 1:
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973
Output: 9973
Explanation: No swap.
Note:
The given number is in the range [0, 108]
'''
class Solution:
def maximumSwap(self, num: int) -> int:
digits = list(map(int, str(num)))
max_ = digits[-1]
l = -1
r = max_i = len(digits) - 1
for i in reversed(range(len(digits) - 1)):
if digits[i] > max_:
max_ = digits[i]
max_i = i
elif digits[i] < max_:
l = i
r = max_i
if l != -1:
digits[l], digits[r] = digits[r], digits[l]
return int("".join(map(str, digits)))
|
4c1f4575e4434992b064e77bf123cc5d99f0116d | cicily-qq/pythontraining | /tongxun.py | 1,362 | 3.84375 | 4 | print('|---欢迎进入通讯录程序---')
print('|---1:查询联系人资料-')
print('|---2:插入新的联系人---')
print('|---3:删除已有联系人---')
print('|---4:退出通讯录程序---')
contacts=dict()
while 1:
instr=int(input('\n请输入相关的指令代码:'))
if instr==1:
name=input('请输入联系人姓名:')
if name in contacts:
print(name+':'+contacts[name])
else:
print('您输入的姓名不在通讯录中')
if instr==2:
name=input('请输入联系人姓名:')
if name in contacts:
print('您输入的名字在通讯录中已存在-->', end='')
print(name+':'+contacts[name])
if input('是否修改用户资料(yes/no):')=='yes':
contacts[name]=input('请输入用户联系电话:')
else:
print('联系人不存在,请添加用户电话')
contacts[name]=input('请输入用户联系电话:')
if instr==3:
name=input('请输入联系人姓名:')
if name in contacts:
del(contacts[name])
else:
print('您输入的联系方式不存在')
if instr==4:
break
print('|---感谢使用通讯录程序---|')
|
d2a6f5373317373046e0cb12959f2e18c950bc9f | emir-naiz/classes | /class Planets.py | 1,070 | 3.96875 | 4 | class Planet:
def __init__(self, name, size, color):
self.name = name
self.size = size
self.color = color
self.temp = -999
self.oxygen = False
self.water = False
self.humanity = False
def description(self):
print(f"Название планеты - {self.name}, размер - {self.size}, цвет - {self.color}, Температура = {self.temp}. "
f"Наличие воздуха - {self.oxygen}, воды = {self.water}, человечества - {self.humanity}")
def set_humanity(self):
self.humanity = True
self.oxygen = True
self.water = True
self.temp = 15
def population(self, people):
if self.humanity and self.water and self.oxygen:
if people > 0:
self.humanity = people
else:
print('Не балуйся!')
else:
print('Жизни нет!')
earth = Planet('Earth', 20, 'Blue')
earth.set_humanity()
earth.population(2)
earth.description()
|
aad2330f3cdb9def7795a78c7c2ab8e73df9f717 | Pickerup-Yirui/ourSpider | /urlPool.py | 1,297 | 3.921875 | 4 | """
author = "YiRui Wang"
定义了一个储存url的仓库类
创建于2020 1 13
"""
class urlPool():
"""
一个储存url的仓库类
pressIn(self, url):压入一个url,返回1
popOut(self,):弹出一个url,返回该url或-1
howMany(self,):返回当前url的数量
"""
def __init__(self,):
"""
建立一个内置队列,储存url,并初始化为空
"""
self.queue = []
def pressIn(self, url):
"""
将一个url压入,成功则返回1
params:
url:待压入的url
"""
self.queue.append(url)
#print(self.queue)
return 1
def popOut(self,):
"""
将一个url弹出,成功则返回url,若队列为空返回-1
"""
#print(self.queue)
if len(self.queue) != 0:
#print(self.queue)
#print("going to pop")
return self.queue.pop(0)
#print(self.queue)
else:
return -1
def howMany(self,):
"""
查询队列中还有多少url,返回url数量
"""
return len(self.queue)
if __name__ == "__main__":
testPool = urlPool()
print(testPool.pressIn(10))
print(testPool.popOut())
print(testPool.howMany())
|
4b541a439b691fc89ed1ee6f3c9be5bfaa628fee | Mdwsbb01/Pyhton4E | /py4e_ex_chapter6.py | 416 | 4.40625 | 4 | #Exercise 5: Take the following Python code that stores a string:
# str = 'X-DSPAM-Confidence: 0.8475 '
# Use find and string slicing to extract the portion of the string
# after the colon character and then use the float function
# to convert the extracted string into a floating point number.
data = 'X-DSPAM-Confidence: 0.8475 '
sp1 = data.find(' ') # first space
# print(sp1)
num = float(data[sp1:])
print(num) |
94c597099d584f82b578849cb93d4fdb90148d91 | MystWalker/Fey | /Character.py | 4,097 | 3.765625 | 4 | #Define character by stats
import pygame
from pygame.locals import *
DEBUG = False
class Character (pygame.sprite.Sprite):
def __init__ ( self, color = [255,0,0], initial_position = [0,0], size = [60, 120]):
"""Returns a Character. Based on python.sprite.Sprite"""
#Sprite
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface(size)
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.midbottom = initial_position
#Movement fields
self.speed = (0,0)
self.right = 0
self.left = 0
#Collision
self.collisions = pygame.sprite.Group()
#Symptom intensities
self.nose = 0
self.headache = 0
self.nausea = 0
#Amount added to symptom every update
# Idealy these slopes would be controled by separate quadratic
# equations that would give each symptom a characteristic rhythm
self.noseSlope = 0.1
self.headSlope = 0.1
self.nauseaSlope= 0.1
#These define the symptom thresholds
# These may become more complex than single numbers. We may use
# several thresholds to simulate different stages of suffering.
self.noseThresh = 1
self.headThresh = 0.5
self.nauseaTresh= 1
def sneeze(self):
"""Performs the sneeze action."""
print("Achoo!")#Game relivant code here
def pound(self):
"""Performs the pound action."""
print("Argh!")#Game relivant code here
def vomit(self):
"""Performs the vomit action."""
print("Hurgle!")#Game relivant code here
def move(self, event):
"""Sets the Character's x-dimentional speed based on passed event."""
if event.type == pygame.KEYDOWN and event.key == K_LEFT:
self.left = -10
elif event.type == pygame.KEYUP and event.key == K_LEFT:
self.left = 0
if event.type == pygame.KEYDOWN and event.key == K_RIGHT:
self.right = 10
elif event.type == pygame.KEYUP and event.key == K_RIGHT:
self.right = 0
self.speed = (self.left + self.right, 0)
if event.type == pygame.KEYDOWN and event.key == K_x:
if(DEBUG):print("X.")
if(self.collisions):
print("Yes, collisions.")
for item in self.collisions:
if(DEBUG):print(str(item))
item.interact()
def update(self):
"""Changes the Character's rect position and symptoms as needed.
This should be called every cycle the Character is active.
"""
#Movement
x, y = self.rect.midbottom
self.rect.move_ip(self.speed)
self.collisions.empty()
""" #Deactivated for now
#Illness
self.nose = self.nose + self.noseSlope
self.headache = self.headache + self.noseSlope
self.nausea = self.nausea + self.nauseaSlope
#These check the different symptom thresholds
if(self.nose >= self.noseThresh):
self.sneeze()
if(self.headache >= self.headThresh):
self.pound()
if(self.nausea >= self.nauseaTresh):
self.vomit()
#"""
#Test Main
if __name__ == '__main__':
john = Character()
while(john.nausea < 1):
print("Nose: " + str(john.nose))
print("Headache: " + str(john.headache))
print("Nausea: " + str(john.nausea) + "\n")
john.update()
print("Oh, this terible cold...\n")
john.noseSlope = john.noseSlope * -1
john.headSlope = john.headSlope * -1
john.nauseaSlope = john.nauseaSlope * -1
while(john.nausea > 0.0):
print("Nose: " + str(john.nose))
print("Headache: " + str(john.headache))
print("Nausea: " + str(john.nausea) + "\n")
john.update()
print("Ah, much better.")
|
bf63d19a83415649c8567a07594dfd1a133839f4 | github653224/GitProjects_PythonLearning | /PythonLearningFiles/麦子学院Python学习笔记/output_and_format.py | 297 | 4.34375 | 4 | str1=input('enter a string :')
str2=input('enter another string:')
print("str1 is "+str1+" and str2 is "+str2)
print('str1 is {} and str2 is {}'.format(str1,str2))
# enter a string :python
# enter another string:python2
# str1 is python and str2 is python2
# str1 is python and str2 is python2
|
e5dbd4b544f9bb05fdf491bf2a0299fa3803c701 | Eitherling/Python_homework1 | /homework_4.3.py | 106 | 3.65625 | 4 | for number in range(1,21):
print(number)
print('-' * 80)
for number in [1,21]:
print(number)
|
457858b9efc04a746716de6f9f1330a913dd8401 | HarkTu/Coding-Education | /SoftUni.bg/Python Advanced/September 2020/03. Find the Eggs.py | 819 | 4.03125 | 4 | from collections import deque
def find_strongest_eggs(sequence, sub):
found = []
sublists = []
for i in range(sub):
sublist = deque()
for x in range(i, len(sequence), sub):
sublist.append(sequence[x])
sublists.append(sublist)
for x in sublists:
mid_ind = len(x) // 2
if x[mid_ind - 1] < x[mid_ind + 1] < x[mid_ind]:
while len(x) > 3:
right = x.pop()
left = x.popleft()
if not right > left:
break
else:
found.append(x[1])
return found
test = ([-1, 7, 3, 15, 2, 12], 2)
print(find_strongest_eggs(*test))
test = ([-1, 0, 2, 5, 2, 3], 2)
print(find_strongest_eggs(*test))
test = ([51, 21, 83, 52, 55], 1)
print(find_strongest_eggs(*test))
|
f90806afdfc17a39caa1ae1f4020ae1846ba8cf0 | TaehoLi/Elementary-Python | /dictionary_assemble/alphanum3.py | 533 | 3.703125 | 4 | song = """by the rivers of babylon, there we sat down yeah we wept,
when we remember zion. when the wicked carried us away in captivity
required from us a song now how shall we sing the lord's song in a
strange land"""
alphabet = dict()
for c in song:
if c.isalpha() == False:
continue
c = c.lower()
if c not in alphabet:
alphabet[c] = 1
else:
alphabet[c] += 1
for code in range(ord('a'), ord('z')+1):
c = chr(code)
num = alphabet.get(c,0)
print(c, "=>", num)
|
41cdb7ee72292f505d82d7a69cc89bc399e04a04 | srinathalla/python | /algo/bit/repeatedDNASequences.py | 342 | 3.515625 | 4 | import collections
from typing import List
class Solution:
def findRepeatedDnaSequences(self, s: str) -> List[str]:
count = collections.Counter(s[i:i+10] for i in range(len(s) - 9))
return [w for w in count if count[w] > 1]
s1 = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
s = Solution()
print(s.findRepeatedDnaSequences(s1))
|
c7a784724627d0eb1920df73161dad47b69423f9 | PrashantMhrzn/Bulk-File-Renamer | /renamer.py | 657 | 3.546875 | 4 | from utils import Renamer
import argparse
parser = argparse.ArgumentParser(description='Renames every file inside the given folder.')
parser.add_argument('path', help='Absolute path of the folder')
parser.add_argument('-n','--naming_convention', metavar='', help='Not specifing will default to the name <file>')
args = parser.parse_args()
r = Renamer()
try:
if args.naming_convention == None:
args.naming_convention = 'file'
r.rename(args.path, args.naming_convention)
print("File Renaming Completed!")
except FileNotFoundError:
print("File Not Found Enter Correct Path!")
except ValueError:
print("Please Enter The Correct!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.