blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
daa95e1d0332847f4d8352cd704faa809e55ab8a | abhaj2/Phyton | /sample programs_cycle_1_phyton/17.py | 124 | 4.0625 | 4 | #To count the number of digits in an integer
c=0
x=int(input("Enter the digit"))
while x!=0:
x=x//10
c=c+1
print(c) |
5bd43106071a675af17a6051c9de1f0cee0e0aec | abhaj2/Phyton | /cycle-2/3_c.py | 244 | 4.125 | 4 | wordlist=input("Enter your word\n")
vowel=[]
for x in wordlist:
if('a' in x or 'e' in x or 'i' in x or 'o' in x or'u' in x or 'A' in x or 'E' in x or 'I' in x or 'O'in x or"U" in x):
vowel.append(x)
print(vowel)
|
b1369e3aa1af6e9af13e8376f8955bd1d4a64419 | abhaj2/Phyton | /sample programs_cycle_1_phyton/16.py | 218 | 3.984375 | 4 | x=int(input("Enter the first number\n"))
y=int(input("Enter the first number\n"))
if (x>y):
min=x
else:
min=y
while (1):
if(min%x==0 and min%y==0):
print("LCM of two numbers is",min)
break
min=min+1 |
460436876ac4dbeafc3b4e7abc9ba4bb0b211ac5 | abhaj2/Phyton | /cycle-2/20.py | 115 | 3.859375 | 4 | integer=[2,0,1,5,41,3,22,10,33]
list=[]
for x in integer:
if(x%2!=0):
list.append(x)
print(list)
|
11eba6924a3dd4c84b02172ba5335e918b6af738 | juliaviolet/Python_For_Everybody | /Chapter_9/Exercise_9.4_Final.py | 509 | 3.578125 | 4 | name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
emails = handle.read()
words=list()
counts=dict()
maximumvalue = None
maximumkey = None
for line in handle:
if not line.startswith('From: '): continue
line = line.split()
words.append(line[1])
for word in words:
counts[word] = counts.get(word, 0) + 1
for key,value in counts.items() :
if value > maximumvalue:
maximumvalue = value
maximumkey=key
print (maximumkey, maximumvalue)
|
a1a9fc369a0b994c99377dc6af16d00612a68f3b | juliaviolet/Python_For_Everybody | /Overtime_Pay_Error.py | 405 | 4.15625 | 4 | hours=input("Enter Hours:")
rate=input("Enter Rate:")
try:
hours1=float(hours)
rate1=float(rate)
if hours1<=40:
pay=hours1*rate1
pay1=str(pay)
print('Pay:'+'$'+pay1)
elif hours1>40:
overtime=hours1-40.0
pay2=overtime*(rate1*1.5)+40.0*rate1
pay3=str(pay2)
print('Pay:'+'$'+pay3)
except:
print('Error, please enter numeric input')
|
7320b834151d83c83268ecb7d9d5a72ca64fbccc | AdilAsanbekov/homework | /laboratory_work.py | 1,107 | 3.5 | 4 | from random import randint
from abc import ABC, abstractmethod
from math import floor
class Characted(ABC):
def __init__(self, name,level=1, strength=8, dexterity=8, intelligence=8, wisdom=8, charisma=8,constitution=8):
self.level = level
self.strength = strength
self.dexterity = dexterity
self.physique = physique
self.intelligence = intelligence
self.wisdom = wisdom
self.charisma = charisma
self.max_hp = 10 + floor((self.constitution - 10) / 2) + randint(1, 11) * self.level
self.hp = self.max_hp
self.armour_class = 15 + floor((self.dexterity - 10) / 2)
self.initiative = randint(1, 21) + floor(((self.dexterity - 10) / 2))
def attack(self):
return randint(1, 13) + floor(((self.strength - 10) / 2))
def save_throw(self, attribute):
return randint(1, 21) + floor(((attribute - 10) / 2))
@abstractmethod
def perk(self):
pass
class Hero(Characted):
def perk(self):
return randint(1, 17) + floor(((self.wisdom - 10) / 2))
class Dragon(Characted):
def perk(self):
return randint(1, 17) + floor(((self.strength - 10) / 2)) |
a48f5fdb04a1ad05b3613fef58f605c5b02ecc3b | abdiazizf/Chexers | /convert_json_to_board_dict.py | 799 | 3.859375 | 4 | # Converts a JSON into a dictionary of tuples(board co-ordinates) as keys with values to be printed
# e.g {[0,2]: 'R',[0,0]:'BLK'}
def convert_json_to_board_dict(file):
# Reads colour from the JSON, compares it to a dictionary of values and
# sets the correct symbol
colour_dict = {'red' : 'R','blue': 'B','green':'G'}
player_colour = colour_dict[file['colour']]
# Creates an empty dict and constructs an entry for each tuple in JSON, using
# predetermined player colour for player pieces and a block otherwise
board_dict = {}
for coordinate in file['pieces']:
board_dict[tuple(coordinate)] = player_colour
for coordinate in file['blocks']:
board_dict[tuple(coordinate)] = 'BLK'
#return dict
return board_dict
|
ddc84b9fe6cd1914fcaf55063d7df0dc9c8f7443 | rajvseetharaman/Hackerrank---Data-Structures-and-Algorithms | /Tries-Contacts.py | 1,161 | 3.59375 | 4 | class Node:
def __init__(self,children,endofword,countofword):
self.children=children
self.endofword=endofword
self.countofword=countofword
def contact_add(contact,root):
pointer=root
for i,letter in enumerate(contact):
if letter not in pointer.children.keys():
if i<len(contact)-1:
pointer.children[letter]=Node({},False,0)
else:
pointer.children[letter]=Node({},True,0)
pointer = pointer.children[letter]
else:
pointer=pointer.children[letter]
pointer.countofword+=1
def contact_find(contact,root):
pointer=root
counter=0
for i,letter in enumerate(contact):
if letter in pointer.children.keys():
pointer=pointer.children[letter]
else:
return 0
return(pointer.countofword)
n = int(input().strip())
root=Node({},False,0)
for a0 in range(n):
op, contact = input().strip().split(' ')
if op == 'add':
contact_add(contact,root)
if op == 'find':
print(contact_find(contact,root))
|
8f5b0df594cd45f91cb61f6afbcb6e9aa2edcafa | saintcoder14/JARVIS | /jarvis.py | 2,252 | 3.5 | 4 | import pyttsx3 #for output voice kinda
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)
def speak(audio):
# Imp function used to convert a text into audio
engine.say(audio)
engine.runAndWait()
def take_command():
# takes in audio from microphone and returns string as o/p
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening..")
r.pause_threshold = 1.2
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-IN')
print(f"User said:{query}\n")
except Exception:
speak("Please, say that again")
return "None"
return query
def wish_me():
#func to wish me on the basis of 'hour'
print("Welcome Back, sir")
speak("Jarvis, at your Service Sir!")
hour=int(datetime.datetime.now().hour)
if hour>=5 and hour <12:
speak("Good Morning darling")
elif hour>=12 and hour <5:
speak("Good afternoon darling")
else:
speak("Good evening darling")
speak("How may I help u?")
if __name__ == "__main__":
# main function
wish_me()
while True:
query=take_command().lower()
if 'wiki' in query:
speak('Searching Wikipedia')
query=query.replace('wikipedia','')
results = wikipedia.summary(query, sentences=2)
speak("According to Wikipedia")
print(results)
speak(results)
elif 'open google' in query:
webbrowser.open("google.com")
elif 'open youtube' in query:
webbrowser.open("youtube.com")
#elif 'what is the time' or 'whats the time' in query:
# strtime=datetime.datetime.now()
# speak("Sir, the time is %d %d" %(strtime.hour,strtime.minute))
elif 'who is your master' in query:
speak('It is one and only Master Sammridh')
elif 'okay bye' or 'bye' in query:
exit()
|
360b8fda90ac1651976268e9cf4205d7ec59f687 | ikhebgeenaccount/MusicBeeStats | /mbp/tagtracker.py | 4,884 | 4.09375 | 4 | class TagTracker:
"""A TagTracker tracks a certain tag.
Arguments:
tag - the tag to be tracked, can be either a str or a function which takes a Track and outputs some value
tag_data - the data tag to be tracked grouped under tag, can be either a str or a function which takes a Track and outputs some value
unique - boolean, True means each instance will be tracked separately, False means that an attempt will be made to add the data up, but this will only work for int or float type data
case_sensitive - boolean, whether to track differently capitalized strings together or separately
Examples:
Counts the number of tracks for each artist separately:
TagTracker('artist')
Note: it counts the number of occurrences of each separate artist, since we have a list of songs with tags artist this constitutes the number of songs of each artist in the library
Counts the play count for each artist separately:
TagTracker('artist', 'play_count', unique=False)
Note: in the above example, if unique is not passed the play_counts of each song will not be summed
Counts the play count for each genre separately:
TagTracker('genre', 'play_count', unique=False)
Sums the total play time of songs per artist:
TagTracker('artist', 'total_time', unique=False)
Calculates the total time played for each artist:
TagTracker('artist', tag_data=lambda t: t.get('play_count') * t.get('total_time'), unique=False)
Counts the number of songs that start with a particular letter:
TagTracker(tag=lambda t: t.get('name')[0])
"""
def __init__(self, tag, tag_data=None, unique=True, case_sensitive=False):
if isinstance(tag, str):
self.tag = lambda t: t.get(tag)
else:
self.tag = tag
if isinstance(tag_data, str):
self.tag_data = lambda t: t.get(tag_data)
else:
self.tag_data = tag_data
self.data = {}
self.case_map = {}
self.unique = unique
self.case_sensitive = case_sensitive
def evaluate(self, track):
"""Evaluates the given Track for the sought after tag. If the tag is found, and there is data in tag_data,
it is added to the tracker. """
if self.tag_data:
# If the track has the tag that we are tracking and it has the relevant data, add it
key = self.tag(track)
value = self.tag_data(track)
if key is not None and value is not None: # is not None because if value returns False for value = 0
if not self.case_sensitive and isinstance(key, str) and key.lower() in self.case_map.keys():
key = self.case_map[key.lower()]
elif not self.case_sensitive and isinstance(key, str):
self.case_map[key.lower()] = key
# Check if this is a new tag we track
if key in self.data.keys():
# If not, add up if it's a number, otherwise append to list
if not self.unique and (isinstance(value, int) or isinstance(value, float)):
self.data[key] += value
else:
self.data[key].append(value)
else:
# It's a new tag, add as a new number or list
if not self.unique and (isinstance(value, int) or isinstance(value, float)):
self.data[key] = value
else:
self.data[key] = [value]
else:
value = self.tag(track)
if value is not None:
if not self.case_sensitive and isinstance(value, str) and value.lower() in self.case_map.keys():
value = self.case_map[value.lower()]
elif not self.case_sensitive and isinstance(value, str):
self.case_map[value.lower()] = value
if value in self.data.keys():
if not self.unique and (isinstance(value, int) or isinstance(value, float)):
self.data[value] += value
else:
self.data[value] += 1
else:
if not self.unique and (isinstance(value, int) or isinstance(value, float)):
self.data[value] = value
else:
self.data[value] = 1
def reset(self):
"""
Resets the TagTracker to an empty state, as if no evaluate() has been called yet. Properties are maintained.
:return:
"""
self.data = {}
self.case_map = {}
# TODO: add arithmetic functions
def __sub__(self, other):
new_data = {}
# Subtract related entries
for i in self.data:
new_data[i] = self.data[i] - other.data[i] if i in other.data else self.data[i]
# Add -count for every entry not in self.data
for i in other.data:
if i not in self.data:
new_data[i] = -1 * other.data[i]
ret_tt = TagTracker(self.tag, self.tag_data, self.unique, self.case_sensitive)
ret_tt.data = new_data
return ret_tt
def __rsub__(self, other):
return self.return_self()
def __add__(self, other):
pass
def __radd__(self, other):
return self.return_self()
def __div__(self, other):
pass
def __rdiv__(self, other):
return self.return_self()
def __mul__(self, other):
pass
def __rmul__(self, other):
return self.return_self()
def return_self(self):
r = TagTracker(self.tag, self.tag_data, self.unique, self.case_sensitive)
r.data = self.data
return r
|
4bdaa4b30be65fa22cbf64265123484375d2c924 | Juttiz/cs50 | /pset6/vigenere.py | 1,096 | 3.828125 | 4 | from cs50 import get_string
from sys import argv
import sys
def main():
while True:
if len(sys.argv) ==2:
break
print("usage: python crack.py keyword")
exit(1)
cipher = []
n = 0
for i in range(len(argv[1])):
# cipher[i] =
if argv[1][i].isupper():
cipher.append(ord(argv[1][i]) - 65)
elif argv[1][i].islower():
cipher.append(ord(argv[1][i]) - 97)
else:
print("usage: python crack.py keyword")
exit(1)
s = get_string("plaintext: ")
print("ciphertext: ")
for c in s:
if c.isalpha():
if c.isupper():
x = n%len(argv[1])
l = ((ord(c)-65) + cipher[x])%26 +65
print(f"{chr(l)}",end = "")
n+=1
elif c.islower():
x = n%len(argv[1])
l = ((ord(c)-97) + cipher[x])%26 +97
print(f"{chr(l)}", end = "")
n+=1
else:
print(c,end = "")
print("")
if __name__ == "__main__" :
main() |
565e52b6beea00de278a0a46d24237839419748f | Juanma1909/scientific-computing | /Entrega Diferenciacion e Integracion/labdif.py | 7,693 | 4.15625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from time import time
def printA(f,x):
"""
Entrada: una funcion f y un arreglo x de números reales
Salida: un arreglo y de numeros reales correspondientes a la evaluacion de f(x)
Funcionamiento: se realiza un ciclo iterando por cada valor dentro del arreglo x, en cada iteracion
se evalua dicho valor en la función f y su resultado se almacena en el arreglo y
"""
y = []
for a in x:
ans = f(a)
y.append(ans)
return y
def printD(met,x,h,f):
"""
Entrada: un metodo met, un arreglo x de numeros reales, un numero h y un funcion f
Salida: un arrelgo correspondiente a la evaluación del metodo escogido con el h y un valor
perteneciente a x
Funcionamiento: se realiza un ciclo iterando por cada valor dentro del arreglo x, en cada iteracion
se evalua dicho valor en la metodología met con la función f y el h determinado, el
resultado se almacena en el arreglo y
"""
y = []
for a in x:
ans = met(f,a,h)
y.append(ans)
return y
def errores(yReal, yAT,yAD,yCE):
"""
Entrada: 4 arreglos de numeros reales yReal, yAT, yAD y yCE el primero hace referencia a los valores
obtenidos con la derivada analitica y los utlimos 3 hacen referencia a los valores obtenidos
mediante los metodos diferecias finitas hacia atras,adelante y centrada respectivamente
Salida: 3 arreglos de numeros reales los cuales hacen referencia a los errores absolutos de los metodos
diferecias finitas hacia atras,adelante y centrada respectivamente
Funcionamiento: se realiza un ciclo iterando por cada valor dentro del arreglo yReal, en cada iteracion
halla la diferencia absoluta con respecto a cada método, posteriormente dicahas diferencias se almacenan
en su arreglo a retornar correspondiente
"""
n = len(yReal)
ErAT,ErAD,ErCE = [],[],[]
for i in range(n):
ErAT.append(abs(yReal[i] - yAT[i]))
ErAD.append(abs(yReal[i] - yAD[i]))
ErCE.append(abs(yReal[i] - yCE[i]))
return ErAT,ErAD,ErCE
def ptime(tAD,tAT,tCE):
"""
Entrada: 3 tiempos de ejecución tAD,tAT y tCE los cuales hacen referencia a los tiempos de ejecucion
de los metodos diferecias finitas hacia adelante,atras y centrada respectivamente
Salida: se muestra en cosola los tiempos en cuestión
Funcionamiento: se realiza un print de los tiempos
"""
print("Tiempos de ejecucion:")
print("Adelante: " + str(tAD))
print("Atras: " + str(tAT))
print("Centrado: " + str(tCE))
return
def perror(err):
"""
Entrada: err es un arreglo que hace referencia a los errores absolutos de uno de los metodos.
Salida: Una impresion más organizada de el error medio y la desviacion estandar
Funcionamiento: primero se halla tanto el error medio como la desviacion estandar de los errores absolutos
posteriormente lo que se hace es imprimir 2 lineas de texto, una que contiene "Error Medio:" seguido de su
valor numerico correspondiente, y la otra que contiene "Desviacion Estandar:" seguido de su valor numerico correspondiente.
"""
mean = np.mean(err)
devia = np.std(err)
print("Error Medio: " + str(mean))
print("Desviación Estándar: " + str(devia))
return
"""
Este grupo de funciones hacen referencia a las funciones reales y sus derivadas analiticas correspondientes,
estas reciben un numero real x y retornal el valor de su imagen, de acuerdo a la evaluacion que se realice,
para su creacin se hizo uso de la librería numpy
"""
def seno2(x): return np.sin(2*x)
def logaritmo(x): return np.log(x)
def expo2(x): return np.exp(2*x)
def devseno2(x): return 2*np.cos(2*x)
def devlog(x): return 1/x
def devexpo2(x): return 2*np.exp(2*x)
def derAtras(f,x,h):
"""
Entrada:Una funcion f,un valor h y un valor x
Salida: el valor aporximado de la derivada de la funcion f a traves del metodo en cuestion
Funcionamiento: Se toman los valores de x y h y se evaluan con respecto a lo que dicta el
metodo de Diferencias finitas hacia atras
"""
ans = f(x) - f(x-h)
ans = ans/h
return ans
def derAdelante(f,x,h):
"""
Entrada:Una funcion f,un valor h y un valor x
Salida: el valor aporximado de la derivada de la funcion f a traves del metodo en cuestion
Funcionamiento: Se toman los valores de x y h y se evaluan con respecto a lo que dicta el
metodo de Diferencias finitas hacia adelante
"""
ans = f(x+h) - f(x)
ans=ans/h
return ans
def derCentro(f,x,h):
"""
Entrada:Una funcion f,un valor h y un valor x
Salida: el valor aporximado de la derivada de la funcion f a traves del metodo en cuestion
Funcionamiento: Se toman los valores de x y h y se evaluan con respecto a lo que dicta el
metodo de Diferencias finitas centrada
"""
ans = f(x+h)-f(x-h)
ans = ans/(2*h)
return ans
def main():
"""
en la funcion main se realiza un for donde en cada iteracion el valor de h se divide entre 10 y así tienda más a 0, en cada ciclo
se hallan los valores de las derivadas aproximadas así como el valor de la derivada analitica para un conjunto de puntos x, posteriormente
se hallan los errores medios para cada uno de los metodos, eso se hace para cada una de las funciones reales escogidas
"""
x = np.linspace(0.5,10,200)
print("Funcion Seno(2x)")
ySinA = printA(devseno2,x)
h = 1
for i in range(4):
if i != 0: h/=10
print(str(h))
tsAD = time()
ySinAD = printD(derAdelante,x,h,seno2)
totalsAD = time() - tsAD
tsAT = time()
ySinAT = printD(derAtras,x,h,seno2)
totalsAT = time() - tsAT
tsCE = time()
ySinCE = printD(derCentro,x,h,seno2)
totalsCE = time() - tsCE
errAT,errAD,errCE=errores(ySinA,ySinAT,ySinAD,ySinCE)
perror(errAT)
perror(errAD)
perror(errCE)
ptime(totalsAD,totalsAT,totalsCE)
plt.title("Funcion Seno")
plt.plot(x,ySinA, label = "Derivada Analitica")
plt.plot(x,ySinAD, label = "Adelante")
plt.plot(x,ySinAT, label = "Atras")
plt.plot(x,ySinCE, label = "Centrada")
plt.grid()
plt.legend()
plt.show()
print("Funcion logaritmo(x)")
x = np.linspace(1.1,10,200)
yLogA = printA(devlog,x)
h = 1
for i in range(4):
if i != 0: h/=10
print(str(h))
tlAD = time()
yLogAD = printD(derAdelante,x,h,logaritmo)
totallAD = time() - tlAD
tlAT = time()
yLogAT = printD(derAtras,x,h,logaritmo)
totallAT = time() - tlAT
tlCE = time()
yLogCE = printD(derCentro,x,h,logaritmo)
totallCE = time() - tlCE
errAT,errAD,errCE=errores(yLogA,yLogAT,yLogAD,yLogCE)
perror(errAT)
perror(errAD)
perror(errCE)
ptime(totallAD,totallAT,totallCE)
plt.title("Funcion Logaritmo")
plt.plot(x,yLogA, label = "Derivada Analitica")
plt.plot(x,yLogAD, label = "Adelante")
plt.plot(x,yLogAT, label = "Atras")
plt.plot(x,yLogCE, label = "Centrada")
plt.grid()
plt.legend()
plt.show()
x = np.linspace(0.5,10,200)
print("Funcion e^(2x)")
yEA = printA(devexpo2,x)
h = 1
for i in range(4):
if i != 0: h/=10
print(str(h))
teAD = time()
yEAD = printD(derAdelante,x,h,expo2)
totaleAD = time() - teAD
teAT = time()
yEAT = printD(derAtras,x,h,expo2)
totaleAT = time() - teAT
teCE = time()
yECE = printD(derCentro,x,h,expo2)
totaleCE = time() - teCE
errAT,errAD,errCE=errores(yEA,yEAT,yEAD,yECE)
perror(errAT)
perror(errAD)
perror(errCE)
ptime(totaleAD,totaleAT,totaleCE)
plt.title("Funcion e")
plt.plot(x,yEA, label = "Derivada Analitica")
plt.plot(x,yEAD, label = "Adelante")
plt.plot(x,yEAT, label = "Atras")
plt.plot(x,yECE, label = "Centrada")
plt.grid()
plt.legend()
plt.show()
return
main()
|
b0ac70b3510ec9bab0f2ca5b49abdf9d2ccabc23 | gutsergey/PythonSamples | /Fedorov/5 Strings/strings1.py | 910 | 3.59375 | 4 | def strings1():
a = "qwerty"
b = 'qwerty123'
c = '''comment1
text1
text2
text3
---- text 4 end of comment1-------
'''
d = """comment 2
text 1
text2
text3
----- end of comment 2 ---------
'''
"""
e = " somebody says: 'Hello' "
f = ' somebody says: "Hello" '
print (a)
print (b)
print (c)
print (d)
print (e)
print (f)
print("type of variable f:", type(f))
print('''
escape sequences
\\n - переход на новую строку
\\t - знак табуляции
\\\\ - наклонная черта влево
\\' - символ одиночной кавычки
\\" - символ двойной кавычки
''')
import sys
print ("Hello", " ", 'World', "!", sep=' ', end='\n', file=sys.stdout, flush=False)
print ("Hello", " ", 'World', "!", sep='-', end='*\n', file=sys.stdout, flush=False)
print ("------");
|
28fe9d2012c336a30119abc523ecd17c5dc41aed | gutsergey/PythonSamples | /Fedorov/4/averageofthreenumbers2.py | 184 | 3.578125 | 4 | def averageofthreenumbers2(a=2, b=4, c=7):
return (a + b + c)/3
print(averageofthreenumbers2())
print(averageofthreenumbers2(5, 7, 2))
print(averageofthreenumbers2(c=3, a=4))
|
687453f6803bea6331dc6513208bc8c7de45bf22 | yeraydiazdiaz/lunr.py | /lunr/vector.py | 5,295 | 4.125 | 4 | from math import sqrt
from lunr.exceptions import BaseLunrException
class Vector:
"""A vector is used to construct the vector space of documents and queries.
These vectors support operations to determine the similarity between two
documents or a document and a query.
Normally no parameters are required for initializing a vector, but in the
case of loading a previously dumped vector the raw elements can be provided
to the constructor.
For performance reasons vectors are implemented with a flat array, where an
elements index is immediately followed by its value.
E.g. [index, value, index, value].
TODO: consider implemetation as 2-tuples.
This allows the underlying array to be as sparse as possible and still
offer decent performance when being used for vector calculations.
"""
def __init__(self, elements=None):
self._magnitude = 0
self.elements = elements or []
def __repr__(self):
return "<Vector magnitude={}>".format(self.magnitude)
def __iter__(self):
return iter(self.elements)
def position_for_index(self, index):
"""Calculates the position within the vector to insert a given index.
This is used internally by insert and upsert. If there are duplicate
indexes then the position is returned as if the value for that index
were to be updated, but it is the callers responsibility to check
whether there is a duplicate at that index
"""
if not self.elements:
return 0
start = 0
end = int(len(self.elements) / 2)
slice_length = end - start
pivot_point = int(slice_length / 2)
pivot_index = self.elements[pivot_point * 2]
while slice_length > 1:
if pivot_index < index:
start = pivot_point
elif pivot_index > index:
end = pivot_point
else:
break
slice_length = end - start
pivot_point = start + int(slice_length / 2)
pivot_index = self.elements[pivot_point * 2]
if pivot_index == index:
return pivot_point * 2
elif pivot_index > index:
return pivot_point * 2
else:
return (pivot_point + 1) * 2
def insert(self, insert_index, val):
"""Inserts an element at an index within the vector.
Does not allow duplicates, will throw an error if there is already an
entry for this index.
"""
def prevent_duplicates(index, val):
raise BaseLunrException("Duplicate index")
self.upsert(insert_index, val, prevent_duplicates)
def upsert(self, insert_index, val, fn=None):
"""Inserts or updates an existing index within the vector.
Args:
- insert_index (int): The index at which the element should be
inserted.
- val (int|float): The value to be inserted into the vector.
- fn (callable, optional): An optional callable taking two
arguments, the current value and the passed value to generate
the final inserted value at the position in case of collision.
"""
fn = fn or (lambda current, passed: passed)
self._magnitude = 0
position = self.position_for_index(insert_index)
if position < len(self.elements) and self.elements[position] == insert_index:
self.elements[position + 1] = fn(self.elements[position + 1], val)
else:
self.elements.insert(position, val)
self.elements.insert(position, insert_index)
def to_list(self):
"""Converts the vector to an array of the elements within the vector"""
output = []
for i in range(1, len(self.elements), 2):
output.append(self.elements[i])
return output
def serialize(self):
# TODO: the JS version forces rounding on the elements upon insertion
# to ensure symmetry upon serialization
return [round(element, 3) for element in self.elements]
@property
def magnitude(self):
if not self._magnitude:
sum_of_squares = 0
for i in range(1, len(self.elements), 2):
value = self.elements[i]
sum_of_squares += value * value
self._magnitude = sqrt(sum_of_squares)
return self._magnitude
def dot(self, other):
"""Calculates the dot product of this vector and another vector."""
dot_product = 0
a = self.elements
b = other.elements
a_len = len(a)
b_len = len(b)
i = j = 0
while i < a_len and j < b_len:
a_val = a[i]
b_val = b[j]
if a_val < b_val:
i += 2
elif a_val > b_val:
j += 2
else:
dot_product += a[i + 1] * b[j + 1]
i += 2
j += 2
return dot_product
def similarity(self, other):
"""Calculates the cosine similarity between this vector and another
vector."""
if self.magnitude == 0 or other.magnitude == 0:
return 0
return self.dot(other) / self.magnitude
|
65ff4a78f9cc6d7254418df1489c95eb0acbe98f | cfung/machine-learning | /projects/smartcab/smartcab/agent.py | 11,289 | 3.71875 | 4 | import random
import math
from environment import Agent, Environment
from planner import RoutePlanner
from simulator import Simulator
from collections import defaultdict
from helper import calculate_safety, calculate_reliability, evaluate_results
class LearningAgent(Agent):
""" An agent that learns to drive in the Smartcab world.
This is the object you will be modifying. """
def __init__(self, env, learning=False, epsilon=1.0, alpha=0.5):
super(LearningAgent, self).__init__(env) # Set the agent in the evironment
self.planner = RoutePlanner(self.env, self) # Create a route planner
self.valid_actions = self.env.valid_actions # The set of valid actions
# Set parameters of the learning agent
self.learning = learning # Whether the agent is expected to learn
self.Q = dict() # Create a Q-table which will be a dictionary of tuples
self.epsilon = epsilon # Random exploration factor
self.alpha = alpha # Learning factor
###########
## TO DO ##
###########
# Set any additional class parameters as needed
self.max_trail = 10 #20
self.prev_state = None
self.prev_action = None
self.prev_reward = None
self.def_Q = 0
self.trial_number = 0
def reset(self, destination=None, testing=False):
""" The reset function is called at the beginning of each trial.
'testing' is set to True if testing trials are being used
once training trials have completed. """
# Select the destination as the new location to route to
self.planner.route_to(destination)
self.trial_number += 1
print "trial_number is...", self.trial_number
###########
## TO DO ##
###########
# Update epsilon using a decay function of your choice
# Update additional class parameters as needed
# If 'testing' is True, set epsilon and alpha to 0
if testing:
self.epsilon = 0
self.alpha = 0
else:
self.epsilon -= 0.05 # this is used for default learning agent
#self.epsilon = math.exp(-self.alpha * self.trial_number)
# other decay functions that were tried
# self.epsilon = math.cos(0.15*self.trial_number)
# self.epsilon = 1/(t^2)
# self.epsilon = float(1)/(math.exp(float( 0.1 * self.trial_number)))
self.gamma = 0.1 # gamma determines how much future reward is valued. 0 means immediate reward
self.prev_state = None
self.prev_action = None
self.prev_reward = None
return None
def build_state(self):
""" The build_state function is called when the agent requests data from the
environment. The next waypoint, the intersection inputs, and the deadline
are all features available to the agent. """
# Collect data about the environment
waypoint = self.planner.next_waypoint() # The next waypoint
inputs = self.env.sense(self) # Visual input - intersection light and traffic
deadline = self.env.get_deadline(self) # Remaining deadline
###########
## TO DO ##
###########
# Set 'state' as a tuple of relevant data for the agent
# Set the state as a tuple and inlcude 'light status', 'oncoming traffic' and 'waypoint'
self.state = (inputs['light'], inputs['oncoming'], inputs['left'], waypoint)
return self.state
def get_maxQ(self, state):
""" The get_max_Q function is called when the agent is asked to find the
maximum Q-value of all actions based on the 'state' the smartcab is in. """
###########
## TO DO ##
###########
# Calculate the maxmimum Q-value of all actions for a given state
maxQ_action = None
maxQ_value = 0
'''
print "******** GET_MAXQ ********"
print "what is whole self.Q..", self.Q
print "what is state (get_maxQ)...", state
print "what is self.state (get_maxQ)...", self.state
print "MAX_Q: action and value" + str(maxQ_action) + ',' + str(maxQ_value)
print "MAX_Q: what is self.Q[self.state]...", self.Q[self.state]
print "length of self.Q..", len(self.Q)
print "length of self.Q[state]", len(self.Q[state])
#print "??? test max ???", max(self.Q[self.state].values())
print "******** ***** ** ************"
'''
if len(self.Q[state]) > 0:
print "(get_maxQ) result...", max(self.Q[state].values())
maxQ_value = max(self.Q[state].values())
else:
maxQ_value = 0
#print ("what is maxQ_value..", maxQ_value)
return maxQ_value
def createQ(self, state):
""" The createQ function is called when a state is generated by the agent. """
###########
## TO DO ##
###########
# When learning, check if the 'state' is not in the Q-table
# If it is not, create a new dictionary for that state
# Then, for each action available, set the initial Q-value to 0.0
# We'll use defaultdict and by default it is initialized to 0
if self.learning:
if state not in self.Q.keys():
self.Q[state] = defaultdict(int)
return
def choose_action(self, state):
""" The choose_action function is called when the agent is asked to choose
which action to take, based on the 'state' the smartcab is in. """
# Set the agent state and default action
self.state = state
self.next_waypoint = self.planner.next_waypoint()
action = None
###########
## TO DO ##
###########
# When not learning, choose a random action
# When learning, choose a random action with 'epsilon' probability
# Otherwise, choose an action with the highest Q-value for the current state
# a valid action is one of None, (do nothing) 'Left' (turn left), 'Right' (turn right), or 'Forward' (go forward)
# Note that you have access to several class variables that will help you write this functionality, such as 'self.learning' and 'self.valid_actions
if self.learning == False:
# choose a
action = random.choice(self.valid_actions)
else: # when learning
# choose a random action with 'ipsilon' probability
if self.epsilon > random.random():
action = random.choice(self.valid_actions)
else:
# get action with highest Q-value for the current state
maxQ = self.get_maxQ(state)
best_actions = []
print "choose_action..self.Q[state]..", self.Q[state]
for act in self.Q[state]:
print "choose_action..act..", act
if self.Q[state][act] == maxQ:
best_actions.append(act)
if (len(best_actions) > 0):
action = random.choice(best_actions)
print "action taken in choose_action...", str(action)
return action
def learn(self, state, action, reward):
""" The learn function is called after the agent completes an action and
receives an award. This function does not consider future rewards
when conducting learning. """
###########
## TO DO ##
###########
# When learning, implement the value iteration update rule
# Use only the learning rate 'alpha' (do not use the discount factor 'gamma')
next_state = self.build_state()
if self.learning:
print "(learn)what is self.state (learn)..", self.state
print "(learn)what is state (learn)..", state
print "(learn)what is action (learn)..", action
currentQ = self.Q[state][action]
print "(learn) what is currentQ....?", currentQ
self.Q[state][action] = reward*self.alpha + currentQ*(1-self.alpha)
print "(learn), what is after learning...", self.Q[state][action]
return
def update(self):
""" The update function is called when a time step is completed in the
environment for a given trial. This function will build the agent
state, choose an action, receive a reward, and learn if enabled. """
state = self.build_state() # Get current state
self.createQ(state) # Create 'state' in Q-table
action = self.choose_action(state) # Choose an action
reward = self.env.act(self, action) # Receive a reward
self.learn(state, action, reward) # Q-learn
return
def run():
""" Driving function for running the simulation.
Press ESC to close the simulation, or [SPACE] to pause the simulation. """
##############
# Create the environment
# Flags:
# verbose - set to True to display additional output from the simulation
# num_dummies - discrete number of dummy agents in the environment, default is 100
# grid_size - discrete number of intersections (columns, rows), default is (8, 6)
env = Environment(verbose=True, grid_size=(8,6))
##############
# Create the driving agent
# Flags:
# learning - set to True to force the driving agent to use Q-learning
# * epsilon - continuous value for the exploration factor, default is 1
# * alpha - continuous value for the learning rate, default is 0.5
agent = env.create_agent(LearningAgent, learning = True, alpha = 0.5, epsilon = 1.0) #0.8 (epsilon) #0.01 (alpha)
#agent.learning = True
#agent.epsilon = 1
#agent.alpha = 0.5
##############
# Follow the driving agent
# Flags:
# enforce_deadline - set to True to enforce a deadline metric
env.set_primary_agent(agent, enforce_deadline = True)
env.testing = True
#env.enforce_deadline = True
##############
# Create the simulation
# Flags:
# update_delay - continuous time (in seconds) between actions, default is 2.0 seconds
# display - set to False to disable the GUI if PyGame is enabled
# log_metrics - set to True to log trial and simulation results to /logs
# optimized - set to True to change the default log file name
sim = Simulator(env, update_delay = 0.01, log_metrics = True, display = False, optimized = False)
sim.testing = True
#sim.update_delay = 0.01, 2.0
#sim.log_metrics = True
#sim.display = False
#sim.optimized = True
##############
# Run the simulator
# Flags:
# tolerance - epsilon tolerance before beginning testing, default is 0.05
# n_test - discrete number of testing trials to perform, default is 0
#sim.n_test = agent.max_trail
sim.run(tolerance = 0.05, n_test = agent.max_trail)
# sim.run(tolerance = 0.6, n_test = agent.max_trail
if __name__ == '__main__':
#get_opt_result()
run()
|
d387a110a9578f1fcf92811f2efc64161feddbf4 | faisalsupriansyah/praxis-academy | /novice/01-02/data_type_convertion/arrayvlist.py | 1,164 | 3.53125 | 4 | import numpy as np
arr_a = np.array([3, 6, 9])
arr_b = arr_a/3 # Performing vectorized (element-wise) operations
print(arr_b)
arr_ones = np.ones(4)
print(arr_ones)
multi_arr_ones = np.ones((3,4)) # Creating 2D array with 3 rows and 4 columns
print(multi_arr_ones)
stack = [1,2,3,4,5]
stack.append(6) # Bottom -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 (Top)
print(stack)
stack.pop() # Bottom -> 1 -> 2 -> 3 -> 4 -> 5 (Top)
stack.pop() # Bottom -> 1 -> 2 -> 3 -> 4 (Top)
print(stack)
graph = { "a" : ["c", "d"],
"b" : ["d", "e"],
"c" : ["a", "e"],
"d" : ["a", "b"],
"e" : ["b", "c"]
}
def define_edges(graph):
edges = []
for vertices in graph:
for neighbour in graph[vertices]:
edges.append((vertices, neighbour))
return edges
print(define_edges(graph))
class Tree:
def __init__(self, info, left=None, right=None):
self.info = info
self.left = left
self.right = right
def __str__(self):
return (str(self.info) + ', Left child: ' + str(self.left) + ', Right child: ' + str(self.right))
tree = Tree(1, Tree(2, 2.1, 2.2), Tree(3, 3.1))
print(tree) |
6995eed67a401cd363dcfa60b2067ef13732becb | ha1fling/CryptographicAlgorithms | /3-RelativePrimes/Python-Original2017Code/Task 3.py | 1,323 | 4.25 | 4 | while True: #while loop for possibility of repeating program
while True: #integer check for input a
try:
a= input ("Enter a:")
a= int(a)
break
except ValueError:
print ("Not valid, input integers only")
while True: #integer check for input b
try:
b= input ("Enter b:")
b= int(b)
break
except ValueError:
print ("Not valid, input integers only")
def gcd(a,b): #define function
c=abs(a-b) #c = the absolute value of a minus b
if (a-b)==0: # if a-b=0
return b #function outputs b
else:
return gcd(c,min(a,b)) #function outputs smallest value out of a,b and c
d=gcd(a,b) #function assigned to value d
if d==1:
print ("-They are relative primes") #if the gcd is one they are relative primes
else:
print ("-They are not relative primes") #else/ if the gcd is not one they are not relative primes
print ()
v=input("Would you like to repeat the relative prime identifier? Enter y or n.") #while loop for repeating program
print ()
if v == "y": #y repeats program
continue
elif v == "n": #n ends program
break |
bd1db01726f5373dadb80c3da3f29b4ec1f8ad88 | TiagoArrazi/Python-HOME | /FileProcessor.py | 588 | 3.59375 | 4 | import os
import csv
def main():
arq = input('Insira o nome do arquivo ')
name, ext = os.path.splitext(arq)
if ext == '.txt':
processaTxt(arq)
elif ext == '.csv':
processaCsv(arq)
else:
print('ERRO!')
def processaTxt(arq):
with open(arq,'r') as f:
content = f.read()
print(content)
def processaCsv(arq):
with open(arq, newline = '') as f:
content = csv.reader(f)
for row in content:
print(row)
main()
|
17ed1954aef7212bf33317ee7e8c174d7f26ca65 | AnnMokhova/PROGA | /hw10/hw10.py | 839 | 3.5625 | 4 | #вариант 2
import re
def open_file(file):
with open(file, 'rb') as f:
f = f.read()
return f
def search_write():
ask = input('Введите название города, часовой пояс которого вы хотите узнать ') #Москва Берлин Нью-Йорк
if ask == 'Москва':
doc = 'Moscow.html'
if ask == 'Берлин':
doc = 'Berlin.html'
if ask == 'Нью-Йорк':
doc = 'NY.html'
text = open_file(doc)
result = re.search(r'Часовой пояс (\S+\s+\S+)', text.decode('utf-8'), re.I | re.U)
with open('text.txt', 'w') as empty_file:
empty_file.write(result.group())
print('Откройте файл text.txt, чтобы узнать часовой пояс указанного города')
search_write()
|
fc7534418fb1b55e1b4aa92c6718bb2553b8efc7 | AnnMokhova/PROGA | /hw2.py | 225 | 3.921875 | 4 | word = str(input('введите слово для задания 2 варианта: '))
for i in range(len(word)):
if (i % 2 == 0) and (word[i] == 'п' or word[i] == 'о' or word[i] == 'е'):
print(word[i])
|
47e84bf4f6a9c1479c1a5ecfd96a983f3f083698 | HarrisonMc555/exercism | /python/isogram/isogram.py | 327 | 3.609375 | 4 | def is_isogram(s):
sletters = list(filter(str.isalpha, s.lower()))
return len(set(sletters)) == len(sletters)
def is_isogram_(s):
seen = set()
for c in s.lower():
if not c.isalpha():
continue
if c in seen:
return False
seen.add(c)
else:
return True
|
a391e811b9248b693273f996d670b5e45cb0c55f | HarrisonMc555/exercism | /python/allergies/test.py | 476 | 3.515625 | 4 | import unittest
from allergies import Allergies
class AllergiesTests(unittest.TestCase):
def test_allergic_to_eggs_in_addition_to_other_stuff(self):
allergies = Allergies(5)
# print('lst:', allergies.lst)
self.assertIs(allergies.is_allergic_to('eggs'), True)
self.assertIs(allergies.is_allergic_to('shellfish'), True)
self.assertIs(allergies.is_allergic_to('strawberries'), False)
if __name__ == '__main__':
unittest.main()
|
52c4f2131fa1b0380b9d3e1c6abdfac944a0e254 | HarrisonMc555/exercism | /python/bob/bob.py | 840 | 3.828125 | 4 | import string
def hey(phrase):
if is_yelling_question(phrase):
return 'Calm down, I know what I\'m doing!'
elif is_question(phrase):
return 'Sure.'
elif is_yelling(phrase):
return 'Whoa, chill out!'
elif is_saying_nothing(phrase):
return 'Fine. Be that way!'
else:
return 'Whatever.'
def is_question(phrase):
phrase = phrase.strip()
if not phrase:
return False
return phrase[-1] == '?'
def is_yelling(phrase):
phrase = phrase.strip()
if not any(letter in phrase for letter in string.ascii_letters):
return False
return not any(letter in phrase for letter in string.ascii_lowercase)
def is_yelling_question(phrase):
return is_question(phrase) and is_yelling(phrase)
def is_saying_nothing(phrase):
return not phrase.strip()
|
a62cde765969fc2327e8149a08492313436b201b | viniciusrogerio/lista_controle_2 | /4.py | 672 | 4.09375 | 4 | '''4. Faca um programa que solicite ao usuário 10 números inteiros e, ao final, informe a
quantidade de números impares e pares lidos. Calcule também a soma dos números pares e a
media dos números impares.
'''
i=1
qtdpares=0
qtdimpares=0
somapares=0
mediaimpares=0
while(True):
if i>10:
break
num=int(input(f'Digite o {i}° numero: '))
if num % 2 == 0:
qtdpares+=1
somapares+=num
else:
qtdimpares+=1
mediaimpares+=num
i+=1
mediaimpares=mediaimpares/qtdimpares
print(f'Quantidade de numeros pares: {qtdpares}')
print(f'Quantidade de numeros impares: {qtdimpares}')
print(f'Soma dos pares: {somapares}')
print(f'Media dos impares: {mediaimpares}') |
b037f4057f2ab8c9c74c1eb697b9d31b598b2565 | booler/spatial-interpolators | /spatial_interpolators/legendre.py | 3,694 | 3.578125 | 4 | #!/usr/bin/env python
u"""
legendre.py (03/2019)
Computes associated Legendre functions of degree n evaluated for each element x
n must be a scalar integer and X must contain real values ranging -1 <= x <= 1
Program is based on a Fortran program by Robert L. Parker, Scripps Institution
of Oceanography, Institute for Geophysics and Planetary Physics, UCSD. 1993.
Parallels the MATLAB legendre function
INPUTS:
l: maximum degree of Legrendre polynomials
x: elements ranging from -1 to 1 (e.g. cos(theta))
PYTHON DEPENDENCIES:
numpy: Scientific Computing Tools For Python (http://www.numpy.org)
REFERENCES:
M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
Dover Publications, 1965, Ch. 8.
J. A. Jacobs, "Geomagnetism", Academic Press, 1987, Ch.4.
UPDATE HISTORY:
Updated 03/2019: calculate twocot separately to avoid divide warning
Written 08/2016
"""
import numpy as np
def legendre(n,x):
#-- Convert x to a single row vector
x = np.squeeze(x).flatten()
#-- for the n = 0 case
if (n == 0):
Pl = np.ones((1,len(x)), dtype=np.float)
return Pl
#-- for all other degrees
rootn = np.sqrt(np.arange(0,2*n+1))#-- +1 to include 2*n
s = np.sqrt(1 - x**2)
P = np.zeros((n+3,len(x)), dtype=np.float)
#-- Find values of x,s for which there will be underflow
sn = (-s)**n
tol = np.sqrt(np.finfo(np.float).tiny)
count = np.count_nonzero((s > 0) & (np.abs(sn) <= tol))
if (count > 0):
ind, = np.nonzero((s > 0) & (np.abs(sn) <= tol))
#-- Approx solution of x*ln(x) = Pl
v = 9.2 - np.log(tol)/(n*s[ind])
w = 1.0/np.log(v)
m1 = 1+n*s[ind]*v*w*(1.0058+ w*(3.819 - w*12.173))
m1 = np.min([n, np.floor(m1)]).astype(np.int)
#-- Column-by-column recursion
for k,mm1 in enumerate(m1):
col = ind[k]
#-- Calculate twocot for underflow case
twocot = -2.0*x[col]/s[col]
P[mm1-1:n+1,col] = 0.0
#-- Start recursion with proper sign
tstart = np.finfo(np.float).eps
P[mm1-1,col] = np.sign(np.fmod(mm1,2)-0.5)*tstart
if (x[col] < 0):
P[mm1-1,col] = np.sign(np.fmod(n+1,2)-0.5)*tstart
#-- Recur from m1 to m = 0, accumulating normalizing factor.
sumsq = tol.copy()
for m in range(mm1-2,-1,-1):
P[m,col] = ((m+1)*twocot*P[m+1,col] - \
rootn[n+m+2]*rootn[n-m-1]*P[m+2,col]) / \
(rootn[n+m+1]*rootn[n-m])
sumsq += P[m,col]**2
#-- calculate scale
scale = 1.0/np.sqrt(2.0*sumsq - P[0,col]**2)
P[0:mm1+1,col] = scale*P[0:mm1+1,col]
#-- Find the values of x,s for which there is no underflow, and (x != +/-1)
count = np.count_nonzero((x != 1) & (np.abs(sn) >= tol))
if (count > 0):
nind, = np.nonzero((x != 1) & (np.abs(sn) >= tol))
#-- Calculate twocot for normal case
twocot = -2.0*x[nind]/s[nind]
#-- Produce normalization constant for the m = n function
d = np.arange(2,2*n+2,2)
c = np.prod(1.0 - 1.0/d)
#-- Use sn = (-s)**n (written above) to write the m = n function
P[n,nind] = np.sqrt(c)*sn[nind]
P[n-1,nind] = P[n,nind]*twocot*n/rootn[-1]
#-- Recur downwards to m = 0
for m in range(n-2,-1,-1):
P[m,nind] = (P[m+1,nind]*twocot*(m+1) - \
P[m+2,nind]*rootn[n+m+2]*rootn[n-m-1])/(rootn[n+m+1]*rootn[n-m])
#-- calculate Pl from P
Pl = P[0:n+1,:]
#-- Polar argument (x == +/-1)
count = np.count_nonzero(s == 0)
if (count > 0):
s0, = np.nonzero(s == 0)
Pl[0,s0] = x[s0]**n
#-- Calculate the unnormalized Legendre functions by multiplying each row
#-- by: sqrt((n+m)!/(n-m)!) = sqrt(prod(n-m+1:n+m))
#-- following Abramowitz and Stegun
for m in range(1,n):
Pl[m,:] = np.prod(rootn[n-m+1:n+m+1])*Pl[m,:]
#-- Last row (m = n) must be done separately to handle 0!
#-- NOTE: the coefficient for (m = n) overflows for n>150
Pl[n,:] = np.prod(rootn[1:])*Pl[n,:]
return Pl
|
7972dcd1ccb20497b56dde4ee725bb1e833b43c8 | xuhyang/practice | /solution/heap.py | 596 | 3.625 | 4 | class Heap:
def heapify(self, nums):
# (len(nums) - 1) // 2 or len(nums) // 2 or len(nums) // 2 - 1 all okay
for i in range(len(nums) // 2, -1, -1):
self.siftDown(nums, i)
def siftDown(self, nums, i):
#check if left child will be out of index, not i < len(nums)
while i * 2 + 1 < len(nums):
son = i * 2 + 1
if son + 1 < len(nums) and nums[son + 1] < nums[son]:
son += 1
if nums[i] <= nums[son]:
break
nums[i], nums[son] = nums[son], nums[i]
i = son
|
009209f32d917829d0a5ee111fdc3cbc8cddaec3 | ruthraprabhu89/Hiku-tester | /hiker1.py | 1,143 | 4 | 4 | class hiker:
def haiku(self,line):
print("line{}".format(line))
lines = line.split('/')
print("no of lines {}".format (len(lines)))
if not len(lines)<3:
raise ValueError('Haiku should contain three lines. No of lines found:{}'.format(len(lines)))
return
syl = [0,0,0]
for i in range(len(lines)):
words = lines[i].split()
print("line no {}: no of words {}".format (i, len(words)))
for j in range(len(words)):
#print("word no {}.{}".format (j,words[j]))
is_vow = False
cur_word = words[j]
for k in range(len(cur_word)):
letter = cur_word[k]
if letter in ('a','e','i','o','u','y'):
if not is_vow == True:
syl[i] += 1
is_vow = True
else:
is_vow = False
print("no of syllable: {}".format(syl[i]))
if (syl[0] == 5 and syl[1] == 7 and syl[2] == 5):
result = 'Yes'
else:
result = 'No'
print("{}/{}/{},{}".format(syl[0],syl[1],syl[2],result))
if __name__ == "__main__":
filepath = 'test.txt'
with open(filepath) as fp:
for cnt,line in enumerate(fp):
haiku(line)
|
a5de4f9c3abf4ce25c5353680f63d4d2bed21a63 | Crazyinfo/Python-learn | /basis/错误、调试和测试/调试.py | 1,426 | 4.0625 | 4 | # 第一种方法将错误打印出来,用print()
# 第二种方法,凡是用print()来辅助查看的地方,都可以用断言(assert)来替代
def foo(s):
n = int(s)
assert n != 0,'n is zero' # ssert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错。
return 10 / n
def main():
foo('0')
if __name__ == '__main__':
main()
# 第三种方法,把print()替换为logging是第3种方式,和assert比,logging不会抛出错误,而且可以输出到文件。
import logging
x = '0'
y = int(x)
logging.info('y = %d' % y)
print(10 / y)
import logging
logging.basicConfig(level=logging.INFO)
# logging的好处,它允许你指定记录信息的级别,有debug,info,warning,error等几个级别,
# 当我们指定level=INFO时,logging.debug就不起作用了。
# 第四种方法是启动Python的调试器pdb,让程序以单步方式运行,可以随时查看运行状态。
# pdb.set_trace()
# 这个方法也是用pdb,但是不需要单步执行,我们只需要import pdb,然后,在可能出错的地方放一个pdb.set_trace(),就可以设置一个断点
import pdb
k = '0'
g = int(k)
pdb.set_trace() # 运行到这里会自动暂停
print(10 / g)
# 运行代码,程序会自动在pdb.set_trace()暂停并进入pdb调试环境,可以用命令p查看变量,或者用命令c继续运行 |
aeb8f28c7c87fcf9df9f60e1a0b65786b9910beb | Crazyinfo/Python-learn | /basis/基础/偏函数.py | 766 | 4.3125 | 4 | print(int('12345'))
print(int('12345',base = 8)) # int()中还有一个参数base,默认为10,可以做进制转换
def int2(x,base=2):
return int(x,base) # 定义一个方便转化大量二进制的函数
print(int2('11011'))
# functools.partial就是帮助我们创建一个偏函数的,不需要我们自己定义int2(),可以直接使用下面的代码创建一个新的函数int3:
import functools
int3 = functools.partial(int , base = 2) # 固定了int()函数的关键字参数base
print(int3('11000111'))
# functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。
print(int3('110101',base = 8)) # base = 2可以重新定义 |
e1fefe2ea38f94fda67111e127d82109902e2dea | Crazyinfo/Python-learn | /try/习题/珊.py | 744 | 4 | 4 | '''
# 第二题
class Time():
def __init__(self,hour,minute,second):
self.hour = hour
self.minute = minute
self.second = second
# 第三题
class Date():
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
# 第四题
class Datetime(Date,Time):
pass
'''
'''
# 第五题
class Time():
def __str__(self):
pass
class Date():
def __str__(self):
pass
class Datetime(Date,Time):
pass
print(Time,Date,Datetime)
'''
# 第六题
class Time():
def __str__(self):
pass
class Date():
def __str__(self):
pass
class Datetime(Date,Time):
def Date(self):
pass
def Time(self):
pass
|
4a993902e7e1412bce1c4edffbf397a426a400eb | Crazyinfo/Python-learn | /basis/基础/dict.py | 194 | 3.96875 | 4 | m = {5 : 1, 9 : 2, 4: 3}
if 1 in m:
print('Yes')
else:
print('No')
if 5 in m:
print('Yes')
else:
print('No')
m[8] = 4
if 8 in m:
print(m.items())
else:
print('No')
|
5199e375852e970c925414edd8f6ceea3be216d8 | Crazyinfo/Python-learn | /basis/高级特性/迭代.py | 330 | 3.921875 | 4 | d = {'a': 1,'b': 2,'c': 2}
for m in d:
print(m)
for n in d.values():
print(n)
for x,y in d.items():
print(x,y)
from collections import Iterable
h = isinstance(1233,Iterable) #判断一个对象是否可以迭代
print(h)
for m,n in enumerate([1,2,3,4]):
print(m,n)
for x,y in [(1,2),(3,4),(5,6)]:
print(x,y) |
9e0314bd94c25a0a1b012545cb2047d796a949b1 | true-false-try/Python | /A_Byte_of_Python/lambda_/natural_number.py | 1,551 | 4.21875 | 4 | """
Дано натуральне число n та послідовність натуральних чисел a1, a2,
…, an. Показати всі елементи послідовності, які є
а) повними квадратами;
б) степенями п’ятірки;
в) простими числами.
Визначити відповідні функції для перевірки, чи є число: повним квадратом,
степенню п’ятірки, простим числом.
"""
import random as rn
n = int(input('Write one number for create a length list:'))
lst_step = [rn.randint(1, 11) for i in range(1, n + 1)]
square_number = list(filter(lambda x: (x ** 0.5).is_integer() == True, lst_step))
fifth_power = list(filter(lambda x: (x ** 0.2).is_integer() == True, lst_step))
# this function shows simple numbers
def simple_number():
lst_simple = []
count = 0
for i in range(len(lst_step)):
for j in range(2, lst_step[i] + 1):
if lst_step[i] % j == 0:
count += 1
if count == 1:
lst_simple.append(lst_step[i])
else:
count = 0
continue
count = 0
return lst_simple
print('This is list with random numbers:', lst_step, sep='\n')
print('This is a list of square numbers:', square_number, sep='\n')
print('This is a list of fifth power numbers:', fifth_power, sep='\n')
print('This is a list of simple numbers:', simple_number(), sep='\n')
|
65ed9bd112ebeab025d2f9c3bb6177bdab0f050d | true-false-try/Python | /A_Byte_of_Python/OOP/inheritance/passanger/main.py | 1,869 | 3.671875 | 4 | from random import randint
class Person:
def __init__(self):
self.name = None
self.byear = None
def input(self):
self.name = input('Прізвище: ')
self.byear = input('Рік народження: ')
def print(self):
print(self.name, self.byear, end=' ')
class Passanger(Person):
def __init__(self):
Person.__init__(self)
self.departure_city = None
self.arrival_city = None
self.list_person = []
self.total_list_person = []
def input(self):
Person.input(self)
self.departure_city = input('Місто з якого ви прямуєте: ')
self.arrival_city = input('Місто куди ви прямуєте: ')
# noinspection PyAttributeOutsideInit
self.distance = randint(100, 2001)
self.list_person.extend((self.departure_city, self.arrival_city, self.distance))
def print(self):
print(self.name, self.byear, self.departure_city, self.arrival_city, self.distance)
def price(self):
price_1_km = 0.5
for i in range(len(self.list_person)):
if i == 2:
price_ticket = round((self.list_person[i] * price_1_km), 2)
self.total_list_person.extend([self.name, self.byear, self.departure_city,
self.arrival_city, self.distance, price_ticket])
print('Price is:', price_ticket)
self.list_person.clear()
if __name__ == '__main__':
n = int(input('Введіть скільки пасажірів будуть їхати: '))
for i in range(n):
p = Passanger()
p.input()
p.print()
p.price()
print('List all passanger: ', p.total_list_person, sep='\n')
|
1bc85861d977bb4312e0ff8ed5de02265ad9eb95 | true-false-try/Python | /A_Byte_of_Python/set_()/find_char.py | 1,406 | 3.96875 | 4 | """
Дано рядок з малих латинських літер.
Надрукувати:
a) перші входження літер до рядка, зберігаючи початковий взаємний порядок;
b) всі літери,що входять до рядка не менше двох раз в порядку збіьшення (a - z);
c) всі літери, що входять до рядка по одному разу
"""
string = 'abc abs sda faj'
words = string.split()
together = ''.join(words)
list_couple, list_one, list_first_letter = [], [], []
# a)
def first_letter():
for i in together:
for j in range(97, 123):
if chr(j) == i and i not in list_first_letter:
list_first_letter.append(chr(j))
return list_first_letter
# b) and c)
def couple_and_one():
for i in range(97, 123):
count = 0
for j in together:
if chr(i) == j:
count += 1
if count >= 2:
list_couple.append(chr(i))
if count == 1:
list_one.append(chr(i))
return 'Letters that occur at least 2 times:', \
sorted(list(set(list_couple))), \
'Letters that occur once:', list_one
print('The first occurrence of letters in a line:', first_letter(), sep='\n')
print(*couple_and_one(), sep='\n')
|
19cf04b25a91f1e0ccfe8023cc925cba97bb31dd | true-false-try/Python | /A_Byte_of_Python/file_/file_tasks/real_number/main.py | 1,520 | 3.5625 | 4 | file = open('file_numbers.txt', 'r')
x = [i.rstrip() for i in file]
string = ' '.join(x)
lst = string.split()
convert = [int(i) for i in lst]
# a)
def total():
global lst
return sum([int(i) for i in lst])
# b)
def minus():
global convert
return sum([1 for i in convert if i < 0])
# c)
def last_numb():
global convert
return convert[len(convert) - 1]
# d)
def max_numb():
global convert
return max(convert)
# e)
def min_couple_numb():
global convert
return min([i for i in convert if i > 9])
# f)
def sum_min_max_numb():
global convert
return min([i for i in convert]) + max(i for i in convert if i)
# j)
def first_last():
global convert
return convert[0] - convert[len(convert) - 1]
# h)
def middle_aref():
global convert
return sum([1 for i in convert if i < round(total() / (len(convert) + 1))])
print('sum file:',
total(), sep='\n')
print('count minus:',
minus(), sep='\n')
print('last number:',
last_numb(), sep='\n')
print('max number:',
max_numb(), sep='\n')
print('min couple number:',
min_couple_numb(), sep='\n')
print('min - max:',
sum_min_max_numb(), sep='\n')
print('degree first numb and last numb:',
first_last(), sep='\n')
print('the number of components of a file that are less than the arithmetic mean of all its components:',
middle_aref(), sep='\n')
file.close()
|
6d4671b842d2780d0a28998d856e9663129e0d6f | true-false-try/Python | /A_Byte_of_Python/dictionary_()/dictionary_tasks/car.py | 2,137 | 4.03125 | 4 | """
Відомості про автомобіль складаються з його марки, унікального
номера і прізвища власника. Дано словник, який містить відомості про
декілька автомобілей. Скласти процедури знаходження
a) прізвищ власниківі номерів автомобілей даної марки;
b) кількості автомобілей кожної марки.
"""
cars_dictionary = {'AA3321BE': ['Volvo', 'Solopov'], 'AR33921IO': ['Volvo', 'Korney'],
'AO3312LP': ['Porsche', 'Alehiienko'], 'KA3330II': ['Porsche', 'Dunar'],
'LS3345NP': ['BMW', 'Korney'], 'LM3241PO': ['Mercedes', 'Solopov'],
'LO2234IO': ['Volvo', 'Lopkin'], 'AK4657VS': ['Toyota', 'Volohina'],
'AM33893BI': ['Volga', 'Anroniana'], 'AL4532LO': ['Honda', 'Kanoval']}
# a) this function find last name and number car from input values call car
def find_by_brand():
car_brands = str(input('Enter valid values about brand car: ').lower())
found_car = [(key, value[1]) for key, value in cars_dictionary.items() if value[0].lower() == car_brands]
if any(found_car):
print("I'm finding:", sep='\n')
return found_car
else:
return 'Have not found this brand'
print(find_by_brand(), sep=', ')
print()
# b) this function count how many cars each brand
def count_car():
lst_brands = [cars_dictionary[i][0] for i in cars_dictionary]
lst_all_brands = list(set([cars_dictionary[i][0] for i in cars_dictionary]))
count = [(i, lst_brands.count(i)) for i in lst_all_brands]
n = str(input('Enter "count" if do you want count all brand cars in the dictionary, or "no" if you do not:'))
while n != 'count' or n != 'no':
if 'count' == n.lower():
return count
elif 'no' == n.lower():
return 'End'
else:
n = str(input('Enter correct answer please:'))
print(*count_car(), sep='\n')
|
ee3c93fb3f3b9307aad80df30ca8b2a66007f551 | priiperes/IntroPython | /Aula1.py | 3,357 | 4.0625 | 4 |
#Aula 1
#exercío 1
print('Exercício 1')
print('Se você fizer uma corrida de 10 quilômetros em 43 minutos e 30 segundos, qual será seu tempo médio por milha?')
km=10
milha = km/1.61
tempo=43*60+30
hora= tempo/3600
resultado = hora/milha
print('resultado =',resultado,'h/milha')
print('\n')
print('Qual é a sua velocidade média em milhas por hora?')
velocidade = 1/resultado
print('velocidade =',velocidade,'milha/h')
print('\n')
print('\n')
#exercicio 2
print('Exercício 2')
print('Desde sua varanda você escuta o som do primeiro fogo artificial do reveillon 3 segundos depois de ver a luz, qual a distância?')
#Calcalamos primeiro a distância que os fogos de artificios estão localizados pelo tempo que o som chega
print('\n')
Vsom=343
Vluz=3*10**8
tempo=3
distancia = Vsom*tempo
print('Distancia =', distancia, 'm')
#Agora calculamos o tempo que a luz demora para chegar, baseado na distancia encontrada acima
print('\n')
TempoDaLuz=distancia/Vluz
print('Tempo da Luz =', TempoDaLuz, 's')
print('\n')
print('\n')
#exercicio 3
print('Exercício 3')
print('Ache os zeros da função: y= 3x^2 - 4x -10')
#Para realizar esse calculo, definimos as contantes a, b e c para realizar a formula de baskara
a=3
b=-4
c=-10
#Calculamos Delta
Delta=b*b-(4*a*c)
print('\n')
print('Delta =',Delta)
print('\n')
#calculo das raizes
x1=float((-b + (Delta)**(1/2))/(2*a))
x2=(-b - (Delta)**(1/2))/(2*a)
print('Raiz 1 =',x1)
print('Raiz 2 =',x2)
print('\n')
print('confirmando as raizes encontradas')
print('\n')
y1=a*x1**2+b*x1+c
print('y1= ',y1)
y2=a*x2**2+b*x2+c
print('y2= ',y2)
print('como são proximos de 0, o resultado é compatível')
print('\n')
print('\n')
#exercicio 4
print('Exercício 4')
print('Se, ao meio dia, a sombra de um poste de 5 m de altura tem apenas 50 cm de comprimento no chão, qual o ângulo zenital do sol?')
#O ângulo formado é calculado pelo arcotangente
a=0.5
b=5
AnguloTheta = b/a
print('Angulo Azimute =', AnguloTheta)
print('\n')
print('\n')
#exercicio 5
print('Exercício 5')
print('calcule o seu IMC = M/A^2 (com a massa em Kg e a altura em metros).\n Um valor saudável estara --em geral-- entre 20-25. \n Um bebê de 6 meses gorducho tem 70 cm de comprimento e 11 kg de massa,\n qual o IMC dele?')
#Calculo de Priscyla Peres
M=51
A=1.71
IMC=M/A**A
print('\n')
print('IMC de Priscyla Peres')
print('\n')
print('IMC=', IMC)
print('Como o valor precisa estar entre 20 e 25, o seu IMC está bom e é uma pessoa saudável')
print('\n')
print('IMC do bebê gorducho')
M=11
A=0.7
IMCG=M/A**A
print('IMCG= ', IMCG)
print('\n')
print('\n')
#exercicio
print('Exercício 6')
print('Calcule a velocidade final de um objeto em queda livre a partir de 3 metros de altura \n (sem resistencia do ar). Calcule o tempo que esse objeto demora para cair. \n')
print('Vamos calcular a velocidade final pela equação de Torrichelli independente do tempo \n')
print('Vf^2=V0^2 + 2gd, onde d é a distância e assumimos que g está no sentindo positivo da direção de propagação da particula e V0^2=0\n')
V=0
g=9.8
d=3
Vf=(V**V + 2*g*d)**(1/2)
print('Vf=', Vf, 'm/s \n')
print('Usando a formula, Vf=V0+gt \n')
t=Vf/g
print('t=', t, 's') |
64d01a920fcf73ad8e0e2f55d894029593dc559d | zitorelova/python-classes | /competition-questions/2012/J1-2012.py | 971 | 4.34375 | 4 | # Input Specification
# The user will be prompted to enter two integers. First, the user will be prompted to enter the speed
# limit. Second, the user will be prompted to enter the recorded speed of the car.
# Output Specification
# If the driver is not speeding, the output should be:
# Congratulations, you are within the speed limit!
# If the driver is speeding, the output should be:
# You are speeding and your fine is $F .
# where F is the amount of the fine as described in the table above.
'''
1 to 20 -> 100
21 to 30 -> 270
31 and above -> 500
'''
speed_limit = int(input('Enter the speed limit: '))
speed = int(input('Enter the recorded speed of the car: '))
if speed <= speed_limit:
print('Congratulations, you are within the speed limit!')
else:
if speed - speed_limit <= 20:
fine = 100
elif speed - speed_limit <= 30:
fine = 270
else:
fine = 500
print('You are speeding and your fine is $' + str(fine) + '.')
|
0a58f6868af57dcba6babf48ed32c1a31f8350eb | zitorelova/python-classes | /competition-questions/2017/S2-2017.py | 1,287 | 3.890625 | 4 | """
Input Specification
The first line contains the integer N (1 ≤ N ≤ 100). The next line contains N distinct space-
separated positive integers, where each integer is at most 1 000 000.
Output Specification
Output the N integers in the unique order that Joe originally took the measurements.
Sample Input
8
10 50 40 7 3 110 90 2
Output for Sample Input
10 40 7 50 3 90 2 110
• He started measuring water levels at a low tide, his second measurement was of the water
level at high tide, and after that the measurements continued to alternate between low and
high tides.
• All high tide measurements were higher than all low tide measurements.
• Joe noticed that as time passed, the high tides only became higher and the low tides only
became lower.
"""
N = int(input())
m = [int(x) for x in input().split()]
m.sort()
# # After sorting
# # [2, 3, 7, 10, 40, 50, 90, 110]
if N % 2 == 0:
middle = int(N/2)
else:
middle = int((N+1)/2)
lows = m[:middle][::-1]
highs = m[middle:]
answer = []
for i in range(middle):
try:
answer.append(str(lows[i]))
except:
pass
try:
answer.append(str(highs[i]))
except:
pass
print(' '.join(answer))
# # l = [10, 40, 7, 50, 3, 90, 2, 110]
# # print(l[::-1])
# l = [1, 2, 3, 4, 5] |
b43877784392fe97c441f2998172bd7765d8d1ff | zitorelova/python-classes | /competition-questions/2010/S2-2010.py | 1,893 | 3.53125 | 4 | # Input Specification
# The first line of input will be an integer k (1 ≤ k ≤ 20), representing the number of characters and
# associated codes. The next k lines each contain a single character, followed by a space, followed
# by the binary sequence (of length at most 10) representing the associated code of that character.
# You may assume that the character is an alphabet character (i.e., ‘a’...‘z’ and ‘A’..‘Z’). You may
# assume that the sequence of binary codes has the prefix-free property. On the k + 2nd line is the
# binary sequence which is to be decoded. You may assume the binary sequence contains codes
# associated with the given characters, and that the k + 2nd line contains no more than 250 binary
# digits.
# Output Specification
# On one line, output the characters that correspond to the given binary sequence.
# Sample Input
# 5
# A 00
# B 01
# C 10
# D 110
# E 111
# 00000101111
# Output for Sample Input
# AABBE
# a = int(input())
# decoder = []
# for i in range(a):
# decoder.append(input().split())
# huffmancode = (input())
# huffmancode = [char for char in huffmancode]
# decoded = []
# end = 1
# while len(huffmancode) > 0:
# substr = huffmancode[:end]
# substr = ''.join(substr)
# for i in decoder:
# if substr == i[1]:
# decoded.append(i[0])
# huffmancode = huffmancode[end:]
# end = 0
# end += 1
# print(decoded)
# for i in range(len(decoder)):
k = int(input())
huffman_dict = {}
for i in range(k):
letter = input().split()
huffman_dict[letter[1]] = letter[0]
huffman_code = input()
huffman_decoded = ''
end = 1
while len(huffman_code) > 0:
substr = huffman_code[:end]
if substr in huffman_dict:
huffman_decoded += huffman_dict[substr]
huffman_code = huffman_code[end:]
end = 0
end += 1
print(huffman_decoded)
|
a6a74f456b6c6b484e577de6aefdd5a6e6a4b799 | zitorelova/python-classes | /J1-2020.py | 559 | 3.75 | 4 | """
Input Specification
There are three lines of input. Each line contains a non-negative integer less than 10. The first line
contains the number of small treats, S, the second line contains the number of medium treats, M ,
and the third line contains the number of large treats, L, that Barley receives in a day.
Output Specification
If Barley’s happiness score is 10 or greater, output happy. Otherwise, output sad.
"""
S = int(input())
M = int(input())
L = int(input())
happy = (1*S) + (2*M) + (3*L)
if happy >= 10: print("happy")
else: print("sad") |
6bfea6232f02b525708f2c88cb7a3ad64cb6b13b | Halfkeyboard567/M_mathews_84706_project01_Paint.py | /Paint_C.py | 6,833 | 3.640625 | 4 | #Part C
from graphics import *
class Shape:
def __init__(self, win):
self.win = win
def line(self):
T1 = Text(Point(400, 50), "Line: Enter 2 points")
T1.setSize(8)
T1.draw(self.win)
p1 = self.win.getMouse()
p1.draw(self.win)
p2 = self.win.getMouse()
p2.draw(self.win)
l = Line(p1, p2)
l.draw(self.win)
T1.undraw()
p1.undraw()
p2.undraw()
T2 = Text(Point(400, 50), "Line: Color Line(A-J), u to undo, and q to break")
T2.setSize(8)
T2.draw(self.win)
while True:
k = self.win.checkKey()
if k == "q":
break
elif k == "u":
l.undraw()
break
elif k:
ColorO(k, l)
T2.undraw()
def rectangle(self):
T1 = Text(Point(400, 50), "Rectangle: Enter 2 points")
T1.setSize(8)
T1.draw(self.win)
p1 = self.win.getMouse()
p1.draw(self.win)
p2 = self.win.getMouse()
p2.draw(self.win)
r = Rectangle(p1, p2)
r.draw(self.win)
T1.undraw()
p1.undraw()
p2.undraw()
T2 = Text(Point(400, 50), "Rectangle: Color Shape(0-9), Color Line(A-J), u to undo, and q to break")
T2.setSize(8)
T2.draw(self.win)
while True:
k = self.win.checkKey()
if k == "q":
break
elif k == "u":
r.undraw()
break
elif k:
ColorS(k, r)
ColorO(k, r)
T2.undraw()
def circle(self):
T1 = Text(Point(400, 50), "Circle: Enter point")
T1.setSize(8)
T1.draw(self.win)
p1 = self.win.getMouse()
c = Circle(p1, 50)
c.draw(self.win)
T1.undraw()
T2 = Text(Point(400, 50), "Circle:Color Shape(0-9), Color Line(A-J), u to undo, and q to break")
T2.setSize(8)
T2.draw(self.win)
while True:
k = self.win.checkKey()
if k == "q":
break
elif k == "u":
c.undraw()
elif k:
ColorS(k, c)
ColorO(k, c)
T2.undraw()
def oval(self):
T1 = Text(Point(400, 50), "Oval: Enter 2 points")
T1.setSize(8)
T1.draw(self.win)
p1 = self.win.getMouse()
p2 = self.win.getMouse()
p1.draw(self.win)
p2.draw(self.win)
O = Oval(p1, p2)
O.draw(self.win)
T1.undraw()
p1.undraw()
p2.undraw()
T2 = Text(Point(400, 50), "Oval: Color Shape(0-9), Color Line(A-J), u to undo, and q to break")
T2.setSize(8)
T2.draw(self.win)
while True:
k = self.win.checkKey()
if k == "q":
break
elif k == "u":
c.undraw()
elif k:
ColorS(k, O)
ColorO(k, O)
T2.undraw()
def triangle(self):
T1 = Text(Point(400, 50), "Triangle: Enter 3 points")
T1.setSize(8)
T1.draw(self.win)
p1 = self.win.getMouse()
p1.draw(self.win)
p2 = self.win.getMouse()
p2.draw(self.win)
p3 = self.win.getMouse()
p3.draw(self.win)
t = Polygon(p1, p2, p3)
t.draw(self.win)
T1.undraw()
p1.undraw()
p2.undraw()
p3.undraw()
T2 = Text(Point(400, 50), "Triangle: Color Shape(0-9), Color Line(A-J), u to undo, and q to break")
T2.setSize(8)
T2.draw(self.win)
while True:
k = self.win.checkKey()
if k == "q":
break
elif k == "u":
t.undraw()
elif k:
ColorS(k, t)
ColorO(k, t)
T2.undraw()
def ColorS(C, win):
if C == "0":
win.setFill("white")
elif C == "1":
win.setFill("black")
elif C == "2":
win.setFill("red")
elif C == "3":
win.setFill("blue")
elif C == "4":
win.setFill("yellow")
elif C == "5":
win.setFill("green")
elif C == "6":
win.setFill("orange")
elif C == "7":
win.setFill("purple")
elif C == "8":
win.setFill("pink")
elif C == "9":
win.setFill("gray")
def ColorO(C, win):
if C == "A":
win.setOutline("white")
elif C == "B":
win.setOutline("black")
elif C == "C":
win.setOutline("red")
elif C == "D":
win.setOutline("blue")
elif C == "E":
win.setOutline("yellow")
elif C == "F":
win.setOutline("green")
elif C == "G":
win.setOutline("orange")
elif C == "H":
win.setOutline("purple")
elif C == "I":
win.setOutline("pink")
elif C == "J":
win.setOutline("gray")
def Color(C, win):
if C == "A":
win.setBackground("white")
elif C == "B":
win.setBackground("black")
elif C == "C":
win.setBackground("red")
elif C == "D":
win.setBackground("blue")
elif C == "E":
win.setBackground("yellow")
elif C == "F":
win.setBackground("green")
elif C == "G":
win.setBackground("orange")
elif C == "H":
win.setBackground("purple")
elif C == "I":
win.setBackground("pink")
elif C == "J":
win.setBackground("gray")
def TextS(pt, win):
entry = Entry(pt, 10)
entry.draw(win)
# Go modal: wait until user types Return or Escape Key
while True:
key = win.getKey()
if key == "Return":
break
# undraw the entry and draw Text
entry.undraw()
Text(pt, entry.getText()).draw(win)
win.checkMouse()
def main():
win = GraphWin('Paint', 800, 800)
T1 = Text(Point(400, 25), "keys: l - line, r - rectangle, c - circle, o - oval, t - triangle, q - quit")
T1.setSize(8)
T1.draw(win)
S = Shape(win)
while True:
key = win.checkKey()
if key == "q": # loop exit
break
elif key == "l":
S.line()
elif key == "r":
S.rectangle()
elif key == "c":
S.circle()
elif key == "o":
S.oval()
elif key == "t" :
S.triangle()
elif key:
Color(key, win)
pt = win.checkMouse()
if pt:
TextS(pt, win)
win.close()
if __name__ == '__main__': main()
|
84674ce996ed3ae5e0b13032b05c2803ab6508cd | naveenshukla/OpenQA | /question_processing/question_phrases.py | 326 | 3.875 | 4 | #!/usr/bin/python3 -tt
question_words = ['who','why','where','what','when','how','which','whose','whom', '?', '.', ':', ';', '"', '\'']
def remove(text):
text = text.lower().strip()
if text in question_words:
text = ''
return text
def main():
print(remove(input()))
if __name__ == '__main__':
main()
|
cbbcbf765114f341b973c55c30490ed8984f98bf | zyq507/Pythoncore | /Dict_Test.py | 1,248 | 3.65625 | 4 | phonebook = {'Alice':'2341','Beth':'9102','Cecil':'3258'}
items = [('name','FCK'),('age','21')]
d =dict(items)
print(d)
print(d['name'])#其中的key相当于索引
print(len(d))
print('age' in d)
d['job'] = 'worker'
print(d)
del d['job']
print(d)
k = 'my name is %(name)s, I\'m %(age)s years old'% d
print(k)#字典的key可以做为%s的说明符
x = {'key':'value'}
y = x
x.clear()
print(y)#clear方法会清空x关联的存储空间,y也映射到此存储空间,故亦空
#copy和deepcopy
aa = {'username':'admin','machines':['foo','bar','baz']}
bb = aa.copy()#shallow copy
bb['username'] = 'mlh'
bb['machines'].remove('bar')#原地修改浅复制的内容,原文也会改变
print(aa,'\n',bb)
#使用deepcopy可以解决问题
print({}.fromkeys(['a', 'bb']))#参数是一个list
print(dict.fromkeys(['f','g'],'Hello'))#可以添加一个缺省的参数
print(d.get('name'))#无key时,不会报错
print(d.get('job','N/A'))#可以添加一个参数来赋予缺省值的返回
print(list(d.items()))
print(list(d.keys()))
aaa = {}
aaa.setdefault('name','N/A')#setdefault可以在没有该key时设定默认值
print(aaa)#也可以同get方法在存在该key时获得该值
aaa['name'] = 'Boy'
print(aaa.setdefault('name','N/A'))
|
c7f4cc528ed6497a05e435e7ef3f5ee47e5b3dfc | dechevh/SoftwareUniversity | /Python-Fundamentals/softUni_reception.py | 405 | 3.71875 | 4 | efficiency_one = int(input())
efficiency_two = int(input())
efficiency_three = int(input())
students_count = int(input())
all_employees_per_hour = efficiency_one + efficiency_two + efficiency_three
time_needed = 0
while students_count > 0:
time_needed += 1
if time_needed % 4 == 0:
pass
else:
students_count -= all_employees_per_hour
print(f"Time needed: {time_needed}h.")
|
e64c96b39f822ce75b5b92d0c843248903f9c0ff | University-Assignment/PythonProgramming | /2018037010_7.py | 4,088 | 4.03125 | 4 | '''
# 미션1: 연락처 관리 프로그램
menu = 0
friends = []
while menu != 9:
print("--------------------")
print("1. 친구 리스트 출력")
print("2. 친구추가")
print("3. 친구삭제")
print("4. 이름변경")
print("9. 종료")
menu = int(input("메뉴를 선택하시오: "))
if menu == 1:
print(friends)
elif menu== 2:
name = input("이름을 입력하시오: ")
friends.append(name)
elif menu == 3:
del_name = input("삭제하고 싶은 이름을 입력하시오: ")
if del_name in friends:
friends.remove(del_name)
else:
print("이름이 발견되지 않았음")
elif menu == 4:
old_name = input("변경하고 싶은 이름을 입력하시오: ")
if old_name in friends:
index = friends.index(old_name)
new_name = input("새로운 이름을 입력하시오: ")
friends[index] = new_name
else:
print("이름이 발견되지 않았음")
# 미션2: 연락처 관리 프로그램
def printOption():
print("--------------------")
print("1. 친구 리스트 출력")
print("2. 친구추가")
print("3. 친구삭제")
print("4. 이름변경")
print("9. 종료")
def printList():
global friends
print(friends)
def addFriend():
global friends
name = input("이름을 입력하시오: ")
friends.append(name)
def removeFriend():
global friends
del_name = input("삭제하고 싶은 이름을 입력하시오: ")
if del_name in friends:
friends.remove(del_name)
else:
print("이름이 발견되지 않았음")
def changeName():
global friends
old_name = input("변경하고 싶은 이름을 입력하시오: ")
if old_name in friends:
index = friends.index(old_name)
new_name = input("새로운 이름을 입력하시오: ")
friends[index] = new_name
else:
print("이름이 발견되지 않았음")
menu = 0
friends = []
while menu != 9:
print("--------------------")
printOption()
menu = int(input("메뉴를 선택하시오: "))
if menu == 1:
printList()
elif menu== 2:
addFriend()
elif menu == 3:
removeFriend()
elif menu == 4:
changeName()
# 미션3: tic-tac-toe 게임
board= [[' ' for x in range (3)] for y in range(3)]
while True:
# 게임 보드를 그린다.
for r in range(3):
print(" " + board[r][0] + "| " + board[r][1] + "| " + board[r][2])
if r != 2:
print("---|---|---")
# 사용자로부터 좌표를 입력받는다.
x = int(input("다음 수의 x좌표를 입력하시오: "))
y = int(input("다음 수의 y좌표를 입력하시오: "))
# 사용자가 입력한 좌표를 검사한다.
if board[x][y] != ' ':
print("잘못된 위치입니다. ")
continue
else:
board[x][y] = 'X'
# 컴퓨터가 놓을 위치를 결정한다. 첫 번째로 발견하는 비어있는 칸에 놓는다.
done =False
for i in range(3):
for j in range(3):
if board[i][j] == ' ' and not done:
board[i][j] = 'O';
done = True
break;
# 미션4: 순차탐색 프로그램
data = []
f = open("data.txt", "r") #data가 저장된 디렉토리에서 파일을 읽는다.
# #파일에 저장된 모든 줄을 읽는다.
for line in f.readlines():
#줄바꿈 문자를 삭제한 후에 리스트에 추가한다.
data.append(line.strip())
fileName = input('검색할 파일명을 입력하시오 : ')
success = False
for name in data[0].split(','):
if name == fileName:
success = True
break
print(success)
'''
# Zoom
def selection_sort2(x):
for i in range(len(x) - 1):
x.insert(i, x.pop(x.index(min(x[i: len(x)]))))
return x
array = [180, 165, 175, 170, 160, 171, 150, 162]
selection_sort2(array)
print(array) |
c1507b325a379d1b386e4592e546ec6306ee38a1 | University-Assignment/PythonProgramming | /test.py | 833 | 3.5 | 4 | #변수 x는 원소의 수가 100개인 1차원 배열이다. 변수 x의 원소는 0에서 255까지의 정수를 랜덤하게 갖는다.
# 변수 x를 파이선의 random 모듈을 이용하여 구하시오.
import random
x = []
for i in range(100):
x.append(random.randint(0, 256))
print(x)
# a=[1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0]로 정의된 벡터의 FFT 출력
import numpy as np
import matplotlib.pyplot as plt
a = [1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0]
t = range(len(a))
signal = a
ori_fft = np.fft.fft(signal)
print('original fft', ori_fft)
nomal_fft = ori_fft / len(signal)
print('nomalization fft', nomal_fft)
fft_magnitude = abs(nomal_fft)
print('magnitude fft ', fft_magnitude)
plt.subplot(2, 1, 1)
plt.plot(t, signal)
plt.grid()
plt.subplot(2, 1, 2)
plt.stem(fft_magnitude)
plt.grid()
plt.show() |
5693de8003cd127a82c42b5ee8bb2985a79f045b | shreyasbapat/Astronomy-Code-Camp-Slides | /one.py | 206 | 3.921875 | 4 | def check(num):
if num <= 9:
print("Single Digit")
elif num >9 and num <=99:
print("Double Digit")
else:
print("Others")
if __name__ == "__main__":
num = int(input("Input a number:"))
check(num) |
fbe4f97912ae394e43a5d2b2928ab20297c4fcf8 | escnqh/PracticesWhenLearnPython | /math.py | 516 | 3.796875 | 4 | #在Python中,有两种除法,一种除法是/:
print(10/3)
#/除法计算结果是浮点数,即使是两个整数恰好整除,结果也是浮点数:
print(9/3)
#还有一种除法是//,称为地板除,两个整数的除法仍然是整数:
print(10 // 3)
#整数的地板除//永远是整数,即使除不尽。要做精确的除法,使用/就可以。
#因为//除法只取结果的整数部分,所以Python还提供一个余数运算,可以得到两个整数相除的余数:
print(10%3) |
e85612854387fb68172ad444981ca2590a40d1e3 | escnqh/PracticesWhenLearnPython | /formatting.py | 1,285 | 3.953125 | 4 | #格式化
#最后一个常见的问题是如何输出格式化的字符串。我们经常会输出类似'亲爱的xxx你好!你xx月的话费是xx,余额是xx'之类的字符串,而xxx的内容都是根据变量变化的,所以,需要一种简便的格式化字符串的方式。
#在Python中,采用的格式化方式和C语言是一致的,用%实现,举例如下:
print('hello,%s'%'world')
print('Hi, %s, you have $%d.' % ('Michael', 1000000))
#你可能猜到了,%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。
#常见的占位符有:
# %d 整数
# %f 浮点数
# %s 字符串
# %x 十六进制整数
#其中,格式化整数和浮点数还可以指定是否补0和整数与小数的位数:
print('%2d-%02d' % (3, 1))
print('%.2f' % 3.1415926)
#如果你不太确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串:
print('Age: %s. Gender: %s' % (25, True))
#有些时候,字符串里面的%是一个普通字符怎么办?这个时候就需要转义,用%%来表示一个%:
print( 'growth rate: %d %%' % 7) |
83e3c6fb686616a919d2e28037e1e02cc97fd6cf | x64x6a/ircbot | /ircbot/standard_io.py | 831 | 3.578125 | 4 | '''
This is used to handle stdin and stdout input and output for the library
'''
import time
import sys
import threading
STDOUT_BUFFER = []
def print_stdout_buffer():
'''Continously flushes the stdout buffer'''
global STDOUT_BUFFER
try:
while 1:
if STDOUT_BUFFER:
out = STDOUT_BUFFER[0]
STDOUT_BUFFER = STDOUT_BUFFER[1:]
print >>sys.stdout, out
time.sleep(.001)
except Exception,e:
print >>sys.stderr,"Error in printing to stdout:",e
os._exit(1)
def stdout_print(string):
'''Appends given string to the print/stdout buffer.
To print a string: io.stdout_print
or
standard_io.stdout_print'''
STDOUT_BUFFER.append(string)
def start_io():
'''Starts the input/output buffer flushing'''
t = threading.Thread(target=print_stdout_buffer)
t.start()
|
497835d4aed9639a52e9b17ce039d6f7e2584cc6 | Pasquale-Silv/Bit4id_course | /Some_function/SF1_poppaLista.py | 260 | 3.515625 | 4 | def poppaLista(lista):
"""Poppa l'intera lista passata come argomento."""
for i in range(0, len(lista)):
val_poppato = lista.pop()
print(val_poppato)
print(lista)
list1 = [3, 4, 5, 8]
print(list1)
poppaLista(list1)
|
693c554c403602ca49fb6a852648c4e9547723d7 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/ThirdDay/Loop_ex1.py | 711 | 4.40625 | 4 | items = ["Python", 23, "Napoli", "Pasquale"]
for item in items:
print(item)
print()
for item in items:
print("Mi chiamo {}, vivo a {}, ho {} anni e sto imparando il linguaggio di programmazione '{}'.".format(items[-1],
items[-2],
items[-3],
items[0]))
print()
for item in items:
print("Vediamo ciclicamente cosa abbiamo nella nostra lista:", item)
|
1b6ca4e89dd7d1082eb7d9aba899748ff51c8421 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/SecondDay/es2_numParioDisp.py | 153 | 4.03125 | 4 | num = int(input("Inserisci un numero: "))
if(num % 2 == 0):
print("Il numero", num, " è pari")
else:
print("Il numero", num, " è dispari!") |
52b7ab845ddcc63afb61d533148e64e2077da353 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/TwelfthDay/LC_and_lists/ex5_cifratura.py | 2,149 | 3.859375 | 4 | # Prendi stringa e inverti caratteri della stringa. Per ogni stringa, la ribaltiamo.
# Associare un numero intero a ogni carattere della stringa e separarli con una |pipe| o altro carattere speciale.
# Per associare il numero usa la funzione ord() che restituisce l'equivalente in codice ASCII.
# pipe anche all'inizio e alla fine
import random
# Associazione di un carattere casuale per tutti gli interi generati e per il carattere che li separa.
cifratura = {
111: "ABC", # o
97: "FDS", # a
105: "PQL", # i
99: "OIM", # c
124: "ZNK", # Pipe |
32: "poi", # " "
80: "uyt", # P
115: "rew", # s
113: "qas", # q
117: "dfg", # u
108: "hjk", # l
101: "lmn" # e
}
def inverti_stringa(stringa):
return stringa[::-1]
def cifra(stringa):
stringa2 = ""
for el in stringa:
stringa2 += str(ord(el)) + "|"
return "|" + stringa2
def cifra_random(messaggioConPipe):
mess = messaggioConPipe[1:-1]
daCifrare = mess.split("|")
listaCifrata = []
for elemento in daCifrare:
elemento2 = int(elemento)
if elemento2 in cifratura:
listaCifrata.append(random.choice(cifratura[elemento2]))
return "|" + "|".join(listaCifrata) + "|"
def decifraMess(messCifrato2):
messDec = ""
for lettera in messCifrato2:
for k, v in cifratura.items():
if lettera in v:
messDec += chr(k)
messDec = messDec.replace("|", "")
messDec = inverti_stringa(messDec)
return messDec
def rimuoviPipe(stringa):
return stringa.replace("|", '')
if __name__ == "__main__":
parola = "ciao Pasquale"
parolaRev = inverti_stringa(parola)
messaggioConPipe = cifra(parolaRev)
print(messaggioConPipe)
messCifrato = cifra_random(messaggioConPipe)
print(messCifrato)
print("Messaggio cifrato:", rimuoviPipe(messCifrato))
messDecifrato = decifraMess(messCifrato)
print("Messaggio decifrato:", messDecifrato)
|
4895a53522b4957765e61b27e10239f729b2c2bb | Pasquale-Silv/Bit4id_course | /Some_function/SF9_genNumPrimiDivisa.py | 616 | 3.6875 | 4 | def isPrimo(numInt):
"Restituisce True se un numero è primo, altrimenti False."
for i in range(2, numInt):
if(numInt % i == 0):
return False
return True
def genNumPrimi2func(inizio, fine):
"Raccoglie in un generatore tutti i numeri primi compresi nel range specificato."
while(inizio <= fine):
if(isPrimo(inizio)):
yield inizio
inizio += 1
gen1 = genNumPrimi2func(23, 43)
print(gen1)
print(type(gen1))
for i in gen1:
print(i, end=" ")
print()
gen2 = genNumPrimi2func(100, 201)
for i in gen2:
print(i, end=" ")
|
35a9c81798a968e5306deb13d4587650c65c7e7d | Pasquale-Silv/Bit4id_course | /Course_Bit4id/EleventhDay/Giochi_di_parole/ClasseGiochiDiParole.py | 1,834 | 3.796875 | 4 | class GiochiDiParole():
lista_parole = ["fare", "giocare", "dormire", "fittizio", "lira", "sirena", "fulmine", "polizia", "carabinieri",
"luce", "oscuro", "siluro", "razzo", "pazzo", "sillaba", "tono", "oro", "argento", "moneta",
"panna", "zanna", "simulare", "creare", "mangiare", "rubare", "ridere"]
lista_anagramma = [list(parola) for parola in lista_parole]
def __init__(self, parola):
self.parola = parola
def isPalindroma(self):
parola = self.parola.lower()
parolaContrario = parola[::-1]
if parola == parolaContrario:
return True
else:
return False
def rimario(self):
rime = []
parola = self.parola.lower()
for elemento in self.lista_parole:
if elemento[-3:] == parola[-3:]:
rime.append(elemento)
if (not rime):
print("Non sono state trovate rime corrispondenti alla parola '{}'!".format(self.parola))
else:
print(f"Le rime corrispondenti alla parola '{parola}' sono le seguenti: {rime}")
# def anagramma(self):
# parola = list(self.parola.lower())
# anagrammi = []
# for lettera in parola:
# for
#
# print(f"La parola{self.parola} e {elemento} sono anagrammi!")
# else:
# print("Nessun anagramma!")
if __name__ == "__main__":
parola1 = GiochiDiParole("Salvare")
print(parola1.isPalindroma())
parola1.rimario()
parola2 = GiochiDiParole("AnNA")
print(parola2.isPalindroma())
parola2.rimario()
parola3 = GiochiDiParole("Scarpa")
print(parola3.isPalindroma())
parola3.rimario()
print(GiochiDiParole.lista_anagramma) |
56ce5b83d5ed2b0fb6807d22e52cc0dc9514a9d6 | Pasquale-Silv/Bit4id_course | /Some_function/SF6_factorialWithoutRec.py | 822 | 4.28125 | 4 | def factorial_WithoutRec(numInt):
"""Ritorna il fattoriale del numero inserito come argomento."""
if (numInt <= 0):
return 1
factorial = 1
while(numInt > 0):
factorial *= numInt
numInt -= 1
return factorial
factorial5 = factorial_WithoutRec(5)
print("5! =", factorial5)
factorial4 = factorial_WithoutRec(4)
print("4! =", factorial4)
factorial3 = factorial_WithoutRec(3)
print("3! =", factorial3)
while(True):
num = int(input("Inserisci il numero di cui vuoi vedere il fattoriale:\n"))
factorialNum = factorial_WithoutRec(num)
print("{}! = {}".format(num, factorialNum))
risposta = input("Desideri ripetere l'operazione?\nPremi S per confermare, qualunque altra cosa per annullare.\n").upper()
if(risposta != "S"):
break
|
878f5bb5efec177a0ae72b5a33eca20889dabb05 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FifthDay/DictComprehension_DC.py | 107 | 3.84375 | 4 | word = 'dictionary'
letter_count = {letter:word.count(letter) for letter in word}
print(letter_count)
|
d1a68267f5fa87fcaf1726fc05579e5db9965380 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/SeventhDay/Gestione_delle_eccezioni/ecc1.py | 645 | 4 | 4 | # try
# except
# else This executes ONLY if no exception is raised
# finally Viene eseguito sempre
print("Devi dividere due numeri")
num1 = int(input("Scegli il primo numero:\n"))
num2 = int(input("Scegli il secondo numero:\n"))
try:
res = num1 / num2
print(res)
except (ZeroDivisionError):
print("Eccezione:", ZeroDivisionError, ", completamente gestita! Bravo!")
else:
print("else: Solo se va tutto bene")
finally:
print("finally sempre presente !")
print("poichè hai gestito l'eccezione il programma continua la sua esecuzione fin qui!")
print("Complimenti!")
|
c66f129442daf2ee1efacb2a1549dabcde4018c3 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FifthDay/ifAssign.py | 334 | 3.765625 | 4 | # if ternario
età = int(input("Qual è la tua età?"))
stato = "maggiorenne" if (età >= 18) else "minorenne, vai dalla mammina"
print("Hai", età, "anni...", stato)
# ("no", "yes")[True] ------> (0, 1) nella tupla, quindi accedi al valore corrispondente a False(0) o True(1)
print("Ciao Pasquale" if(True) else "")
|
716636aa9bcd32032127d3c4be3050b98d876481 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FourthDay/funz_alt_print.py | 574 | 3.71875 | 4 | animal = "dog"
animals = ["dog", "cat", "mouse", "horse", "turtle"]
# Sono placeholder
# %s s sta per string
# %d d sta per digit(cifra)
print("I have a %s" % animal)
print("I have a %s, a %s and a %s." % (animals[0], animals[1], animals[-1])) # Passi gli argomenti come tuple
number = 23
numbers = [23, 25, 26, 44, 33, 3.8]
print("My age is %d years old." % number)
print("My age is %d, my favourite number is %d and a float is like %f.Good luck by now." %(numbers[0], numbers[2], numbers[-1]))
# Puoi anche mischiare i vari placeholder %s, %d
|
ed1208ad2fadaa5406721bf32b38179cef46e1bf | Pasquale-Silv/Bit4id_course | /Course_Bit4id/SeventhDay/Gestione_delle_eccezioni/ecc4.py | 712 | 3.8125 | 4 | nomi = ["Pasquale", "Alfonso", "Luca"]
for nome in nomi:
print(nome)
risp = int(input("\nQuanti nomi presenti nella lista vuoi vedere?\n"))
try:
for i in range(0, risp):
print(nomi[i])
except (IndexError): # Se non specifichi nessun tipo di errore, Python catturerà tutti i tipi d'errore sollevabili(portata generale)
print("Sei andato fuori dal range degli indici della lista!")
print("Numero massimo di nomi in lista:", len(nomi))
else:
print("Qua ci arrivi solo se va tutto bene !")
finally:
print("Io sono l'onnipresente finally ! mi vedrai sempre!")
print("\nQua non ci arrivi se non gestisci tutte le possibili eccezioni verificabili!")
|
54ceb93532b9046a2474e55a4de058c4c20d4b53 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FourthDay/ex1_List.py | 288 | 4.0625 | 4 | names = ["Pasquale", "Bruno", "Lucia", "Antonio", "Giacomo"]
while(len(names) >= 3):
print("La stanza è affollata, liberare!")
print("Via", names.pop())
if(len(names) < 3):
print("La stanza non è affollata!")
print("\nPersone in stanza:", names, ", ottimo!")
|
ceb9862e7d277490de90854f070afe9daab3d9e8 | Pasquale-Silv/Bit4id_course | /Some_function/kata2_reverseWords2.py | 301 | 3.6875 | 4 | def reverse_words(str):
newStr = []
for i in str.split(' '):
newStr.append(i[::-1])
return ' '.join(newStr)
primo = reverse_words("La vita è bella! vero?")
print(primo)
secondo = reverse_words('double spaced words') #, 'elbuod decaps sdrow')
print(secondo)
|
c32334bce0e237b3ad2dac4de7efeb73cdbfb123 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FourthDay/ex5_SortingIntList.py | 808 | 4.5 | 4 | nums = [100, -80, 3, 8, 0]
print("Lista sulla quale effettueremo le operazioni:", nums)
print("\nOriginal order:")
for num in nums:
print(num)
print("\nIncreasing order::")
for num in sorted(nums):
print(num)
print("\nOriginal order:")
for num in nums:
print(num)
print("\nDecreasing order:")
for num in sorted(nums,reverse=True):
print(num)
print("\nOriginal order:")
for num in nums:
print(num)
print("\nReverse-positional order:")
nums.reverse()
for num in nums:
print(num)
nums.reverse()
print("\nOriginal order:")
for num in nums:
print(num)
print("\nPermanent increasing order:")
nums.sort()
for num in nums:
print(num)
print("\nPermanent decreasing order:")
nums.sort(reverse=True)
for num in nums:
print(num)
|
1215b573ac6647498439014f1d3b6062d0966c7c | Pasquale-Silv/Bit4id_course | /Course_Bit4id/TenthDay/OOP7.py | 1,237 | 3.5 | 4 | class Gatto():
tipo="felino" # Variabile/Attributo di classe
def __init__(self, nome, anni, fidanzato=False, padrone=None):
self.nome = nome
self.anni = anni
self.fidanzato = fidanzato
self.padrone = padrone
g1 = Gatto("Fuffy", 3)
g2 = Gatto("Ciccy", 6, fidanzato=True)
g3 = Gatto("Annabelle", 2, False, "Giulio")
print(Gatto.tipo)
print(g1.tipo)
print(g2.tipo)
print(g3.tipo)
print("\nMutando la variabile di classe mediante istanza, essa muterà solo per l'oggetto in questione:")
g2.tipo = "tuccino"
print(Gatto.tipo)
print(g1.tipo)
print(g2.tipo)
print(g3.tipo)
print("\nMutando la variabile di classe utilizzando la classe stessa, "
"cambierò anche tutte le variabili di tutte le istanze future e già presenti,"
"tranne di quelle sovrascritte già, come nel precedente caso di g2:")
Gatto.tipo = "cluster"
print(Gatto.tipo)
print(g1.tipo)
print(g2.tipo)
print(g3.tipo)
print("\nAdesso vediamo se i gatti sono fidanzati:")
print(g1.fidanzato)
print(g2.fidanzato)
print(g3.fidanzato)
print("\nAdesso vediamo chi sono i padroni dei gatti:")
print(g1.padrone)
print(g2.padrone)
print(g3.padrone)
|
82c05807574232ec277e3779dfea98b9f1f251f1 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FifthDay/FunctionsIntro/ex_func2.py | 444 | 3.78125 | 4 | def writeFullName(firstname, lastname):
print("Hello %s %s, are you ok?" % (firstname, lastname))
writeFullName("Pasquale", "Silvestre")
writeFullName("Giulio", "Di Clemente")
writeFullName("Armando", "Schiano di Cola")
print("------------------------------------------------------")
def sum2num(num1, num2):
sum = num1 + num2
print("The sum of the inserted numbers is %d" % sum)
sum2num(8, 10)
sum2num(10, 11)
sum2num(30,71)
|
5329f13a9b2a3d52451e79d8ece8b90512aaf037 | Pasquale-Silv/Bit4id_course | /Some_function/SF7_factorialWithRec.py | 274 | 4 | 4 | def factorialWithRec(numInt):
if(numInt <= 1):
return 1
factorial = numInt * factorialWithRec(numInt - 1)
return factorial
factorial5 = factorialWithRec(5)
print("5! =", factorial5)
factorial4 = factorialWithRec(4)
print("4! =", factorial4)
|
94fd34899c3c92b34e5fdcae999928a0573b9c1f | mariahfernnn/udemy-python | /copying.py | 230 | 4.03125 | 4 | # EXERCISE: Stop Copying Me - While Loop
# Repeat user input until they say the magic word/phrase
copy = input("Are we there yet? ")
while copy != "I'll let you know when":
print(copy)
copy = input()
print("Yes, we're here!") |
35dc8158e1cecf78e95b9ea0ea23f3da26f3355a | nj137/Fee-estimation | /fee_estimate.py | 2,868 | 4 | 4 | #Program to estimate the fees for a course
print "Fees to be paid:"
#List of fees to be paid
fees=['application fees','exam fees']
#Exam fee structure
exam_fees={'Nationality':['Indian','Foreign','NRI','SAARC'],'Courses':['Ayurveda','Dental','Medical'],'Level':['UG','UG-Diploma','PG']}
#Application fee structure
application_fees={'Nationality':['Indian','Foreign'],'Courses':['Ayurveda','Dental','Medical'],'Level':['UG','UG-Diploma','PG']}
print "1."+fees[0]+"\n"+"2."+fees[1]
#select fees to be paid
select=int(raw_input("Select the type:"))
#j - initialization variable used for printing
j=0
if select == 2:
#Exam fees
#select nationality and print the choices
for i in exam_fees['Nationality']:
j=j+1
print str(j)+"."+str(i)
nation=int(raw_input("Select the type:"))
j=0
#select course and print the choices
for i in exam_fees['Courses']:
j=j+1
print str(j)+"."+str(i)
j=0
#select level and print the choices
course=int(raw_input("Select:"))
for i in exam_fees['Level']:
j=j+1
print str(j)+"."+str(i)
level=int(raw_input("Select the type:"))
if nation == 1 :
amount=400
elif nation == 2:
amount=100
elif nation == 3:
amount=600
else:
amount=600
print "Exam fees to be paid:"+str(amount)
elif select == 1:
#Application fees
#select nationality and print the choices
for i in application_fees['Nationality']:
j=j+1
print str(j)+"."+str(i)
nation=int(raw_input("Select the type:"))
j=0
if nation == 1:
#Indian
#select course and print the choices
for i in exam_fees['Courses']
j=j+1
print str(j)+"."+str(i)
course=int(raw_input("Select:"))
j=0
#select level and print the choices
for i in exam_fees['Level']:
j=j+1
print str(j)+"."+str(i)
level=int(raw_input("Select the type:"))
if level == 1:
amount=200
elif level == 2:
amount=300
else:
amount=500
else:
#Foreign
#select course and print the choices
for i in exam_fees['Courses']:
j=j+1
print str(j)+"."+str(i)
course=int(raw_input("Select:"))
j=0
#select level and print the choices
for i in exam_fees['Level']:
j=j+1
print str(j)+"."+str(i)
level=int(raw_input("Select the type:"))
if level == 1:
amount=400
elif level == 2:
amount=400
else:
amount=700
print "Application fees to be paid is:"+str(amount)
else:
#Invalid choice
#Start selection again
print "Invalid choice made.Start selection again!"
|
88cb690799b6fd6aa32ced1feab805eec6aaefd6 | Azureki/LeetCode | /lc19.py | 615 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head.next:
return None
hk = west = head
for i in range(n):
hk = hk.next
if not hk:
return head.next
while hk.next:
hk = hk.next
west = west.next
west.next = west.next.next
return head
|
4309f01c9e87cf50157393eeaea2857980856d77 | Azureki/LeetCode | /lc892.py | 1,187 | 3.859375 | 4 | '''
之前有道题求投影,这个是求表面积,因此需要考虑凹的情况。
上下(也就是平行于xy平面)容易,依然是投影。
平行于yz、xz平面的分成两部分:
1. 先求周围一圈
2. 再求被挡住的
'''
class Solution:
def surfaceArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid[0])
xy = sum(v > 0 for row in grid for v in row) * 2
front = sum(x for x in grid[n - 1])
back = sum(x for x in grid[0])
left = sum(grid[i][0] for i in range(n))
right = sum(grid[i][n - 1] for i in range(n))
for i in range(n - 1):
# front to back
front += sum(max(grid[i][j] - grid[i + 1][j], 0) for j in range(n))
# back to front
back += sum(max(grid[i + 1][j] - grid[i][j], 0) for j in range(n))
left += sum(max(grid[j][i + 1] - grid[j][i], 0) for j in range(n))
right += sum(max(grid[j][i] - grid[j][i + 1], 0) for j in range(n))
return xy + front + back + left + right
s = Solution()
grid = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
print(s.surfaceArea(grid))
|
101e3174916e5959999f8dc9aeb9f63d6e058415 | Azureki/LeetCode | /lc938. Range Sum of BST.py | 871 | 3.546875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from bisect import bisect_left
class Solution:
def dfs(self, root, lst):
if not root:
return
self.dfs(root.left, lst)
lst.append(root.val)
self.dfs(root.right, lst)
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
lst = []
self.dfs(root, lst)
lo = bisect_left(lst, L)
hi = bisect_left(lst, R)
return sum(lst[lo:hi + 1])
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.left.left = TreeNode(3)
root.left.right = TreeNode(7)
L = 7
R = 15
s = Solution()
print(s.rangeSumBST(root, L, R))
|
74274ba211d24f26d6056d52df0ebe385434af5b | Azureki/LeetCode | /lc888.py | 416 | 3.5625 | 4 | class Solution:
def fairCandySwap(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
sumA=sum(A)
sumB=sum(B)
dif=sumA-sumB
tem=int(dif/2)
A=set(A)
B=set(B)
for a in A:
if a-tem in B:
return [a,a-tem]
A = [1,2]
B = [2,3]
s=Solution()
res=s.fairCandySwap(A,B)
print(res) |
895c3d7d11a6584c5eb83c6ea1519b25988c48c8 | Azureki/LeetCode | /lc167. Two Sum II - Input array is sorted.py | 547 | 3.546875 | 4 | class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left = 0
right = len(numbers) - 1
while left < right:
tem = numbers[left] + numbers[right]
if tem > target:
right -= 1
elif tem < target:
left += 1
else:
return [left + 1, right + 1]
nums = [2, 7, 11, 15]
target = 9
s = Solution()
print(s.twoSum(nums, target))
|
b8cb0d6f5da2b6177bbb78304070827be4d6f6e1 | rachelyeshurun/papercutting | /connect.py | 10,035 | 3.5 | 4 | ''' connect all the black components of the image and thicken the connecting paths
'''
import errno
import os
import sys
import numpy as np
import cv2
from utils import show_image
import numpy as np
import cv2
from pprint import pprint
# The following class is based on answer by Boaz Yaniv here: https://stackoverflow.com/questions/5997189/how-can-i-make-a-unique-value-priority-queue-in-python
# I need to wrap the simple heap q with a set so that I can update priority. So we implement a 'priority set'
import heapq
class PrioritySet(object):
def __init__(self):
self.heap = []
self.set = set()
def add(self, d, pri):
if not d in self.set:
heapq.heappush(self.heap, (pri, d))
self.set.add(d)
else:
# if pixel is already in the unvisited queue, just update its priority
prevpri, d = heapq.heappop(self.heap)
heapq.heappush(self.heap, (pri, d))
def get(self):
pri, d = heapq.heappop(self.heap)
self.set.remove(d)
return d, pri
def is_empty(self):
return len(self.set) == 0
def print(self):
print ('currently unvisited pixels with their priority (distance):')
pprint(self.heap)
# Using some of this code as a basis, but need to change a lot of things
# http://www.bogotobogo.com/python/python_Dijkstras_Shortest_Path_Algorithm.php
# Create 'distance' (sum of intensities) image - inf
# Create 'prev' image (to get path)
# Find the smallest component, store the label number of the smallest component - call it the current component
# Get border pixels of current component
# Create a list of tuples: (coordinates
# Heapify border pixels (this is the Q) with infinite distance
# heapq to store unvisited vertices (pixels) with their distance (sum of intensities).
# while Q is not empty
# extract the minimum distance unvisited pixel (call it the 'current pixel')
# for each of the 8 neighboring pixels:
# if neigbouur belongs to another component - stop algorithm! we found the path.
# if neighbour belongs to current component - skip
# calculate the neighbour's distance from the current pixel by adding the current pixel's distance with the neighbour's intensity value
# if the neighbour's calculated distance is less than its current distance, then update its distance.
# also add to the priority set (update if already there)
class ComponentConnector(object):
def __init__(self, binary_image, intensity_image):
self.current_image = binary_image
self.intensities = intensity_image
self.rows = binary_image.shape[0]
self.cols = binary_image.shape[1]
self.distances = np.ndarray((self.rows, self.cols, 2), dtype = np.uint64)
self.prev_array = np.ndarray((self.rows, self.cols, 2), dtype = np.uint64)
self.current_component_mask = np.zeros_like(intensity_image)
self.other_component_mask = np.zeros_like(intensity_image)
self.unvisited = PrioritySet()
self.path_end = (0,0)
def connect_and_thicken(self):
num_components = self.connect_smallest_component()
while num_components > 1:
num_components = self.connect_smallest_component()
return self.current_image
def connect_smallest_component(self):
# inspired by https://stackoverflow.com/questions/47055771/how-to-extract-the-largest-connected-component-using-opencv-and-python
# initialize the distance and prev_array (for the path)
self.distances = np.ones((self.rows, self.cols), np.uint64) * sys.maxsize
self.prev_array = np.zeros((self.rows, self.cols, 2), dtype = np.uint64)
while True:
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(cv2.bitwise_not(self.current_image),
connectivity=8, ltype=cv2.CV_32S)
print('num_labels\n', num_labels)
# print('labels\n', labels, labels.shape)
print('stats\n', stats, stats.shape)
# print('centroids\n', centroids, centroids.shape)
# get label of smallest componenent (note - the first stat is the background, so look at rows starting from 1)
smallest_label = 1 + np.argmin(stats[1:, cv2.CC_STAT_AREA])
print('smallest label: ', smallest_label)
area = stats[smallest_label, cv2.CC_STAT_AREA]
x = stats[smallest_label, cv2.CC_STAT_LEFT]
y = stats[smallest_label, cv2.CC_STAT_TOP]
if area == 1:
# fill in any components with area 1
self.current_image[y, x] = 0
show_image(self.current_image, 'filled hole?')
else:
break
if num_labels < 3:
print('done')
return 1
# get border pixels of smallest label -
self.other_component_mask = np.zeros_like(self.intensities)
self.other_component_mask[np.logical_and(labels != smallest_label, labels != 0)] = 255
self.current_component_mask = np.zeros_like(self.intensities)
self.current_component_mask[labels == smallest_label] = 255
# show_image(self.other_component_mask, 'other_components_mask')
# show_image(self.current_component_mask, 'current_components_mask')
contourImg, contours, hierarchy = cv2.findContours(self.current_component_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# mask = np.zeros_like(bin_inverted)
# cv2.drawContours(mask, contours, -1, (255), 1)
# show_image(mask, 'contourImg')
# add the component border pixels to the unvisited set of vertices (pixels)
# todo: get a run time error here if the area is 1 pixel ..
borderList = [tuple(c) for c in np.vstack(contours).squeeze()]
self.unvisited = PrioritySet()
for coord in borderList:
self.unvisited.add((coord[1], coord[0]), self.intensities[coord[1], coord[0]])
self.unvisited.print()
while not self.unvisited.is_empty():
current_pixel, distance = self.unvisited.get()
row, col = current_pixel # coordinates from contour are col, row not row, col ...
# print('current pixel (row, col, distance):', row, col, distance)
# check out the neighbours
if row > 0 and col > 0:
other_component = self.evaluate_neighbour(row, col, distance, row - 1, col - 1)
if other_component:
break
if row > 0:
other_component = self.evaluate_neighbour(row, col, distance, row - 1, col)
if other_component:
break
if row > 0 and col < self.cols - 1:
other_component = self.evaluate_neighbour(row, col, distance, row - 1, col + 1)
if other_component:
break
if col < self.cols - 1:
other_component = self.evaluate_neighbour(row, col, distance, row, col + 1)
if other_component:
break
if row < self.rows - 1 and col < self.cols - 1:
other_component = self.evaluate_neighbour(row, col, distance, row + 1, col + 1)
if other_component:
break
if row < self.rows - 1:
other_component = self.evaluate_neighbour(row, col, distance, row + 1, col)
if other_component:
break
if row < self.rows - 1 and col > 0:
other_component = self.evaluate_neighbour(row, col, distance, row + 1, col - 1)
if other_component:
break
if col > 0:
other_component = self.evaluate_neighbour(row, col, distance, row, col - 1)
if other_component:
break
r, c = self.path_end
print ('path end:', r, c)
# print ('prev array', self.prev_array)
# todo: colour the path pixels in black (update the current image)
while not self.current_component_mask[r, c]:
# print('current comp mask', self.current_component_mask[r, c])
self.current_image[r, c] = 0
r, c = self.prev_array[r, c]
# print('prev (row, col)', r, c)
# show_image(self.current_image, 'updated with path')
print ('prev array', self.prev_array)
# todo: thicken the path .. (update the current image)
return num_labels - 2
def evaluate_neighbour(self, row, col, distance, neighbour_row, neighbour_col):
# print('eval neighbour', row,col, neighbour_row, neighbour_col)
if self.current_component_mask[neighbour_row, neighbour_col]:
# print('not a neighbour.. on same component', neighbour_row, neighbour_col)
return False
if self.other_component_mask[neighbour_row, neighbour_col]:
print('reached another component!!', neighbour_row, neighbour_col)
self.path_end = (row, col)
return True
# print('distance: ', distance, self.intensities[neighbour_row, neighbour_col])
sum = distance + np.uint64(self.intensities[neighbour_row, neighbour_col])
# print ('sum, current distance of neighbour', sum, self.distances[neighbour_row, neighbour_col])
if sum < self.distances[neighbour_row, neighbour_col]:
self.distances[neighbour_row, neighbour_col] = sum
# print('adding row, col to path', row, col)
self.prev_array[neighbour_row, neighbour_col] = (row, col)
self.unvisited.add((neighbour_row, neighbour_col), sum)
# print('updated path', neighbour_row, neighbour_col, '<--:', self.prev_array[neighbour_row, neighbour_col])
return False
|
d67ecfdeaa6a10e83058d5bf4a2d160abaa8a5a0 | odiepus/PLP6 | /p6.py | 3,234 | 3.71875 | 4 | import re
str = "( + (+ 3 2) (- 7 3))"
global lastLeftParen
lastLeftParen = 0
global lastRightParen
lastRightParen = 0
class Error(Exception):
pass
class OperationError(Error):
pass
class OperandError(Error):
pass
def tokenize_str(input_str):
new_str = input_str.replace(" ", "")
new_str = new_str.replace("or", "|")
new_str = new_str.replace("and", "&")
temp_tok = re.findall(r"([^.])|[.]", new_str)
return temp_tok
def prefixEval(op, op1, op2):
if op is "+":
return int(op1) + int(op2)
elif op is "-":
return int(op1) - int(op2)
elif op is "*":
return int(op1) * int(op2)
elif op is "/":
return int(op1) / int(op2)
elif op is "&":
x = int(op1)
y = int(op2)
return x & y
elif op is "|":
x = int(op1)
y = int(op2)
return x | y
elif op is ">":
return int(op1) > int(op2)
elif op is "<":
return int(op1) < int(op2)
def parseTokList(tok_list):
global answer
global lastLeftParen
global lastRightParen
for i in tok_list:
if i is "(":
lastLeftParen += 1
tok_list.pop(0)
answer = parseTokList(tok_list)
elif i is "-":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i is "+":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i is "*":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i is "/":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i is "&":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i is "|":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i.isdigit():
return i
elif i is ")":
lastRightParen += 1
tok_list.pop(0)
return answer
def prefixReader(str):
print(">", str)
str = str.replace(" ", "")
parens = re.search(r"\(\(", str)
if parens is not None:
try:
raise OperandError
except OperandError:
print("Expect operator after each left parenthesis")
else:
tok_list = tokenize_str(str)
result = parseTokList(tok_list)
print(result)
print(3 | 4)
prefixReader(str)
|
5670d0bec92648eea1b37bc852ec858de9dce2dd | a1ip/python-learning | /lutz.LearningPython/script1.py | 307 | 3.609375 | 4 | #!/usr/bin/env python3
# Первый сценарий на языке Python
import sys # Загружает библиотечный модуль
print(sys.platform)
print(2 ** 100) # Возводит число 2 в степень 100
x = 'Spam!'
print(x * 8) # Дублирует строку
input ()
|
6da48b1d055c81f33d761c13c3ceef41133231bb | a1ip/python-learning | /phyton3programming/1ex4.awfulpoetry2_ans.py | 1,576 | 4.1875 | 4 | #!/usr/bin/env python3
"""
добавьте в нее программный код, дающий пользователю возможность определить количество выводимых строк (от 1 до 10 включительно),
передавая число в виде аргумента командной строки. Если программа вызывается без аргумента,
она должна по умолчанию выводить пять строк, как и раньше.
"""
import random
#tuple (кортежи) - относятся к разряду неизменяемых объектов
t_art=('the','a','an') #article, артикли
t_noun=('cat', 'dog', 'man', 'woman') #существительные
t_verb=('sang', 'ran', 'jumped') #глагол
t_adv=('loudly', 'quietly', 'well', 'badly') #adverb, наречие
max=5
while True:
line = input("enter a number of row or Enter to finish: ")
if line:
try:
max = int(line)
except ValueError as err:
print(err)
continue
else:
break
print ("max=",max)
if max == 0:
max=5
i = 0
l=()
while i < max:
if (random.randint(1,2))==1:
l=random.choice(t_art)
l=l+" "+random.choice(t_noun)
l=l+" "+random.choice(t_verb)
l=l+" "+random.choice(t_adv)
else:
l=random.choice(t_art)
l=l+" "+random.choice(t_noun)
l=l+" "+random.choice(t_verb)
print(l)
i+=1
|
2fbbc1a17133c74dd37c612200ddee48a0b2c4ca | a1ip/python-learning | /lutz.LearningPython/P1129.py | 923 | 3.890625 | 4 | #!/usr/bin/env python3
registry = {}
def register(obj): # Декоратор функций и классов
registry[obj.__name__] = obj # Добавить в реестр
return obj # Возвращает сам объект obj, а не обертку
@register
def spam(x):
return(x ** 2) # spam = register(spam)
@register
def ham(x):
return(x ** 3)
@register
class Eggs: # Eggs = register(Eggs)
def __init__(self, x):
self.data = x ** 4
def __str__(self):
return str(self.data)
print('Registry:')
for name in registry:
print(name, '=>', registry[name], type(registry[name]))
print('\nManual calls:')
print(spam(2)) # Вызов объекта вручную
print(ham(2)) # Вызовы не перехватываются декоратором
X = Eggs(2)
print(X)
print('\nRegistry calls:')
for name in registry:
print(name, '=>', registry[name](3)) # Вызов из реестра
|
9a261241acebb6fe2d50116cd6227f22c9571b1b | a1ip/python-learning | /empireofcode.com/adamantite_mine_1MostNumbers.py | 1,034 | 3.71875 | 4 | #!/usr/bin/env python3
def most_difference(*args):
if len(args) > 0:
nums=sorted(args)
min=nums[0]
max=nums[-1]
print (max,'-',min,'=',round(max-min,3))
return round(max-min,3)
return 0
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
##def almost_equal(checked, correct, significant_digits):
## precision = 0.1 ** significant_digits
## return correct - precision < checked < correct + precision
##assert almost_equal(most_difference(1, 2, 3), 2, 3), "3-1=2"
##assert almost_equal(most_difference(5, 5), 0, 3), "5-5=0"
##assert almost_equal(most_difference(10.2, 2.2, 0.00001, 1.1, 0.5), 10.199, 3), "10.2-(0.00001)=10.19999"
##assert almost_equal(most_difference(), 0, 3), "Empty"
assert most_difference(1, 2, 3) == 2
assert most_difference(5, -5) == 10
assert most_difference(10.2, -2.2, 0, 1.1, 0.5) == 12.4
assert most_difference() == 0
assert most_difference(-0.036, -0.11, -0.55, -64.0)
|
445aafce7f87fa1181a00366875fe06bb8ea8a24 | a1ip/python-learning | /phyton3programming/sort.py | 347 | 3.796875 | 4 | #!/usr/bin/env python3
numbers = [9,6,2,4,5,1]
print(numbers)
#Сортировка
i=0
while i<len(numbers):
j=0
print("")
while j<len(numbers)-i-1:
print(i,j)
#
if numbers[j]>numbers[j+1]:
#
tmp=numbers[j]
numbers[j]=numbers[j+1]
numbers[j+1]=tmp
print(numbers)
j+=1
#
i+=1
print(numbers)
|
ecad1b1fc73e3f4a21f139b7702cca8f2a293045 | a1ip/python-learning | /lutz.LearningPython/tester.py | 1,436 | 3.796875 | 4 | ##tester func
"""
def tester(start):
state = start # Обращение к нелокальным переменным
def nested(label): # действует как обычно
nonlocal state
print(label, state) # Извлекает значение state из области
state += 1
return nested
"""
#tester class
"""
class tester: # Альтернативное решение на основе классов (Часть VI)
def __init__(self, start): # Конструктор объекта,
self.state = start # сохранение информации в новом объекте
def nested(self, label):
print(label, self.state) # Явное обращение к информации
self.state += 1 # Изменения всегда допустимы
"""
#tester class as func
"""
class tester:
def __init__(self, start):
self.state = start
def __call__(self, label): # Вызывается при вызове экземпляра
print(label, self.state) # Благодаря этому отпадает
self.state += 1
"""
#tester func as user func
def tester(start):
def nested(label):
print(label, nested.state) # nested – объемлющая область видимости
nested.state += 1 # Изменит атрибут, а не значение имени nested
nested.state = start # Инициализация после создания функции
return nested
|
a3982626451b29e21a6077cbf8c0b7be10fbc31b | a1ip/python-learning | /lutz.LearningPython/part3ex1c.py | 181 | 3.59375 | 4 | #!/usr/bin/env python3
S='t s'
L=[]
for x in S:
print ('ASCII code for symbol', x, '=', ord(x))
L.append(ord(x))
print ("\nlist for S as ASCII code:", L)
#or list(map(ord, S))
|
efba9a36610e4837f4723d08518a5255da5a881a | TonyZaitsev/Codewars | /8kyu/Remove First and Last Character/Remove First and Last Character.py | 680 | 4.3125 | 4 | /*
https://www.codewars.com/kata/56bc28ad5bdaeb48760009b0/train/python
Remove First and Last Character
It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.
*/
def remove_char(s):
return s[1:][:-1]
/*
Sample Tests
Test.describe("Tests")
Test.assert_equals(remove_char('eloquent'), 'loquen')
Test.assert_equals(remove_char('country'), 'ountr')
Test.assert_equals(remove_char('person'), 'erso')
Test.assert_equals(remove_char('place'), 'lac')
Test.assert_equals(remove_char('ok'), '')
*/
|
0c17db71399217a47698554852206d60743ef93e | TonyZaitsev/Codewars | /7kyu/Reverse Factorials/Reverse Factorials.py | 968 | 4.375 | 4 | """
https://www.codewars.com/kata/58067088c27998b119000451/train/python
Reverse Factorials
I'm sure you're familiar with factorials – that is, the product of an integer and all the integers below it.
For example, 5! = 120, as 5 * 4 * 3 * 2 * 1 = 120
Your challenge is to create a function that takes any number and returns the number that it is a factorial of. So, if your function receives 120, it should return "5!" (as a string).
Of course, not every number is a factorial of another. In this case, your function would return "None" (as a string).
Examples
120 will return "5!"
24 will return "4!"
150 will return "None"
"""
def reverse_factorial(num):
f = num
n = 1
while n <= f:
f /= n
n += 1
return "None" if f != 1 else str(n-1) + "!"
"""
Sample Tests
test.assert_equals(reverse_factorial(120), '5!')
test.assert_equals(reverse_factorial(3628800), '10!')
test.assert_equals(reverse_factorial(150), 'None')
"""
|
3d35471031ccadd2fc2e526881b71a7c8b55ddc0 | TonyZaitsev/Codewars | /8kyu/Is your period late?/Is your period late?.py | 1,599 | 4.28125 | 4 | """
https://www.codewars.com/kata/578a8a01e9fd1549e50001f1/train/python
Is your period late?
In this kata, we will make a function to test whether a period is late.
Our function will take three parameters:
last - The Date object with the date of the last period
today - The Date object with the date of the check
cycleLength - Integer representing the length of the cycle in days
If the today is later from last than the cycleLength, the function should return true. We consider it to be late if the number of passed days is larger than the cycleLength. Otherwise return false.
"""
from datetime import *
def period_is_late(last,today,cycle_length):
return last + timedelta(days = cycle_length) < today
"""
Sample Tests
Test.describe("Basic tests")
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 35), False)
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 28), True)
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 35), False)
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 6, 29), 28), False)
Test.assert_equals(period_is_late(date(2016, 7, 12), date(2016, 8, 9), 28), False)
Test.assert_equals(period_is_late(date(2016, 7, 12), date(2016, 8, 10), 28), True)
Test.assert_equals(period_is_late(date(2016, 7, 1), date(2016, 8, 1), 30), True)
Test.assert_equals(period_is_late(date(2016, 6, 1), date(2016, 6, 30), 30), False)
Test.assert_equals(period_is_late(date(2016, 1, 1), date(2016, 1, 31), 30), False)
Test.assert_equals(period_is_late(date(2016, 1, 1), date(2016, 2, 1), 30), True)
"""
|
019b5d23d15f4b1b28ee9d89112921f4d325375e | TonyZaitsev/Codewars | /7kyu/Sum Factorial/Sum Factorial.py | 1,148 | 4.15625 | 4 | """
https://www.codewars.com/kata/56b0f6243196b9d42d000034/train/python
Sum Factorial
Factorials are often used in probability and are used as an introductory problem for looping constructs. In this kata you will be summing together multiple factorials.
Here are a few examples of factorials:
4 Factorial = 4! = 4 * 3 * 2 * 1 = 24
6 Factorial = 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720
In this kata you will be given a list of values that you must first find the factorial, and then return their sum.
For example if you are passed the list [4, 6] the equivalent mathematical expression would be 4! + 6! which would equal 744.
Good Luck!
Note: Assume that all values in the list are positive integer values > 0 and each value in the list is unique.
Also, you must write your own implementation of factorial, as you cannot use the built-in math.factorial() method.
"""
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
def sum_factorial(lst):
return sum(list(map(lambda x: factorial(x), lst)))
"""
Sample Tests
test.assert_equals(sum_factorial([4,6]), 744)
test.assert_equals(sum_factorial([5,4,1]), 145)
"""
|
56be1dd38c46c57d5985d8c85b00895eeca5777d | TonyZaitsev/Codewars | /5kyu/The Hashtag Generator/The Hashtag Generator.py | 2,177 | 4.3125 | 4 | """
https://www.codewars.com/kata/52449b062fb80683ec000024/train/python
The Hashtag Generator
The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!
Here's the deal:
It must start with a hashtag (#).
All words must have their first letter capitalized.
If the final result is longer than 140 chars it must return false.
If the input or the result is an empty string it must return false.
Examples
" Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata"
" Hello World " => "#HelloWorld"
"" => false
"""
def generate_hashtag(s):
hashtag = "#" + "".join(list(map(lambda x: x.capitalize(), s.split(" "))))
return hashtag if 1< len(hashtag) < 140 else False
"""
Sample Tests
Test.describe("Basic tests")
Test.assert_equals(generate_hashtag(''), False, 'Expected an empty string to return False')
Test.assert_equals(generate_hashtag('Do We have A Hashtag')[0], '#', 'Expeted a Hashtag (#) at the beginning.')
Test.assert_equals(generate_hashtag('Codewars'), '#Codewars', 'Should handle a single word.')
Test.assert_equals(generate_hashtag('Codewars '), '#Codewars', 'Should handle trailing whitespace.')
Test.assert_equals(generate_hashtag('Codewars Is Nice'), '#CodewarsIsNice', 'Should remove spaces.')
Test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice', 'Should capitalize first letters of words.')
Test.assert_equals(generate_hashtag('CodeWars is nice'), '#CodewarsIsNice', 'Should capitalize all letters of words - all lower case but the first.')
Test.assert_equals(generate_hashtag('c i n'), '#CIN', 'Should capitalize first letters of words even when single letters.')
Test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice', 'Should deal with unnecessary middle spaces.')
Test.assert_equals(generate_hashtag('Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Cat'), False, 'Should return False if the final word is longer than 140 chars.')
"""
|
a5ebb27b3e709396ad81c482ff164bf372e9bf96 | kepler471/katas | /esolangInterpreter/ministring.py | 202 | 3.5625 | 4 | def interpreter(code):
count = 0
accum = ''
for i in code:
if i == '+':
count = (count + 1) % 256
elif i == '.':
accum += chr(count)
return accum
|
ef2c835a3bcefbf4b26cea5291d3478014f877fd | uzunovavera/learnPythonTheHardWay | /venv/ex13.py | 593 | 3.875 | 4 | from sys import argv
#read the WYSS section for how to run this
script, first, second, third = argv
age = input("What is your age?")
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
# To execute this you need to open CMD from the folder with the scripts and write:
# python ex13.py one_thing another_thing the last_thing
# You will get result:
# The script is called: ex13.py
# Your first variable is: 1thing
# Your second variable is: 2things
# Your third variable is: 3things
|
7cc9db5d288ce69ff8d87079d92ad899ac52026b | mehedieh/dice | /dice.py | 2,997 | 3.75 | 4 | import random
import time
import getpass
import hashlib
HASHED_PASSWORD = "b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86"
USERS = ('User1', 'User2', 'User3', 'User4', 'User5')
def login(max_attempts=5):
attempts = 0
while attempts < max_attempts:
username = input('What is your username? ')
password = getpass.getpass('What is your password? ')
# [OPTIONAL] add a salt
if username not in USERS or HASHED_PASSWORD != hashlib.sha512(password.encode()).hexdigest():
print('Something went wrong, try again')
attempts += 1
continue
print(f'Welcome, {username} you have been successfully logged in.')
return username
print("Too many tries, exiting")
exit()
if __name__ == '__main__':
user = login()
def roll():
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
change = 10 if (die1 + die2) % 2 == 0 else -5
points = die1 + die2 + change
if die1 == die2:
points += random.randint(1, 6)
return points
def game(user1, user2):
player1_points = 0
player2_points = 0
for i in range(1,5):
player1_points += roll()
print(f'After this round {user1} you now have: {player1_points} Points')
time.sleep(1)
player2_points += roll()
print(f'After this round {user2} you now have: {player2_points} Points')
time.sleep(1)
player1_tiebreaker = 0
player2_tiebreaker = 0
if player1_points == player2_tiebreaker:
while player1_tiebreaker == player2_tiebreaker:
player1_tiebreaker = random.randint(1,6)
player2_tiebreaker = random.randint(1,6)
player1_win = (player1_points + player1_tiebreaker) > (player2_points, player2_tiebreaker)
return (player1_points, player1_win), (player2_points, not player2_win)
def add_winner(winner):
with open('Winner.txt', 'a') as f:
f.write('{winner[0]},{winner[1]}\n')
def get_leaderboard():
with open('Leaderboard.txt', 'r') as f:
return [line.replace('\n','') for line in f.readlines()]
def update_leaderboard(leaderboard, winner):
for idx, item in enumerate(leaderboard):
if item.split(', ')[1] == winner[1] and int(item.split(', ')[0]) < int(winner[0]):
leaderboard[idx] = '{}, {}'.format(winner[0], winner[1])
else:
pass
leaderboard.sort(reverse=True)
def save_leaderboard(leaderboard):
with open('Leaderboard.txt', 'w') as f:
for item in leaderboard:
f.write(f'{item}\n')
def main():
user1 = login()
user2 = login()
(player1, player1_win), (player2, player2_win) = game(user1, user2)
if player1_win:
winner = (player1, user1)
else:
winner = (player2, user2)
print('Well done, {winner[1]} you won with {winner[0]} Points')
add_winner(winner)
leaderboard = get_leaderboard()
update_leaderboard(leaderboard, winner)
save_leaderboard(leaderboard)
if __name__ == '__main__':
main()
|
d78ad76a67dfa6b320a78cf88427b8ef791bb814 | movingpictures83/MATria | /networkx_mod/generators/stochastic.py | 1,433 | 3.6875 | 4 | """Stocastic graph."""
# Copyright (C) 2010-2013 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
import networkx as nx
from networkx.utils import not_implemented_for
__author__ = "Aric Hagberg <aric.hagberg@gmail.com>"
__all__ = ['stochastic_graph']
@not_implemented_for('multigraph')
@not_implemented_for('undirected')
def stochastic_graph(G, copy=True, weight='weight'):
"""Return a right-stochastic representation of G.
A right-stochastic graph is a weighted digraph in which all of
the node (out) neighbors edge weights sum to 1.
Parameters
-----------
G : directed graph
A NetworkX DiGraph
copy : boolean, optional
If True make a copy of the graph, otherwise modify the original graph
weight : edge attribute key (optional, default='weight')
Edge data key used for weight. If no attribute is found for an edge
the edge weight is set to 1. Weights must be positive numbers.
"""
import warnings
if copy:
W = nx.DiGraph(G)
else:
W = G # reference original graph, no copy
#degree = W.out_degree(weight=weight)
degree = W.degree(weight=weight)
for (u,v,d) in W.edges(data=True):
if degree[u] == 0:
warnings.warn('zero out-degree for node %s'%u)
d[weight] = 0.0
else:
d[weight] = float(d.get(weight,1.0))/degree[u]
return W
|
285505ccfb2e2dbd706c6ef6f884c92f1fa0214c | LiamTHCH/Boids-Simulation | /Test Version/main (0).py | 1,974 | 3.53125 | 4 | import random
import time
from tkinter import *
master = Tk()
master.title("Points")
canvas_width = 1000
canvas_height = 800
w = Canvas(master, width=canvas_width, height=canvas_height)
w.pack(expand=YES, fill=BOTH)
w.pack()
##definir les variables
Ox = (random.randint(100, 900))
Oy = (random.randint(100, 700))
m = 30
dt = 0.1
t = 0
size = 10
nb = 10
def paint(x, y, color): ##la fonction paint cree les points
color
x1, y1 = (x - size), (y - size)
x2, y2 = (x + size), (y + size)
w.create_oval(x1, y1, x2, y2, fill=color)
class point(): ##cree la fonction point
def __init__(self,m,dt): ##initialisation (self = lui meme) tout les variable sont propres a luis
self.Ox = (random.randint(0, 800))
self.Oy = (random.randint(0, 1000))
self.m = m
self.dt = dt
self.Mx = (random.randint(0, 800))
self.My = (random.randint(0, 1000))
self.OMx = 0
self.OMy = 0
self.fx = 0
self.fy = 0
self.ax = 0
self.ay = 0
self.vx = 100
self.vy = 50
def calcule(self): ## calcule de son prochain point
self.OMx = self.Mx - self.Ox
self.OMy = self.My - self.Oy
self.fx = m * (-self.OMx)
self.fy = m * (-self.OMy)
self.ax = (1 / self.m) * self.fx
self.ay = (1 / self.m) * self.fy
self.vx = self.vx + (self.ax * self.dt)
self.vy = self.vy + (self.ay * self.dt)
self.Mx = self.Mx + (self.vx * self.dt)
self.My = self.My + (self.vy * self.dt)
def show(self): ## met le point sur la carte
paint(self.Mx,self.My,"#FF0000")
flock = [point(m,dt) for _ in range(nb)] ## cree nb de point dans la liste
while True:
for p in flock: ##fais un par un les commande pour chaque elements de la liste
p.calcule()
p.show()
paint(Ox, Oy, "#000000")
master.update()
time.sleep(0.05)
w.delete("all")
mainloop() |
74e2b19f5933103ad676852617eb303038fbe3ce | ckasper21/CS265 | /lab04/s1.py | 591 | 3.671875 | 4 | #!/usr/bin/python
# s1.py
# Author: Chris Kasper
# Purpose: Breakdown students input file, outputs name and average
import sys
if len(sys.argv)==1: # Check to make sure theres an arg (other then the script)
sys.exit()
f = open(str(sys.argv[1]), 'r') # Open the file from arg
l=f.readline()
while l :
total=0
l=l.strip() # Get rid of newlines, trailing spaces, etc
l=l.split(" ") # Split the line by spaces
for x in range(1,len(l)): # Index through grades. l[0] is the name
total+=int(l[x])
average=(float(total)/(len(l)-1))
print "%s %.2f" % (l[0],average)
l=f.readline()
f.close()
|
f9df830f5502a1652f458cfa5f3d25832a27fc54 | caohanlu/test | /阶段01/08 类与类之间的调用、继承.py | 9,933 | 4.78125 | 5 |
"""
类与类之间的调用:
需求:老张开车去东北
类:承担行为 【行为一样的,划分成一个类】【按照行为,划分成类,就叫做封装】
对象:承担数据 【每个对象的数据不一样,但是每个对象的行为是一样的】
1. 识别对象
老张 车
2. 分配职责
去() 行驶()
3. 建立交互
老张调用车
4.东北没有动作,所以不用划分成类
"""
# 写法1:直接创建对象
# 语义: 老张去东北用一辆新车
# class Person:
# def __init__(self, name=""):
# self.name = name
#
# def go_to(self, position):
# print(self.name, "去", position)
# car = Car() # 调用类Car(),创建了对象car
# car.run() # 对象car,调用了类Car()里的函数run
# #这种写法,每去一个地方,都会执行一次car = Car(),即都会创建一个car对象,不太合适
#
#
# class Car:
# # 实例方法
# def run(self):
# print("汽车在行驶")
#
#
# lw = Person("老王")
# lw.go_to("东北")
# lw.go_to("西北")
# 写法2:在构造函数中创建对象
# 语义: 老张开车自己的车去东北
# class Person:
# def __init__(self, name=""):
# self.name = name
# self.car = Car() #在构造函数中,通过类class Car,创建对象car
#
# def go_to(self, position):
# print(self.name, "去", position)
# # 第一次.: 从栈帧到人对象
# # 第二次.: 从人到车对象
# self.car.run() #通过self.car调用实例方法run()
#
#
# class Car:
# # 实例方法
# def run(self):
# print("汽车在行驶")
#
#
# lw = Person("老王")
# lw.go_to("东北")
# lw.go_to("西北")
# 写法3:通过参数传递对象
# 语义:人通过交通工具(参数传递而来)去东北
# class Person:
# def __init__(self, name=""):
# self.name = name
#
# def go_to(self, position, vehicle): #vehicle是参数名
# print(self.name, "去", position)
# vehicle.run() #vehicle是参数名,vehicle这个对象,调用函数run()
#
#
# class Car:
# # 实例方法
# def run(self):
# print("汽车在行驶")
#
#
# lw = Person("老王")
# c01 = Car()
# lw.go_to("东北", c01)#c01这个Car对象,通过参数,传递给go_to函数
"""
练习:
需求:小明请保洁打扫卫生
1. 识别对象
小明【客户类】 保洁【保洁类】
2. 分配职责
通知 打扫卫生
3. 建立交互
小明调用保洁的打扫卫生方法
"""
# 写法1:类里的动作函数,创建别的类的对象,然后通过对象调用别的类的实例方法
# 每次请一个新保洁
# class Client:
# def __init__(self, name=""):
# self.name=name
# def notify(self):
# cleaner=Cleaner()
# cleaner.clean()
#
# class Cleaner:
# def __init__(self, name=""):
# self.name=name
# def clean(self):
# print("保洁在打扫卫生")
#
# client=Client("小明")
# client.notify()
# 写法2:类里的构造函数,创建别的类的对象,然后通过对象调用别的类的实例方法
# 每次请同一个保洁
# class Client:
# def __init__(self, name=""):
# self.name=name
# self.cleaner=Cleaner()
# def notify(self):
# self.cleaner.clean()
#
# class Cleaner:
# def __init__(self, name=""):
# self.name=name
# def clean(self):
# print("保洁在打扫卫生")
#
# client=Client("小明")
# client.notify()
# 写法3:通过参数,调用别的类的实例方法
# class Client:
# def __init__(self, name=""):
# self.name=name
# def notify(self,cleaner):
# cleaner.clean()
#
#
# class Cleaner:
# def __init__(self, name=""):
# self.name=name
# def clean(self):
# print("保洁在打扫卫生")
#
# client=Client("小明")
# cleaner01=Cleaner()
# client.notify(cleaner01)
"""
练习
1. 玩家攻击敌人,敌人受伤(播放动画)
2. 玩家(攻击力)攻击敌人(血量),
敌人受伤(播放动画,血量减少)
3. 敌人(攻击力)还能攻击玩家(血量),
玩家受伤(碎屏,血量减少)
"""
#
#
# class GamePlayer:
# def __init__(self, name="", power=0, blood=0):
# self.name = name
# self.power = power
# self.blood = blood
#
# def attack(self, enemy):
# enemy.injured(self.power)
#
# def injured(self, value):
# print("玩家受伤")
# self.blood -= value
# print(self.blood)
#
#
# class Enemy:
# def __init__(self, name="", power=0, blood=0):
# self.name = name
# self.power = power
# self.blood = blood
#
# def attack(self, gameplayer):
# gameplayer.injured(self.power)
#
# def injured(self, value):
# print("敌人受伤了")
# self.blood -= value
# print(self.blood)
#
#
# gameplayer01 = GamePlayer("玩家01", 10, 100)
# enemy01 = Enemy("敌人01", 10, 100)
# gameplayer01.attack(enemy01)
# enemy01.attack(gameplayer01)
"""
继承
编程:代码不用子类写,但是子类能使用
多个类有代码的共性,且属于共同一个概念。
下面继承父类的实例方法【即函数】
"""
# 从思想讲:先有子再有父
# 从编码讲:先有父再有子
# 多个类有代码的共性,且属于共同一个概念。
# 比如学生会说话,老师也会说话,则把说话这段代码 抽象成人这个类,人会说话
# class Person:
# def say(self):
# print("说话")
#
# class Student(Person): #(Person),表示继承父类Person
# def study(self):
# self.say() #可以调用父类的实例方法
# print("学习")
#
# class Teacher(Person):
# def teach(self):
# print("教学")
#
#
# # 创建子类对象,可以调用父类方法和子类方法
# s01 = Student()
# s01.say() #这个就是父类方法
# s01.study()
#
# # 创建父类对象,只能调用父类方法
# p01 = Person()
# p01.say()
"""
父类、子类,关系的判断方法,三种
【兼容性判断】
"""
#
# # isinstance(对象,类) 判断关系,python内置函数
#
# # 学生对象 是一种 学生类型
# print(isinstance(s01, Student)) # True
# # 学生对象 是一种 人类型
# print(isinstance(s01, Person)) # True
# # 学生对象 是一种 老师类型
# print(isinstance(s01, Teacher)) # False
# # 人对象 是一种 学生类型
# print(isinstance(p01, Student)) # False
#
#
#
#
# # issubclass(类型,类型) 判断关系
#
# # 学生类型 是一种 学生类型
# print(issubclass(Student, Student)) # True
# # 学生类型 是一种 人类型
# print(issubclass(Student, Person)) # True
# # 学生类型 是一种 老师类型
# print(issubclass(Student, Teacher)) # False
# # 人类型 是一种 学生类型
# print(issubclass(Person, Student)) # False
#
#
#
#
#
# # Type
# # type(对象) == 类型 相等/相同/一模一样
#
# # 学生对象的类型 是 学生类型
# print(type(s01) == Student) # True
# # 学生对象的类型 是 人类型
# print(type(s01) == Person) # False
# # 学生对象的类型 是 老师类型
# print(type(s01) == Teacher) # False
# # 人对象的类型 是 学生类型
# print(type(p01) == Student) # False
"""
继承数据【继承的是父类的实例变量】
class 儿子(爸爸):
def __init__(self, 爸爸构造函数参数,儿子构造函数参数):
super().__init__(爸爸构造函数参数)
self.数据 = 儿子构造函数参数
"""
# class Person:
# def __init__(self, name="", age=0):
# self.name = name
# self.age = age
#
#
# class Student(Person):
# def __init__(self, name="", age=0, score=0):
# super().__init__(name, age) # 通过super()调用父类__init__函数,自己的__init__需要给父类的__init__传递参数
# self.score = score
#
#
# # 1. 子类可以没有构造函数,可以直接使用父类的__init__函数
# s01 = Student()
#
# # 2. 子类有构造函数,会覆盖父类构造函数(好像他不存在)
# # 所以子类必须通过super()调用父类构造函数
# s01 = Student("小明", 24, 100)
# print(s01.name)
# print(s01.age)
# print(s01.score)
#
"""
练习:继承数据【即继承实例变量】
创建父类:车(品牌,速度)
创建子类:电动车(电池容量,充电功率)
创建子类对象并画出内存图。
"""
# class Car:
# def __init__(self, brand="", speed=0):
# self.brand=brand
# self.speed=speed
#
# class ElectricVehicle(Car):
# def __init__(self,brand="", speed=0,capacity=0,power=0):
# super().__init__(brand,speed)
# self.capacity=capacity
# self.power=power
#
# ElectricVehicle01=ElectricVehicle("速派奇",100,200,200)
# print(ElectricVehicle01.brand)
# print(ElectricVehicle01.speed)
# print(ElectricVehicle01.capacity)
# print(ElectricVehicle01.power)
"""
多继承
同名方法解析顺序
类.mro()
"""
#
# class A:
# def func01(self):
# print("A -- func01")
#
#
# class B(A):
# def func01(self):
# print("B -- func01")
#
#
# class C(A):
# def func01(self):
# print("C -- func01")
#
#
# class D(B, C):
# def func01(self):
# super().func01() # 继承列表第一个父类B的func01()方法
# print("D -- func01")
#
#
# d = D()
# d.func01()
# 具体的解析顺序:使用 类名字.mro()方法,可以print出来
# [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
# print(D.mro())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.