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 |
|---|---|---|---|---|---|---|
624b61cfac66a83ca8f5989b0f1806df330c7cab | delonxd/Calculate2.0 | /src/Freq.py | 1,464 | 3.84375 | 4 | class Freq:
"""
频率
"""
def __init__(self, value=0.0):
self.value = value
def change_freq(self):
new = self.value
if self.value == 1700:
new = 2300
elif self.value == 2000:
new = 2600
elif self.value == 2300:
new = 1700
elif self.value == 2600:
new = 2000
self.value = new
return new
def __float__(self):
return float(self.value)
def copy(self):
obj = Freq(self.value)
return obj
def __add__(self, other):
value_new = self.value + other
return value_new
def __radd__(self, other):
value_new = self.value + other
return value_new
def __sub__(self, other):
value_new = self.value - other
return value_new
def __rsub__(self, other):
value_new = other - self.value
return value_new
def __neg__(self):
value_new = -self.value
return value_new
def __mul__(self, other):
value_new = self.value * other
return value_new
def __rmul__(self, other):
value_new = self.value * other
return value_new
def __truediv__(self, other):
value_new = self.value / other
return value_new
def __rtruediv__(self, other):
value_new = other / self.value
return value_new
def __repr__(self):
return str(self.value)
|
8c5cf3b851e9e73a31b36418acb8c58e69bb29a5 | folkol/c3 | /funcs.py | 1,750 | 3.921875 | 4 | def chunkify(lst, n):
"""Given a list of a number n, yield consecutive chunks of size n."""
for pos in range(0, len(lst), n):
yield lst[pos:pos + n]
def hex_to_ints(hex_string):
"""Converts the hex string to a list of ints by converting chunks of 2 chars to int."""
return [int(chars, 16) for chars in chunkify(hex_string, 2)]
def ints_to_hex(ints):
as_hex = (format(x, '02x') for x in ints)
return ''.join(as_hex)
def ints_to_base64(ints):
"""Converts a list of ints, interpreted as byte values, to base64.
No padding support, which means that len(ints) must be a multiple of 3."""
from string import ascii_uppercase, ascii_lowercase, digits
numerals = ascii_uppercase + ascii_lowercase + digits + '+/'
as_binary = (format(i, '08b') for i in ints)
as_binary_string = ''.join(as_binary)
return ''.join([numerals[int(x, 2)] for x in chunkify(as_binary_string, 6)])
def hex_to_base64(hex_string):
as_ints = hex_to_ints(hex_string)
as_base64 = (ints_to_base64(x) for x in chunkify(as_ints, 3))
return ''.join(as_base64)
def assert_equals(expected, actual):
assert expected == actual, "Expected/actual: \n\t'{}'\n\t'{}'.".format(expected, actual)
def ascii_to_ints(string):
return [ord(x) for x in string]
def ascii_to_hex(string):
print(string)
ints = ascii_to_ints(string)
print(ints)
return ints_to_hex(ints)
def ints_to_ascii(ints):
return ''.join(chr(i) for i in ints)
def hex_to_ascii(hex_string):
return ints_to_ascii(hex_to_ints(hex_string))
def encrypt_repeating_key_xor(msg, key):
from itertools import cycle
as_ints = ascii_to_ints(msg)
return ints_to_hex(i ^ ord(k) for i, k in zip(as_ints, cycle(key))) |
593c576dd4cd4cb4063ca8b9778d25119c08ff97 | Nevilli/unit_three | /d4_unit_three_warmups.py | 270 | 3.859375 | 4 | def area_of_rectangle(length, width):
"""
This function calculate the area of a rectangle
:param length: length of long side of rectangle
:param width: length of small side of rectangle
:return: area
"""
area = length * width
return area
|
d0d02f1607c97e6c7284f3f14d9366e79dc359fd | tylerweng/test-tensor | /examples/variable_example.py | 1,293 | 3.734375 | 4 | import tensorflow as tf
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W*x + b
"""
Constants are initialized when you call tf.constant, and their value can never change. By contrast, variables are not
initialized when you call tf.Variable. To initialize all the variables in a TensorFlow program, you must explicitly
call a special operation as follows:
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
It is important to realize init is a handle to the TensorFlow sub-graph that initializes all the global variables.
Until we call sess.run, the variables are uninitialized.
"""
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print("sess.run(linear_model, {x: [1, 2, 3, 4]})", sess.run(linear_model, {x: [1, 2, 3, 4]}))
y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)
print("sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]})", sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}))
fixW = tf.assign(W, [-1.])
fixb = tf.assign(b, [1.])
sess.run([fixW, fixb])
print("sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]})", sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}))
|
12c7f58887bfc154c09569a13de79d6eb83caa59 | Leo7890/Tarea-04 | /VentadeSoftware.py | 1,244 | 3.9375 | 4 | #encode: UTF-8
#Autor: Leonardo Castillejos Vite
#Descripción: Da el precio total del software comprado
def main():
paquetesComprados = int(input("Teclea el número de softwares comprados: "))
if paquetesComprados > 0:
descuento = calcularDescuento(paquetesComprados)
totalPagar = calcularTotal(paquetesComprados)
print("El descuento fue de $%.2f" %(descuento))
print("EL total a pagar es de $%.2f" %(totalPagar))
else:
print("Cantidad invalida")
# Calcula la cantidad de descuento que se hara
def calcularDescuento(paquetesComprados):
if paquetesComprados >= 10 and paquetesComprados <= 19:
return ((paquetesComprados * 1500) * .2)
elif paquetesComprados >= 20 and paquetesComprados <= 49:
return ((paquetesComprados * 1500) * .3)
elif paquetesComprados >= 50 and paquetesComprados <= 99:
return ((paquetesComprados * 1500) * .4)
elif paquetesComprados >= 100:
return ((paquetesComprados * 1500)* .5)
else:
return 0
# Calcula el precio total aplicando el descuento
def calcularTotal(paquetesComprados):
total = (paquetesComprados * 1500) - calcularDescuento(paquetesComprados)
return total
main()
|
a68707c994be958a06e2a0cc5480cf78d488f3ad | BalaKumaran1998/Python | /Armstrong Number.py | 243 | 3.921875 | 4 | n=int(input())
def arms(n):
sum = 0
temp = n
while temp > 0:
digit=temp % 10
sum+=digit ** 3
temp //= 10
if (n == sum):
print(n,"is Armstrong number")
else:
print(n,"is not Armstrong number")
arms(n)
|
238001c5397879d0a6d632a2d2de48dccffa2ddc | irfankhan309/DS-AL | /Py_Codes/my_practice/python_series/dictionary.py | 278 | 3.796875 | 4 | rec={}
n=(int(input('enter no of students:')))
i=1
while i<=n:
name=input('enter the student name:')
marks=input('enter the %of the student')
rec[name]=marks
i=i+1
print('name of student','\t','% of marks')
for x in rec:
print('\t',x,'\t\t',rec[x])
|
c6c9e57135b1c1ef08112b65ec310b6c333e414b | irfankhan309/DS-AL | /Py_Codes/my_practice/python_series/functions_1.py | 1,024 | 3.921875 | 4 | def sum_dec(func):
def inner(a,b):
return a+b
return inner
def sub_dec(func):
def inner(a,b):
c=a+b
c1=c*2
return c1
return inner
@sub_dec
@sum_dec
def add(a,b):
print('the values of sum:',a+b)
add(2,4)
#-------------------------
def wish_dec(func):
def inner(name):
print('heyaa how are you',name)
return inner
def wish_dec1(func):
def inner(name):
print('as salamu alykum,kaifa haal',name)
return inner
@wish_dec1
@wish_dec
def wish(name):
print('hai',name)
wish('sam')
wish('irfan')
#------------------------------------------
#generators example 3
def mobile(num):
def inner(std):
print('the number is:',std)
return inner
def mob1(num):
def inner(std):
print('this is finally phone number you are seeing here',std)
return inner
@mob1
@mobile
def code(std):
print('the code is',std)
code(91)
code(8008469093)
code(9030139353)
|
fbf736938161e98b8c03b83620597aed3a28d5a5 | irfankhan309/DS-AL | /Py_Codes/my_practice/python_series/y.py | 747 | 3.609375 | 4 | class supermarket:
def __init__(self,cnumber,item,cost,qty):
self.cnumber=cnumber
self.item=item
self.cost=cost
self.qty=qty
def total(self):
print('*'*30)
print('cnumber items cost qty')
print('*'*30)
print('number is:',self.cnumber)
print('items are:',self.item)
print('total cost:',self.cost)
print('qyt is:',self.qty)
print('*'*30)
import time
time.sleep(4)
import random
a=[10,20,30,40,50]
b=[90,45,34,32]
c=random.choice(a)
print(c)
time.sleep(2)
d=random.choice(b)
print(d)
time.sleep(2)
e=c+d
print(e)
import math
a=10
b=20
c=math.factorial(a)
time.sleep(3)
c1=math.pow(b,2)
print(c)
print(c1)
|
5498480aa47f089ec6dbdde9b94057e3bd774cb7 | irfankhan309/DS-AL | /Py_Codes/my_practice/python_series/NOTHING.PY | 242 | 3.65625 | 4 | class student:
def __init__(self,sno,sname):
self.sno=sno
self.sname=sname
def sinfo(self):
print("the student number is:",self.sno)
print("the student name is:", self.sname)
s1=student('08DN1A0526', 'irfankhan')
s1.sinfo() |
472e517a45ca9635b512f268bc0ed6f5acd31dda | mohamed-elghayesh/PyHackerRank | /count_substring/door_mat.py | 246 | 3.96875 | 4 | rows = input()
cols = int(rows) * 3
for i in range(int(rows)//2):
print((".|."*(2*i+1)).center(int(cols),"-"))
print("WELCOME".center(int(cols),"-"))
for i in reversed(range(int(rows)//2)):
print((".|."*(2*i+1)).center(int(cols),"-"))
|
d78f2a4ea0aca46bea573ee1f0c695e273b706e3 | Riqzz/master_course | /numerical analysis/misc/eu.py | 307 | 3.53125 | 4 | def fun(x):
return (2*x+1)**0.5
def dfun(x):
return 1/(2*x+1)**0.5
def dy(x, y):
return y - 2*x/y
xn = 0
yn = fun(xn)
h = 0.1
xn1 = xn + h
yn1 = yn + h * dy(xn, yn)
print('yn+1\'', yn1)
for i in range(20):
yn1 = yn + h * dy(xn1, yn1)
print('yn+1', yn1)
print('y(xn+1)', fun(xn1)) |
0d7f4bc775f87d78a2324b5540cc3db0215db945 | rahuladream/Speech-Recogniser | /Speech Recogniser.py | 1,924 | 3.734375 | 4 |
#Python Speech Recogniser
#Please do check your mic before beginning..
import speech_recognition as sr
from time import ctime
import time
import os
import sys
from gtts import gTTS
def speak(audioString):
print(audioString)
tts = gTTS(text=audioString, lang='en')
def recordAudio():
# Record Audio
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)
# Speech recognition using Google Speech Recognition
data = ""
try:
# Uses the default API key
# To use another API key: `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
data = r.recognize_google(audio)
print("You said: " + data)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
return data
def jarvis(data):
if "hello" in data:
speak("Hi! how are you ?")
if "compose mail" in data:
sys.stdout.write(RED)
speak("Alright I am going to compose mail")
if "how are you" in data:
speak("I am fine")
if "what time is it" in data:
speak(ctime())
if "where is" in data:
data = data.split(" ")
location = data[2]
speak("Hold on Bro, I will show you where " + location + " is.")
os.system("chromium-browser https://www.google.nl/maps/place/" + location + "/&")
if "what language you speak" in data:
speak("I only understand English")
if "f*** you" in data:
speak("Yo motherf** ! I don't speak in that way")
# initialization
time.sleep(2)
speak("Hi Frank, what can I do for you?")
while 1:
data = recordAudio()
jarvis(data)
|
3a0e0613e6800fb782f195d6587e6060c7274f47 | mxpablo/Batch17Roja | /15 ejListas.py | 491 | 3.75 | 4 | lista = []
for i in range(0,100):
lista.append(i+1)
print(lista)
numero = int(input("Escribe un número \n"))
lista2 = []
for i in range(1,11):
lista2.append (numero*i)
print(lista2)
lista3=[4,76,3,12,65,3]
lista4=[234,222,523,65]
lista5 = []
lista5.extend(lista3)
lista5.extend(lista4)
print(lista5)
suma = 0
for i in lista5:
suma += i
print(suma)
lista6=[4,76,3,12,65,3]
lista7=[234,222,523,65]
lista8 = lista6 + lista7
valor = 0
for i in lista8:
valor = valor + i
print(valor) |
c20fb0daa9ad8f5124511a54a8cdbf9fd7e7a91a | mxpablo/Batch17Roja | /16 dict.py | 1,319 | 3.953125 | 4 | diccionario = {
'nombre':'Carlos',
'edad':'22',
'cursos':['Python','Flask']
}
print(diccionario)
print(diccionario['nombre'])
print(diccionario['edad'])
print(diccionario['cursos'])
print(diccionario['cursos'][0])
print(diccionario['cursos'][1])
dic = dict(nombre='Juan',apellido='Juarez',edad=22)
print(dic['nombre'])
print("--------------------------------")
for key,value in diccionario.items():
print(key + " :" + str(value))
print("--------------------------------")
print(len(diccionario))
print("--------------------------------")
print(diccionario.keys())
print("--------------------------------")
print(diccionario.values())
print("--------------------------------")
print(diccionario.get("nombre","JUANITO"))
print("--------------------------------")
print(diccionario.get("nombree", "JUANITO"))
print("--------------------------------")
diccionario['key'] = 'value'
print(diccionario)
print("--------------------------------")
diccionario.pop('key')
print(diccionario)
print("--------------------------------")
lista_cursos = diccionario['cursos']
lista_cursos.append('Java')
print(lista_cursos)
print(diccionario)
print("--------------------------------")
diccionario2 = diccionario.copy()
print(diccionario2)
print("--------------------------------")
diccionario.update(dic)
print(diccionario) |
638b3f1058b6f91699bb21598044d1f99ae29449 | jerryjsebastian/leetcode | /1431_KidsAndCandies/KidsAndCandies.py | 207 | 3.5 | 4 | def kidsWithCandies(candies, extraCandies):
sol = []
for c in candies:
if c+extraCandies>=max(candies):
sol.append(True)
else:
sol.append(False)
return sol |
288765118face2829ac1a203b78b5767eab41327 | Angihyo/Angihyo | /GiHyo/servo_angle_calcul.py | 347 | 3.53125 | 4 | import math
def Servo_angle_calcul(vanishingpoint):
height = 360 - vanishingpoint[1]
width = vanishingpoint[0] - 240
angle = 180*(width/height) / math.pi
print(angle)
if angle > 30:
return 1 #turn right maximum
elif angle < -30:
return -1 #turn left maximum
else:
return angle/30
|
09b34c8e145b7f56157dfac0bab96585321fb618 | AarthiAnanth/SampleProject | /MarsExplotion.py | 520 | 3.859375 | 4 |
import sys
def marsExploration(s):
# Complete this function
length=len(s)
multiple=len(s)//3
p=0
q=3
count=0
for i in range(multiple):
new_sub_string=s[p:q]
if new_sub_string[0]!='S':
count+=1
if new_sub_string[1]!='O':
count+=1
if new_sub_string[2]!='S':
count+=1
p=q
q+=3
return (count)
if __name__ == "__main__":
s = input().strip()
result = marsExploration(s)
print(result) |
fcb92b490e1c70b46762fdbff6f8e2fec51e2d30 | himmu-git/MyDesktopAssistant | /MyAssitant.py | 2,415 | 3.609375 | 4 | import pyttsx3
import datetime
import speech_recognition as sr
import webbrowser
import wikipedia as wiki
import tkinter as tk
engine =pyttsx3.init('sapi5')
voices= engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def myWindow():
m=tk.Tk(screenName='Desktop Assitant')
button = tk.Button(m, text='SPEAK', width=25, command=takeCommand)
button.pack()
m.title("Desktop Assitant")
m.mainloop()
def wishme(name):
# datetime object containing current date and time
now = int(datetime.datetime.now().hour)
if(now>=12 and now<16):
speak("Good Afternoon!"+name)
speak("Have a good day")
elif(now>=16 and now<20):
speak("Good Evening!"+name)
speak("I hope you are having a good day")
elif((now>=20 and now<=23) or (now>=0 and now<4 ) ):
speak("Good Night!"+name)
speak("I hope you had a great day")
else:
speak("Good Moring!"+name)
speak("I hope you have a good day")
speak("I am your assistant. Tell me How can I help you?")
def takeCommand():
#take microphone input and returns text output
r=sr.Recognizer()
with sr.Microphone() as source:
print("Listening.......")
r.pause_threshold=1
audio=r.listen(source)
try:
print("Recognising......")
query= r.recognize_google(audio,language='en-in')
print("User said:"+ query)
except Exception as e: #if any error occur
speak("Sorry!!!I didn't hear that. Can you say it again?")
return "None"
return query
if __name__ == "__main__":
wishme("Bro")
#myWindow()
while True:
query=takeCommand().lower()
if(("wikipedia" in query)) :
if("wikipedia"in query):
query.replace("wikipedia","")
res=wiki.summary(query,sentences=2)
elif("tell me about" in query):
query.replace("tell me about","")
res=wiki.summary(query,sentences=2)
speak("According to Wikipedia")
print(res)
speak(res)
if("open youtube" in query):
webbrowser.open("youtube.com")
if("open google" in query):
webbrowser.open("google.com")
if("bye" in query):
speak("Okay!! bye Have a good day")
break
|
a784e7502fd9150977a1b0279b83dc23ccfcf8e2 | tehspyke/Example-Programs | /Py4J Program/Account.py | 1,517 | 3.828125 | 4 | #Mike Rozier
class Account:
'Class to hold accounts'
def __init__(self, acc):
'Initializer for Account class'
self.accountNumber = acc
self.transactionList = []
self.balance = 0.0
def __str__(self):
'String representation for an instance of Account'
return '{0:<20} {1:<20} \n{2:<20} ${3:<20.2f}'.format("Account#: ", self.accountNumber, "Balance (USD): ", self.balance)
def __len__(self):
'Returns the length of the transaction list'
return len(self.transactionList)
def __getitem__(self, index):
'Returns a transaction at the given index'
return self.transactionList[index]
def getBalance(self):
'Returns the account balance'
return self.balance
def apply(self, transaction):
'Adds a transaction to the transaction list and updates the balance'
self.transactionList.append(transaction)
self.balance += transaction.getUSD()
def addTransactions(self, tqueue):
'Takes in a TransactionQueue and calls apply() for all transactions in the queue'
while tqueue.queueLength() > 0:
self.apply(tqueue.dequeue())
def __iter__(self):
'Initializes iteration'
self.index = 0
return self
def __next__(self):
'Returns a value for the current iteration'
#Error checking
if len(self) == 0:
print("Error! Transaction list empty.")
raise StopIteration
if self.index >= len(self):
raise StopIteration
transaction = self.transactionList[self.index]
self.index += 1
return transaction
|
c26c3fa52692454bd47cfab92253715ed461f4f2 | DiegoRmsR/holbertonschool-higher_level_programming | /0x03-python-data_structures/3-print_reversed_list_integer.py | 223 | 4.28125 | 4 | #!/usr/bin/python3
def print_reversed_list_integer(my_list=[]):
if not my_list:
pass
else:
for list_reverse in reversed(my_list):
str = "{:d}"
print(str.format(list_reverse))
|
df51784a57ea894f61e560f04413337a2e299c92 | DiegoRmsR/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 353 | 3.75 | 4 | #!/usr/bin/python3
def inherits_from(obj, a_class):
"""
function that verifies if is an instance of a class
that inherited (directly or indirectly)
Return True if is an instance of a class
Return False otherwise
"""
if isinstance(obj, a_class) and type(obj) is a_class:
return(False)
else:
return(True)
|
93c28615161ad665f97e89b09222deb2b306f097 | DiegoRmsR/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/2-print_alphabet.py | 96 | 3.515625 | 4 | #!/usr/bin/python3
import binascii
for alp in range(97, 123):
print(end="{:c}".format(alp))
|
2f6e9e49c2e16eb0367a99ea29bd2ded11a20da3 | narinee1403/workshop2..0 | /if-else/if_else.py | 246 | 3.734375 | 4 | point = int(input("Enter you score : "))
grade = ["A", "B+", "B", "C+", "C", "D+", "D", "F"]
score = [80, 75, 70, 65, 60, 55, 50, 0]
z = 0
for y in grade:
if point >= score[z]:
print("Grade : " + grade[z])
break
z = z + 1
|
f64e6f348f76f3b3ca4d3b87ac1ff4f004ee87d5 | Starfunk/neural-network-library | /train_network.py | 1,843 | 3.6875 | 4 | """Using this network setup, I have achieved a maximum accuracy
of 98.06% on the MNIST dataset."""
import numpy as np
import network_library
import mnist_loader
# load the MNIST dataset using the mnist_loader file---the returned
# data structure is a list containing the training data, the validation
# data, and the test data.
data = mnist_loader.load_mnist()
# Set training data and training labels. The training dataset is a set
# of 50,000 MNIST (hand-drawn digit) images.
training_data = data[0]
training_labels = data[1]
# Set validation data and validation labels. The validation dataset is a
# set of 10,000 MNIST (hand-drawn digit) images.
validation_data = data[2]
validation_labels = data[3]
# Set test data and test labels. The test dataset is a
# set of 10,000 MNIST (hand-drawn digit) images.
test_data = data[4]
test_labels = data[5]
# Instantiate the neural network with an architecture of 784-100-100-10,
# a learning rate of 0.6, a minibatch size of 64, using the
# cross-entropy function and small weight initialization.
net = network_library.Network([784, 100, 100, 10], 0.6
, 64, cost_function=network_library.CrossEntropyCost, small_weights=True)
# Run mini-batch stochastic gradient descent for 60,000 training epochs
# with L2 regularization.
net.stochastic_gradient_descent(training_data, training_labels,
60000, L2=True)
# Evaluate the network's performance on the test dataset.
acc = net.evaluation(test_data, test_labels)
print("The network classified " + str(acc) + "% of the test data")
# If you would like to verify that I trained a network that achieved
# an accuracy of 98.06%, delete the quotations in the following section.
"""
net = network_library.load('network.txt')
acc = net.evaluation(test_data, test_labels)
print("The network classified " + str(acc) + "% of the test data")
"""
|
cde46fdfc48a87498f1150a034bd82926467bb64 | PPavlidis7/Peg-Solitaire | /Peg_Solitaire/pegsol.py | 18,550 | 3.890625 | 4 | # This program solves the Peg Solitaire problem using two algorithms:
# - BFS - Best First Search (argument = best)
# - DFS - Depth First Search (argument = depth)
# Game board is read from an given input file and the solution is written to a given output ile
# This program is written by Pavlidis Pavlos for a task at the Artificial Intelligence course, April 2018
from __future__ import print_function
from collections import defaultdict
import copy
from operator import itemgetter
import sys
import time
start_time = time.time()
width = None
height = None
board = {}
movehistory = []
# Functions
def readfile(gameboard):
# This function reads the data from the input file and stores them in a dictionary
# Dictionary board has: key : x,y and value 0, 1 or 2
# 0 -> invalid position
# 1 -> position with peg
# 2 -> position without peg
# 0 <= x <= width - 1
# 0 <= y <= height - 1
# inputs : game_board -> an empty dictionary
# output : returns a dictionary created by file's data
file = sys.argv[2]
with open(file,'r') as f:
w, h = map(int, f.readline().split())
x = 0
test = []
for line in f: # read rest of lines
test.append([int(x) for x in line.split()])
y = 0
for inner_l in test:
for item in inner_l:
gameboard[x, y] = item
y += 1
x += 1
test.clear()
return w, h
def checkforsolution(game_board):
# This function checks if we have found a solution
# inputs : game_board : the current game board
# output : true if we have solve the problem , else return false
count = 0
for item in game_board:
if game_board[item] == 1:
count += 1
if count > 1:
return False
else: # The count must be 1. That's means there is only one peg in our board and we have solve the problem
return True
def calculate_pegs_area(game_board):
# This function finds the corners of the orthogonal area which surrounds the pegs
# inputs : game_board : the current game board
# output : returns the area
min_r = -1
min_c = height + 1
max_r = 0
max_c = 0
# Find first and last rows
for item in game_board:
if game_board[item] == 1:
if min_r == -1:
min_r = item[0]
elif max_r < item[0]:
max_r = item[0]
# Find first and last columns
for item in game_board:
if game_board[item] == 1:
if min_c > item[1]:
min_c = item[1]
if max_c < item[1]:
max_c = item[1]
return (max_r - min_r + 1) * (max_c - min_c + 1)
def heuristic(game_board, peg_position, direction):
# This function calculates the heuristic value for a possible move
# inputs : game_board : the current game board
# : peg_position : The pegs' coordinates that we will move
# : direction : The direction which the peg will take
# output : Returns the orthogonal area multiplied by manhattan distance and multiplied by
# the remained number of pegs
number_of_pegs = 0
temp_board = make_move(game_board, peg_position, direction)
man_dis = 0
for item in temp_board:
if temp_board[item] == 1:
number_of_pegs +=1
for item2 in temp_board:
if temp_board[item2] == 1:
man_dis += abs(item[0] - item2[0]) + abs(item[1] - item2[1])
area = calculate_pegs_area(temp_board)
if man_dis == 0:
man_dis = 1
return area*number_of_pegs*man_dis
def valid_move(game_board, item, direction):
# This function check if a peg at position 'item' can move to a specific direction
# inputs : game_board : the current game board
# : item : The pegs' coordinates that we will move
# : direction : The direction which the peg will take
# output : Returns True if we can make that move , else returns False
if direction == 'left':
if item[1] >= 2 and game_board[item] == 1 and game_board[item[0], item[1] - 2] == 2 and \
game_board[item[0], item[1] - 1] == 1:
return True
elif direction == 'right':
if (item[1] != height - 1) and (item[1] + 2 <= (height - 1)) and game_board[item] == 1 \
and game_board[item[0], item[1] + 2] == 2 and game_board[item[0], item[1] + 1] == 1:
return True
elif direction == 'up':
if item[0] >= 2 and game_board[item] == 1 and game_board[item[0] - 2, item[1]] == 2 and \
game_board[item[0] - 1, item[1]] == 1:
return True
elif direction == 'under':
if (item[0] != (width - 1)) and (item[0] + 2 <= (width - 1)) and game_board[item] == 1 \
and game_board[item[0] + 2, item[1]] == 2 and game_board[item[0] + 1, item[1]] == 1:
return True
return False
def make_move(game_board, position, direction):
# This function return the new board after we move the peg at given position and towards a given direction
# inputs : game_board : the current game board
# : position : The pegs' coordinates that we will move
# : direction : The direction which the peg will take
# output : Returns the new game board after peg's movement
next_board = copy.deepcopy(game_board)
if (direction == 'left') and valid_move(game_board, position, direction):
next_board[position] = 2
next_board[position[0], position[1] - 2] = 1
next_board[position[0], position[1] - 1] = 2
elif direction == 'right' and valid_move(game_board, position, direction):
next_board[position] = 2
next_board[position[0], position[1] + 2] = 1
next_board[position[0], position[1] + 1] = 2
elif direction == 'under' and valid_move(game_board, position, direction):
next_board[position] = 2
next_board[position[0] + 2, position[1]] = 1
next_board[position[0] + 1, position[1]] = 2
elif direction == 'up' and valid_move(game_board, position, direction):
next_board[position] = 2
next_board[position[0] - 2, position[1]] = 1
next_board[position[0] - 1, position[1]] = 2
return next_board
def get_possible_moves(game_board):
# This function detects all possible moves
# inputs : game_board : the current game board
# output : Returns a dictionary with all possible moves and their direction
free_positions = []
moves = defaultdict(list)
pegs_position = ('under', 'left', 'up', 'right')
# Find all free positions
for item in game_board:
if game_board[item] == 2:
free_positions.append(item)
for free_position in free_positions:
# Find the neighbors at 'temp' side who can move to this free position
for temp in pegs_position:
row = 0
col = 0
if temp == 'under':
row = free_position[0] + 2
col = free_position[1]
pegs_move_direction = 'up'
elif temp == 'right':
row = free_position[0]
col = free_position[1] + 2
pegs_move_direction = 'left'
elif temp == 'up':
row = free_position[0] - 2
col = free_position[1]
pegs_move_direction = 'under'
elif temp == 'left':
row = free_position[0]
col = free_position[1] - 2
pegs_move_direction = 'right'
if row < 0 or col < 0 or row >= width or col >= height:
continue
position = row, col
# If it is a possible move and at 'position' there is a peg put at 'move' dictionary this move
if valid_move(game_board, position, pegs_move_direction) and (game_board[position] == 1):
moves[position].append(pegs_move_direction)
return moves
def find_child(game_board):
# This Function finds the node's children
# inputs : game_board : the current game board
# output : Return node's children
moves = get_possible_moves(game_board)
return moves
def adjust_coordinats_to_write(position, direction):
# This function is used to adjust the coordinates for our output file.
# It adjusts our coordinates increasing them by 1
# inputs : position : peg's coordinates
# : direction: peg's movement direction
# output : Returns a string with the peg's adjusted coordinates before and after its movement
if direction == 'left':
line = [str(position[0] + 1), " ", str(position[1] + 1), " ", str(position[0] + 1), " ", str(position[1] - 1)]
elif direction == 'right':
line = [str(position[0] + 1), " ", str(position[1] + 1), " ", str(position[0] + 1), " ", str(position[1] + 3)]
elif direction == 'under':
line = [str(position[0] + 1), " ", str(position[1] + 1), " ", str(position[0] + 3), " ", str(position[1] + 1)]
elif direction == 'up':
line = [str(position[0] + 1), " ", str(position[1] + 1), " ", str(position[0] - 1), " ", str(position[1] + 1)]
return line
def find_solution_BFS(game_board, counter):
# This function uses BFS algorithm to find the moves that we need to solve our problem.
# inputs : game_board : the current game board
# : counter : the current counter's value. At the beginning of our program it is equal with zero
# output : Returns the new counter's value . If we reach a dead end path, it will returns the value that
# it got when we called this function
# flag variable contains the initial value of counter
flag = counter
# a list with the heuristics values that we are going to estimate
heuristics_values = []
# check if a solution has been found and create the output file
if checkforsolution(game_board):
results.writelines(str(counter) + '\n')
for item in movehistory:
results.writelines(item)
results.writelines('\n')
# We found a solution so we return -1 to stop all find_solution_BFS calls
return -1
else:
# Find the current node's children
moves = find_child(game_board)
# Estimate their heuristic values
for inner_1 in moves:
for inner_2 in moves[inner_1]:
heuristics_values.append([inner_1, inner_2, heuristic(game_board, inner_1, inner_2)])
# Sort them by their heuristic value
heuristics_values.sort(key=itemgetter(2))
# Take the best child, make this move and call again the find_solution_BFS function do the same
# activity with its children
for inner in heuristics_values:
position = inner.__getitem__(0)
direction = inner.__getitem__(1)
child_board = make_move(game_board, position, direction)
counter += 1
# The program close if it is running for 5 mins and it have not find a solution
if (time.time() - start_time) >= 300:
print('I could not find a solution in 5 minutes')
print(time.time() - start_time)
quit()
line = adjust_coordinats_to_write(position,direction)
# Put to movehistory list this move
movehistory.append(line)
counter = find_solution_BFS(child_board, counter)
if (counter == -1):
break;
# if this line is executed then we have reached a dead end so we delete the last move we have made
del movehistory[-1]
# if we reached a dead end return the counter - 1 because we discard this path
if flag == counter:
return counter - 1
return counter
def find_solution_DFS(game_board, counter):
# This function uses DFS algorithm to find the moves that we need to solve our problem.
# inputs : game_board : the current game board
# : counter : the current counter's value. At the beginning of our program it is equal with zero
# output : Returns the new counter's value . If we reach a dead end path, it will returns the value that
# it got when we called this function
# flag variable contains the initial value of counter
flag= counter
#check if a solution has been found
if checkforsolution(game_board):
results.writelines(str(counter) + '\n')
for item in movehistory:
results.writelines(item)
results.writelines('\n')
# We found a solution so we return -1 to stop all find_solution_BFS calls
return -1
else:
# for each cell of our game board
for item in game_board:
if checkforsolution(game_board):
break
#Check if peg can move left
if valid_move(game_board,item,'left'):
# Make a copy of current game board updated with the new move
new_board = make_move(game_board, item, 'left')
counter += 1
# If we have been unsuccessfully trying over 5 minutes to find a solution terminate the program
if (time.time() - start_time) >= 300:
print('I could not find a solution in 5 minutes')
print(time.time() - start_time)
quit()
if new_board not in movehistory:
line = adjust_coordinats_to_write(item, 'left')
# Put to movehistory list this move
movehistory.append(line)
# Call again find_solution_BFS function parsing the new game board
counter = find_solution_DFS(new_board, counter)
if counter == -1:
break;
# if this line is executed then we have reached a dead end so we delete the last move we have made
del movehistory[-1]
# Check if peg can move right
if valid_move(game_board, item,'right'):
# Make a copy of current game board updated with the new move
new_board = make_move(game_board, item, 'right')
counter += 1
# If we have been unsuccessfully trying over 5 minutes to find a solution terminate the program
if (time.time() - start_time) >= 300:
print('I could not find a solution in 5 minutes')
print(time.time() - start_time)
quit()
if new_board not in movehistory:
line = adjust_coordinats_to_write(item, 'right')
# Put to movehistory list this move
movehistory.append(line)
# Call again find_solution_BFS function parsing the new game board
counter = find_solution_DFS(new_board, counter)
if counter == -1:
break;
# if this line is executed then we have reached a dead end so we delete the last move we have made
del movehistory[-1]
#Check if peg can move up
if valid_move(game_board, item, 'up'):
# Make a copy of current game board updated with the new move
new_board = make_move(game_board, item, 'up')
counter += 1
if (time.time() - start_time) >= 300:
# If we have been unsuccessfully trying over 5 minutes to find a solution terminate the program
print('I could not find a solution in 5 minutes')
print(time.time() - start_time)
quit()
if new_board not in movehistory:
line = adjust_coordinats_to_write(item, 'up')
# Put to movehistory list this move
movehistory.append(line)
# Call again find_solution_BFS function parsing the new game board
counter = find_solution_DFS(new_board, counter)
if counter == -1:
break;
# if this line is executed then we have reached a dead end so we delete the last move we have made
del movehistory[-1]
##Check if peg can move down
if valid_move(game_board, item, 'under'):
# Make a copy of current game board updated with the new move
new_board = make_move(game_board, item, 'under')
counter += 1
# If we have been unsuccessfully trying over 5 minutes to find a solution terminate the program
if (time.time() - start_time) >= 300:
print('I could not find a solution in 5 minutes')
print(time.time() - start_time)
quit()
if new_board not in movehistory:
line = adjust_coordinats_to_write(item, 'under')
# Put to movehistory list this move
movehistory.append(line)
# Call again find_solution_BFS function parsing the new game board
counter = find_solution_DFS(new_board, counter)
if counter == -1:
break;
# if this line is executed then we have reached a dead end so we delete the last move we have made
del movehistory[-1]
# if we reached a dead end return the counter - 1 because we discard this path
if(flag ==counter):
return (counter-1)
return counter
# if user asked for DFS algorithm
if sys.argv[1] == 'depth':
# estimate game board's size
width, height = readfile(board)
results = open(sys.argv[3], 'w')
# Call DFS algorithm
counter = find_solution_DFS(board, counter=0)
results.close()
print("--- It took %s seconds to find a solution ---" % (time.time() - start_time))
# if user asked for DFS algorithm
elif sys.argv[1] == 'best':
# estimate game board's size
width, height = readfile(board)
results = open(sys.argv[3], 'w')
# Call BFS algorithm
counter = find_solution_BFS(board, counter=0)
results.close()
print("--- It took %s seconds to find a solution ---" % (time.time() - start_time))
# if user input wrong algorithm name
else:
print('You have put wrong method') |
64c38b12e17bcb0a43e450543252adeea2010817 | chebread/findText | /Terminal/exec.py | 811 | 3.828125 | 4 | # 파일에서 문자열 찾기 (terminal)
import os.path
import sys
def Isfile(file): # 파일이 존재하는가 ?
if os.path.isfile(file):
return 1 # 있어요
else:
return -1 # 없어요
def Find(file, text):
isfile = Isfile(file)
if isfile == -1:
return -1
load = open(file, "rb")
_read_ = load.read()
load.close()
decoding = _read_.decode(encoding = "utf-8") # Bytes -> Str
if decoding.find(text) == -1:
return -1
else:
return 1
def TextInput():
text = sys.argv[2]
if text == "q":
return exit()
return text
def PathInput():
file = sys.argv[1]
if file == "q":
return exit()
return file # 경로를 반환해요
path = PathInput()
text = TextInput()
find = Find(path, text)
print(find)
|
056309b99eb0f20cb9ef3ab0fc211602718f3f1f | muvekat/nummethods | /lab2tsk1newthon.py | 531 | 3.84375 | 4 | import copy, math, cmath
def Newton(f, dfdx, x, eps):
f_value = f(x)
it = 0
while True:
prev_x = x
x = x - float(f_value)/dfdx(x)
f_value = f(x)
it += 1
if abs(x - prev_x) < eps:
return x, it
def f(x):
return x**3 + x**2 - x - 0.5
def dfdx(x):
return 3*x**2 + 2*x - 1
def main():
print("Epsilon:")
eps = float(input())
x, it = Newton(f, dfdx, 0.5, eps)
print("X:")
print(x)
print("Number of iterations:")
print(it)
if __name__ == '__main__':
main()
|
8f15111bdab7c53803b54f1a36289f2f468c6348 | Jacobb200/ComputerScience3 | /Phone_Number.py | 1,636 | 3.578125 | 4 | """Assignment 02 - 09 Jacob B,"""
class phoneNumber:
# Class Constants
DEFAULT_NUMBER = "0000000000"
def __init__(self, phone_num=DEFAULT_NUMBER):
# Initializes the instance variables
self._phone_num = phone_num
# Sanity checks for the phone_number
try:
self.phone_number = self._phone_num
except TypeError:
self._phone_num = self.DEFAULT_NUMBER
@property
def phone_number(self):
"""Getter for the phone number"""
return self._phone_num
@phone_number.setter
def phone_number(self, new_phone_number):
"""Setter for phone number that is inputted"""
if self.get_valid_num(new_phone_number) is None:
raise TypeError
# else
self._phone_num = self.get_valid_num(new_phone_number)
@staticmethod
def extract_digits(new_phone_num):
"""Extracts the numbers in inputted string and adds into new string"""
extracted_num = ""
for i in new_phone_num:
if i.isdigit():
extracted_num += i
return extracted_num
@classmethod
def get_valid_num(cls, new_phone_num):
"""Checks for the length of the num inputted, returns extracted num"""
if 10 <= len(new_phone_num) <= 20:
return cls.extract_digits(new_phone_num)
return None
def __str__(self):
"""Returns the digits to be printed in the client code"""
return f"({self._phone_num[0:3]}) " \
f"{self._phone_num[3:6]}-" \
f"{self.extract_digits(self._phone_num)[6:len(self._phone_num)]}"
|
31157a1f3b21b680b86c67ece8fe22898b3f8580 | Jacobb200/ComputerScience3 | /Phone_Number_client.py | 347 | 3.953125 | 4 | from Phone_Number import phoneNumber
phone_num1 = phoneNumber("***650--688--0850***#")
print(f"Phone number for phone_num1 is {phone_num1}")
phone_num2 = phoneNumber("***650--688--0850**#")
print(f"Phone number for phone_num1 is {phone_num2}")
""""
Phone number for phone_num1 is (000) 000-0000
Phone number for phone_num1 is (650) 688-0850
""" |
4f8f36ec20bd137cc2423bc1330763257128aef5 | luizamboni/python-type-study | /2-struct.py | 147 | 3.75 | 4 | from typing import Dict, List, Set
# structs
f: Dict[str, str]
f = {
'a': 'b'
}
g: List[int]
g = [1,2,3]
h: Set[int]
h= set()
print(f,g,h) |
3edee7525b3c87debd1525df3dde6ccd470acbea | jindulys/Leetcode | /90-subsets.py | 689 | 3.59375 | 4 | import copy
from sets import Set
class Solution:
# @param S, a list of integer
# @return a list of lists of integer
def subsets(self, S):
n = len(S)
result = self.getSubsets(S,n)
return result
def getSubsets(self,S,n):
result = []
if n == 0:
return []
for i in xrange(n):
S_copy = copy.deepcopy(S)
del S_copy[i]
tmp = self.getSubsets(S_copy, n-1)
for t in tmp:
result.append(t)
result.append(S)
return result
if __name__ == '__main__':
s = Solution()
myAns = s.subsets([1,2,3,4])
print myAns
|
a79f1c2fc6391d0032cceafe73e3530784105c14 | jindulys/Leetcode | /minStack.py | 1,531 | 3.703125 | 4 | class MinStack:
# @param x, an integer
# @return an integer
def __init__(self):
self.myList = []
self.topIndex = -1
self.minIndex = []
self.minTop = -1
def push(self, x):
self.myList.append(x)
self.topIndex = self.topIndex+1
if self.minTop == -1:
self.minIndex.append(self.topIndex)
self.minTop = self.minTop + 1
else:
currentMin = self.minIndex[self.minTop]
if x < self.myList[currentMin]:
self.minIndex.append(self.topIndex)
self.minTop = self.minTop + 1
# @return nothing
def pop(self):
if self.topIndex == self.minIndex[self.minTop]:
# First remove minIndex
del self.minIndex[self.minTop]
self.minTop = self.minTop - 1
del self.myList[self.topIndex]
self.topIndex = self.topIndex - 1
# @return an integer
def top(self):
return self.myList[self.topIndex]
# @return an integer
def getMin(self):
min = None
if self.minTop != -1:
min = self.myList[self.minIndex[self.minTop]]
return min
if __name__ == "__main__":
stack = MinStack()
stack.push(100)
stack.push(10)
stack.push(19)
stack.push(1)
stack.push(1001)
print stack.top() #print 1001
print stack.getMin() #print 1
stack.pop()
stack.pop()
print stack.getMin() #print 10
|
b6757bb87853eb6476f6b445827df2a660bd8e98 | jindulys/Leetcode | /sortList.py | 1,319 | 3.9375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
if head == None or head.next == None:
return head
fast = head
slow = head
while fast.next != None and fast.next.next != None:
fast = fast.next.next
slow = slow.next
fast = slow.next
slow.next = None
slow = head
slow = self.sortList(slow)
fast = self.sortList(fast)
result = self.mergeList(slow, fast)
return result
def mergeList(self,node1, node2):
dummy = ListNode(0)
if node1 == None:
return node2
elif node2 == None:
return node1
tmp = dummy
while node1 != None and node2 != None:
if node1.val > node2.val:
tmp.next = node2
node2 = node2.next
else:
tmp.next = node1
node1 = node1.next
tmp = tmp.next
if node1 == None:
tmp.next = node2
else:
tmp.next = node1
return dummy.next
|
0254ed479c00b3f5140df3546c06612dca233557 | Andriy63/- | /lesson 4-4.py | 686 | 4.15625 | 4 | '''
Представлен список чисел. Определить элементы списка, не имеющие повторений.
Сформировать итоговый массив чисел, соответствующих требованию.
Элементы вывести в порядке их следования в исходном списке.
Для выполнения задания обязательно использовать генератор.'''
from itertools import permutations
from itertools import repeat
from itertools import combinations
my_list = [1, 2, 2, 3, 4, 1, 2]
new = [el for el in my_list if my_list.count(el)==1]
print(new) |
4b8f690cb618bb443380333e392b745c2437b9d7 | Andriy63/- | /lesson 2.py | 3,582 | 3.65625 | 4 | # 1
mylist = ['boy', 12, [], {}, 'year']
print(list(map(type, mylist)))
# 2
l = [2, 1, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(0, len(l), 2):
old = l[i]
l[i] = l[i + 1]
l[i + 1] = old
print(l)
# 3
year = {1: 'january', 2: 'february', 3: ' march', 4: 'april', 5: 'may', 6: 'june',
7: 'july', 8: 'august', 9: 'september', 10: 'october', 11: 'november', 12: 'december'}
a = print(year.keys())
if a == 1 or 2 or 12:
print('Winter')
if a == 3 or 4 or 5:
print('Sping')
if a == 6 or 7 or 8:
print('Summer')
if a == 9 or 10 or 11:
print('Autumn')
else:
print('Error')
# второй вариант
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
if a == 1 or 2 or 12:
print('Winter')
if a == 3 or 4 or 5:
print('Sping')
if a == 6 or 7 or 8:
print('Summer')
if a != 9 and not 10:
print('Error')
else:
print('Autumn')
# 4
my_str = 'зима весна лето осень тепло холодно жарко'
my_word = []
num = 1
for el in range(my_str.count(' ') + 1):
my_word = my_str.split()
if len(str(my_word)) <= 10:
print(f" {num} {my_word[el]}")
num += 1
else:
print(f" {num} {my_word[el][0:10]}")
num += 1
# 5
my_list = [9, 8, 7, 5, 3, 3, 2]
print(f"Рейтинг - {my_list}")
digit = int(input(6))
while digit != 10:
for el in range(len(my_list)):
if my_list[el] == digit:
my_list.insert(el + 1, digit)
break
elif my_list[0] < digit:
my_list.insert(0, digit)
elif my_list[-1] > digit:
my_list.append(digit)
elif my_list[el] > digit and my_list[el + 1] < digit:
my_list.insert(el + 1, digit)
print(f"текущий список - {my_list}")
digit = int(input(6))
print(my_list)
# 6
var = [
(1, {'name': 'computer', 'price': 20000, 'amount': 5, 'units': 'one'}),
(2, {'name': 'printer', 'price': 6000, 'amount': 2, 'units': 'one'}),
(3, {'name': 'scanner', 'price': 2000, 'amount': 7, 'units': 'one'})
]
var = {
'name' : [ 'computer', 'printer', 'scanner'],
'price' : [20000, 6000, 2000],
'amount' : [5, 2, 7],
'units': 'one'
}
goods = []
features = {'name': '', 'price': '', ' amount': '', 'units': ''}
analytics = {'name': [], 'price': [], ' amount': [], 'units': []}
num = 0
feature_ = None
control = None
while True:
control = input("For quit press 'Q', for continue press 'Enter', for analytics press 'A'").upper()
if control == 'Q':
break
num += 1
if control == 'A':
print(f'\n Current analytics \n {"-" * 30}')
for key, value in analytics.items():
print(f'{key[:25]:>30}: {value}')
print("-" * 30)
for f in features.keys():
feature_ = input(f'Input feature "{f}"')
features[f] = int(feature_) if (f == 'price' or f == ' amount') else feature_
analytics[f].append(features[f])
goods.append((num, features))
goods = int(input(3))
n = 1
my_dict = []
my_list = []
my_analys = {}
while n <= goods:
my_dict = dict({ 'name': input("введите название "), 'price' : input("Введите цену "),
' amount' : input('Введите количество '), 'eд': input("Введите единицу измерения ")})
my_list.append((n, my_dict))
n += 1
my_analys = dict(
{ 'name' : my_dict.get('название'), 'price' : my_dict.get('цена'), ' amount': my_dict.get('количество'),
'units' : my_dict.get('ед')})
print(my_list)
print(my_analys)
|
a7f1790524dd1d056f6b29c0b2d389afaac889b0 | laialanza/P1-Laia | /rgb_yuv.py | 621 | 3.546875 | 4 | def YUVfromRGB(R, G, B):
Y = 0.257 * R + 0.504 * G + 0.098 * B + 16
U = -0.148 * R - 0.291 * G + 0.439 * B + 128
V = 0.439 * R - 0.368 * G - 0.071 * B + 128
return Y,U,V
def RGBfromYUV(Y, U, V):
Y -=16
U-=128
V -=128
R = 1.164 * Y + 1.596 * V
G = 1.164 * Y - 0.392 * U - 0.813 * V
B = 1.164 * Y + 2.017 * U
return (R,G,B)
R = int(input("Intorduce the R value\n"))
G = int(input("Intorduce the G value\n"))
B = int(input("Intorduce the B value\n"))
a = YUVfromRGB(R,G,B)
print("This are the new YUV values: ", a)
print("Double conversion to check it work properly: ", RGBfromYUV(a[0],a[1],a[2])) |
1a6a7bdd7150e0e08557a728cdb62f87d653aa0e | augustosch/mi_primer_programa | /combate_pokemon.py | 1,142 | 3.984375 | 4 |
pokemon_elegido = input("¿Contra qué Pokemos quieres combatir? (Squirtle / Charmander / Bullbasaur): ")
vida_pikachu = 100
if pokemon_elegido == "Squirtle":
vida_enemigo = 90
nombre_pokemon = "Squirtle"
ataque_pokemon = 8
elif pokemon_elegido == "Charmander":
vida_enemigo = 80
ataque_pokemon = 7
nombre_pokemon = "Charmander"
elif pokemon_elegido == "Bullbasaur":
vida_enemigo = 100
nombre_pokemon = "Bullbasaur"
ataque_pokemon = 10
while vida_pikachu > 0 and vida_enemigo >0:
ataque_elegido = input("¿Qué ataque vamo a usar? (Chispazo / Bola Voltio)")
if ataque_elegido == "Chispazo":
vida_enemigo -= 10
elif ataque_elegido == "Bola Voltio":
vida_pikachu -= 12
print("La vida del {} ahora es de {}".format(nombre_pokemon, vida_enemigo) )
print("{} te hace un ataque de {} de daño".format(nombre_pokemon, ataque_pokemon))
vida_pikachu -= ataque_pokemon
print("La vida de Pikachu es de {}".format(vida_pikachu))
if vida_enemigo <= 0:
print("¡Has Ganado!")
elif vida_pikachu <= 0:
print("¡Has Perdido!")
print("el combate a terminado") |
3dde05cf95b6f3dd8d930e090a3fda960e8f5d42 | vinitkantrod/HackerRank | /Algorithm/DFS_proability_of_reach.py | 1,431 | 3.5625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
# globals
input_list = []
ptr = 0
def path_exists(s,d,graph,visited):
if s == d:
return True
visited.append(s)
adj=graph[s]
for i in adj:
if i not in visited and path_exists(i,d,graph,visited):
return True
return False
def find_probability(N,graph,probs):
probability = 0.0
target = str(N+1)
sorted_list = sorted(graph.keys(),key=int)
for p in sorted_list:
visited = []
if p == target:
continue
if path_exists(p,target,graph,visited):
probability += probs[p]
else:
probability = 0
break
print str(int(probability))
def driver():
global ptr
T = int(input_list.pop(0))
while ptr < len(input_list)-1:
MAIN_GRAPH = {}
probabilities = {}
N = int(input_list[ptr])
for i in range(N+1):
ptr += 1
key = str(ptr)
paths = input_list[ptr].split(' ')[1:]
MAIN_GRAPH[str(i+1)] = paths
ptr += 1
prob_list = input_list[ptr].split(' ')
for idx,val in enumerate(prob_list):
probabilities[str(idx+1)] = float(val)
find_probability(N,MAIN_GRAPH,probabilities)
ptr += 1
return MAIN_GRAPH
# main
for line in sys.stdin:
input_list.append(line.strip())
driver()
|
9933a3b31cd139f4bfb736a5ae45d6c56f7760a3 | vinitkantrod/HackerRank | /alternating-characters.py | 431 | 3.53125 | 4 | def alternative(stri,de):
l = len(s)
for j in range(l):
if(stri[j]=='a'):
if(((j+1)>l) and (stri[j+1]=='a')):
de = de + 1
if(stri[j]=='b'):
if(((j+1)>l) and (stri[j+1]=='b')):
de = de + 1
return de
no = raw_input()
no = int(no)
v = []
for i in range(no):
d = 0
s = raw_input()
s = s.lower()
dele = alternative(s,d)
print dele
|
21455fe40cb7f7adcc7a69bc559ed363e3cad386 | mohitciet/CorePython | /LearnPython/PythonBasics/OOPS_Inheritance_Polymorphism.py | 638 | 3.890625 | 4 | class Person(object):
def __init__(self,name):
self.name=name
def getName(self):
return self.name
def isEmployee(self):
return False
p1= Person("Harry")
print(p1.getName())
print(p1.isEmployee())
print("================")
class ChildClass(Person):
def isEmployee(self):
return True
c1=ChildClass("Tom")
print(c1.getName())
print(c1.isEmployee()) #Method Overiding
#Method Overloading
class Human :
def getName(self,name=None):
if name is None:
print("First Case")
else:
print("Second Case")
h1=Human()
h1.getName()
h1.getName("A")
|
440fb62ef8a3a4144b3082ca38c478fc78357c6b | mohitciet/CorePython | /LearnPython/PythonBasics/Dictionary.py | 2,077 | 4.3125 | 4 | """DICTIONARY"""
dictionary={'key1' : 'india','key2' : 'USA'}
#Access Elements from Dictionary
print(dictionary['key1'])
print("===================")
#Adding Elements from Dictionary
dictionary={'key1' : 'india','key2' : 'USA'}
dictionary['key3']='Pakistan'
print(dictionary)
print("===================")
#Modify Elements from Dictionary
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
dictionary['key3']='Aus'
print(dictionary)
print("===================")
#Delete Elements from Dictionary
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
del dictionary['key3']
print(dictionary)
print("===================")
#Looping to Iterate the Dictionary
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
for x in dictionary:
print(x +" : "+dictionary[x])
print("===================")
#Length of a Dictionary
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
print(len(dictionary))
print("===================")
#Equallity Test in Dictionary
dictionary1={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
dictionary2={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
dictionary3={'key1' : 'india','key2' : 'USA'}
print(dictionary1==dictionary2)
print(dictionary1==dictionary3)
print("===================")
#Functions in Dictionary
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
print(dictionary.popitem()) #Returns random element and removed from Dictionary
print(dictionary)
print("===================")
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
print(dictionary.keys()) #Returns all keys as tuple Format
print("<><><><>")
print(dictionary.values()) #Returns all values as tuple Format
print("<><><><>")
print(dictionary.get('key1')) #Returns value on the basis of key,if key invalid it returns None
print("<><><><>")
print(dictionary.pop('key5')) #Delete value on the basis of key,if key invalid it throws exception
print("<><><><>")
print(dictionary.clear()) #Delete Everything from Dictionary
print(dictionary)
print("<><><><>")
print("===================") |
d8646f6f1e0173693fd08bb76bd1491603456b74 | mohitciet/CorePython | /LearnPython/PythonBasics/IfElseConcept.py | 157 | 4.0625 | 4 | a=10
if(a<0):
print("a is a negative number")
elif(a>0):
print("a is a postive number")
else:
print("a is a zero")
print("number is : "+str(a))
|
1506a8ea3f9f4e7e05c2a16541d5ae8c0af91047 | kylegalloway/CS403 | /Project/prettyPrinter.py | 11,136 | 3.703125 | 4 | from parser import Parser
def main(filename):
p = Parser(filename)
parse_tree = p.parse()
prettyPrint(parse_tree)
print()
def prettyPrint(tree):
if(tree != None):
# printf(tree.ltype + " ", end="")
if(tree.ltype == "PARSE"):
printPARSE(tree)
elif(tree.ltype == "PROGRAM"):
printPROGRAM(tree)
elif(tree.ltype == "DEFINITION"):
printDEFINITION(tree)
elif(tree.ltype == "VARDEF"):
printVARDEF(tree)
elif(tree.ltype == "FUNCDEF"):
printFUNCDEF(tree)
elif(tree.ltype == "IDDEF"):
printIDDEF(tree)
elif(tree.ltype == "ARRAYACCESS"):
printARRAYACCESS(tree)
elif(tree.ltype == "FUNCCALL"):
printFUNCCALL(tree)
elif(tree.ltype == "OPTPARAMLIST"):
printOPTPARAMLIST(tree)
elif(tree.ltype == "PARAMLIST"):
printPARAMLIST(tree)
elif(tree.ltype == "OPTEXPRLIST"):
printOPTEXPRLIST(tree)
elif(tree.ltype == "EXPRLIST"):
printEXPRLIST(tree)
elif(tree.ltype == "EXPR"):
printEXPR(tree)
elif(tree.ltype == "PRIMARY"):
printPRIMARY(tree)
elif(tree.ltype == "OPERATOR"):
printOPERATOR(tree)
elif(tree.ltype == "BLOCK"):
printBLOCK(tree)
elif(tree.ltype == "OPTSTATEMENTLIST"):
printOPTSTATEMENTLIST(tree)
elif(tree.ltype == "STATEMENTLIST"):
printSTATEMENTLIST(tree)
elif(tree.ltype == "STATEMENT"):
printSTATEMENT(tree)
elif(tree.ltype == "WHILELOOP"):
printWHILELOOP(tree)
elif(tree.ltype == "IFSTATEMENT"):
printIFSTATEMENT(tree)
elif(tree.ltype == "OPTELSESTATEMENT"):
printOPTELSESTATEMENT(tree)
elif(tree.ltype == "ELSESTATEMENT"):
printELSESTATEMENT(tree)
elif(tree.ltype == "ELSEIFSTATEMENT"):
printELSEIFSTATEMENT(tree)
elif(tree.ltype == "LAMBDA"):
printLAMBDA(tree)
elif(tree.ltype == "JOIN"):
printJOIN(tree)
elif(tree.ltype == "STRING"):
printSTRING(tree)
elif(tree.ltype == "INTEGER"):
printINTEGER(tree)
elif(tree.ltype == "FUNCTION"):
printFUNCTION(tree)
elif(tree.ltype == "VAR"):
printVAR(tree)
elif(tree.ltype == "WHILE"):
printWHILE(tree)
elif(tree.ltype == "IF"):
printIF(tree)
elif(tree.ltype == "ELSE"):
printELSE(tree)
elif(tree.ltype == "RETURN"):
printRETURN(tree)
elif(tree.ltype == "INCLUDE"):
printINCLUDE(tree)
elif(tree.ltype == "ID"):
printID(tree)
elif(tree.ltype == "SEMI"):
printSEMI(tree)
elif(tree.ltype == "COMMA"):
printCOMMA(tree)
elif(tree.ltype == "OPAREN"):
printOPAREN(tree)
elif(tree.ltype == "CPAREN"):
printCPAREN(tree)
elif(tree.ltype == "OBRACE"):
printOBRACE(tree)
elif(tree.ltype == "CBRACE"):
printCBRACE(tree)
elif(tree.ltype == "OBRACKET"):
printOBRACKET(tree)
elif(tree.ltype == "CBRACKET"):
printCBRACKET(tree)
elif(tree.ltype == "PLUS"):
printPLUS(tree)
elif(tree.ltype == "MINUS"):
printMINUS(tree)
elif(tree.ltype == "TIMES"):
printTIMES(tree)
elif(tree.ltype == "DIVIDE"):
printDIVIDE(tree)
elif(tree.ltype == "MODULO"):
printMODULO(tree)
elif(tree.ltype == "EXPONENT"):
printEXPONENT(tree)
elif(tree.ltype == "AMPERSAND"):
printAMPERSAND(tree)
elif(tree.ltype == "PERIOD"):
printPERIOD(tree)
elif(tree.ltype == "BAR"):
printBAR(tree)
elif(tree.ltype == "GREATEREQUAL"):
printGREATEREQUAL(tree)
elif(tree.ltype == "GREATER"):
printGREATER(tree)
elif(tree.ltype == "LESSEQUAL"):
printLESSEQUAL(tree)
elif(tree.ltype == "LESS"):
printLESS(tree)
elif(tree.ltype == "DOUBLEEQUAL"):
printDOUBLEEQUAL(tree)
elif(tree.ltype == "EQUAL"):
printEQUAL(tree)
elif(tree.ltype == "NOTEQUAL"):
printNOTEQUAL(tree)
elif(tree.ltype == "NOT"):
printNOT(tree)
elif(tree.ltype == "NIL"):
printNIL(tree)
elif(tree.ltype == "TRUE"):
printTRUE(tree)
elif(tree.ltype == "FALSE"):
printFALSE(tree)
elif(tree.ltype == "PRINT"):
printPRINT(tree)
elif(tree.ltype == "APPEND"):
printAPPEND(tree)
elif(tree.ltype == "REMOVE"):
printREMOVE(tree)
elif(tree.ltype == "BOOLEAN"):
printBOOLEAN(tree)
elif(tree.ltype == "END_OF_INPUT"):
print("\n" + " ", end="")
else:
print("ERROR: "+tree.ltype+" : "+tree.lvalue + " ", end="")
def printPARSE(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printPROGRAM(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printDEFINITION(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printVARDEF(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printFUNCDEF(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printIDDEF(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printARRAYACCESS(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printFUNCCALL(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printOPTPARAMLIST(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printPARAMLIST(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printOPTEXPRLIST(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printEXPRLIST(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printEXPR(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printPRIMARY(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printOPERATOR(tree):
l = tree.left
r = tree.right.left
op = tree.lvalue.left
prettyPrint(l)
prettyPrint(op)
prettyPrint(r)
def printBLOCK(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printOPTSTATEMENTLIST(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printSTATEMENTLIST(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printSTATEMENT(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printWHILELOOP(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printIFSTATEMENT(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printOPTELSESTATEMENT(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printELSESTATEMENT(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printELSEIFSTATEMENT(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printLAMBDA(tree):
print(tree.left)
prettyPrint(tree.right)
def printJOIN(tree):
if(tree.left):
prettyPrint(tree.left)
if(tree.right):
prettyPrint(tree.right)
def printSTRING(tree):
print(tree.lvalue + " ", end="")
def printINTEGER(tree):
print(tree.lvalue + " ", end="")
def printFUNCTION(tree):
print(tree.lvalue + " ", end="")
def printVAR(tree):
print(tree.lvalue + " ", end="")
def printWHILE(tree):
print(tree.lvalue + " ", end="")
def printIF(tree):
print(tree.lvalue + " ", end="")
def printELSE(tree):
print(tree.lvalue + " ", end="")
def printRETURN(tree):
print(tree.lvalue + " ", end="")
def printINCLUDE(tree):
print(tree.lvalue + " ", end="")
def printID(tree):
print(tree.lvalue + " ", end="")
def printSEMI(tree):
print(tree.lvalue + "\n", end="")
def printCOMMA(tree):
print(tree.lvalue + " ", end="")
def printOPAREN(tree):
print(tree.lvalue, end="")
def printCPAREN(tree):
print(tree.lvalue, end="")
def printOBRACE(tree):
print(tree.lvalue + "\n", end="")
def printCBRACE(tree):
print(tree.lvalue + "\n\n", end="")
def printOBRACKET(tree):
print(tree.lvalue, end="")
def printCBRACKET(tree):
print(tree.lvalue, end="")
def printPLUS(tree):
print(tree.lvalue + " ", end="")
def printMINUS(tree):
print(tree.lvalue + " ", end="")
def printTIMES(tree):
print(tree.lvalue + " ", end="")
def printDIVIDE(tree):
print(tree.lvalue + " ", end="")
def printMODULO(tree):
print(tree.lvalue + " ", end="")
def printEXPONENT(tree):
print(tree.lvalue + " ", end="")
def printAMPERSAND(tree):
print(tree.lvalue + " ", end="")
def printPERIOD(tree):
print(tree.lvalue + " ", end="")
def printBAR(tree):
print(tree.lvalue + " ", end="")
def printGREATEREQUAL(tree):
print(tree.lvalue + " ", end="")
def printGREATER(tree):
print(tree.lvalue + " ", end="")
def printLESSEQUAL(tree):
print(tree.lvalue + " ", end="")
def printLESS(tree):
print(tree.lvalue + " ", end="")
def printDOUBLEEQUAL(tree):
print(tree.lvalue + " ", end="")
def printEQUAL(tree):
print(tree.lvalue + " ", end="")
def printNOTEQUAL(tree):
print(tree.lvalue + " ", end="")
def printNOT(tree):
print(tree.lvalue + " ", end="")
def printNIL(tree):
print(tree.lvalue + " ", end="")
def printBOOLEAN(tree):
print(str(tree.lvalue) + " ", end="")
def printPRINT(tree):
print(tree.left.lvalue + " ", end="")
prettyPrint(tree.right)
def printAPPEND(tree):
print(tree.left.lvalue + " ", end="")
prettyPrint(tree.right)
def printREMOVE(tree):
print(tree.left.lvalue + " ", end="")
prettyPrint(tree.right)
import sys
if(len(sys.argv) == 2):
filename = sys.argv[1]
else:
filename = "redwall/program.rwall"
main(filename)
|
e9bf4f58421ccd1a104729718f1f76608f15aa47 | jonnrauber/first-follow | /first_follow.py | 7,954 | 3.625 | 4 | from Estado import *
###GLOBAL VARIABLES###
i_line = 1
Estados = []
has_changed = True
pos_estado = None
pos_estado_atual = None
all_have_eps = True
######################
################### PRINT FUNCTIONS #######################
#Print the first sets
def imprime_first():
global Estados
print("CONJUNTOS FIRST")
for estado in Estados:
print(estado.nome + " -> {", end="")
for i in range(0, len(estado.first)):
if i:
print(", ", end="")
print(estado.first[i], end="")
print("}")
#Print the follow sets
def imprime_follow():
global Estados
print("CONJUNTOS FOLLOW")
for estado in Estados:
print(estado.nome + " -> {", end="")
for i in range(0, len(estado.follow)):
if i:
print(", ", end="")
print(estado.follow[i], end="")
print("}")
##############################################################
##################### UTIL FUNCTIONS #########################
#Splits a string between '<' and '>' characters to obtain the NonTerminal Symbol
def splitNT(line):
global i_line
NT = "" #NonTerminal symbol
if line[i_line] == '<':
i_line += 1
while line[i_line] != '>':
NT = NT + line[i_line]
i_line += 1
return NT
#Verifies if a determinated state exists in the list of states (Estados)
def exists_estado(estado):
for i in Estados:
if estado == i.nome:
return True
return False
#Search the position of a state in the list (Estados)
def search_pos_estado(estado):
for i in range(0, len(Estados)):
if Estados[i].nome == estado:
return i
#################################################################
############### FUNCTIONS TO FIND FIRST SET #####################
#Retorna True se terminou de ler a produção e Falso se precisa continuar lendo
def read_production_first(line):
global i_line, Estados, has_changed, pos_estado_atual, pos_estado
if line[i_line] != '<' and line[i_line] != '>':
#If production's first symbol is Terminal,
#verifies if it already exists in state's first set.
if line[i_line] not in Estados[pos_estado_atual].first:
Estados[pos_estado_atual].first.append(line[i_line])
#print("First(" + Estados[pos_estado_atual].nome + ") <- " + line[i_line])
has_changed = True
i_line += 1
return True
else:
#If production's first symbol is NonTerminal,
#copy the first set corresponding to it into current state.
estado = splitNT(line)
if exists_estado(estado):
pos_estado = search_pos_estado(estado)
for i in Estados[pos_estado].first:
if i not in Estados[pos_estado_atual].first and i != 'ε':
Estados[pos_estado_atual].first.append(i)
#print("First(" + Estados[pos_estado_atual].nome + ") <- " + i)
has_changed = True
if 'ε' not in Estados[pos_estado].first:
return True
else:
return True
i_line += 1
if(line[i_line] == ' ' or line[i_line] == '|' or line[i_line] == '\n'):
if 'ε' not in Estados[pos_estado_atual].first:
Estados[pos_estado_atual].first.append('ε')
return False
#Receives a line from the external file and executes the verification of
#the First Set Algorithm.
def read_line_first(line):
global i_line, has_changed, Estados, pos_estado, pos_estado_atual, all_have_eps
i_line = 1
estado = splitNT(line)
if exists_estado(estado):
pos_estado_atual = search_pos_estado(estado)
else:
Est = Estado()
Est.nome = estado
Estados.append(Est)
pos_estado_atual = len(Estados)-1
while (line[i_line] == ' ' or line[i_line] == '>' or line[i_line] == ':'
or line[i_line] == '='):
i_line += 1
while line[i_line] != '\n':
while line[i_line] != ' ' and line[i_line] != '\n':
if read_production_first(line) == True:
break
while line[i_line] != '|':
if line[i_line] == '\n': return #Current line is over, end function
i_line += 1
i_line += 1
while line[i_line] == ' ':
i_line += 1
#Everytime has_changed is set, it means some first set has changed in last iteration;
#so, the function reopen the file and iterate over it again.
def resolve_first():
global i_line, Estados, has_changed
#open file in read mode
has_changed = False;
with open("GLC.txt", "r") as File:
for line in File:
read_line_first(line)
################# FUNCTIONS TO FIND FOLLOW SETS ######################
#Receives a line from the external file and executes the verification of the first part of the Follow Set algorithm.
def read_line_follow(line):
global i_line, Estados, has_changed
i_line = 1
estado = splitNT(line)
while (line[i_line] == ' ' or line[i_line] == '>' or line[i_line] == ':'
or line[i_line] == '='):
i_line += 1
while line[i_line] != '\n':
while line[i_line] == '|' or line[i_line] == ' ':
i_line += 1
if line[i_line] == '<':
i_line += 1
est = splitNT(line)
i_line += 1
if line[i_line] == '<':
i_line += 1
est2 = splitNT(line)
for i in Estados:
if i.nome == est2:
for j in Estados:
if j.nome == est:
for k in i.first:
if k not in j.follow and k != 'ε':
j.follow.append(k)
i_line -= 1
while line[i_line] != '<':
i_line -= 1
i_line -= 1
else:
if(line[i_line] != '\n'):
for i in Estados:
if i.nome == est:
if line[i_line] not in i.follow and line[i_line] != 'ε' and line[i_line] != ' ':
i.follow.append(line[i_line])
if line[i_line] != '\n':
i_line += 1
#Receives a line from the external file and executes the verification of the second part of the Follow Set algorithm.
def read_line_follow2(line):
global i_line, Estados, has_changed, all_have_eps
all_have_eps = True
fim_producao = False
i_line = 1
estado = splitNT(line)
while (line[i_line] == ' ' or line[i_line] == '>' or line[i_line] == ':'
or line[i_line] == '='):
i_line += 1
while line[i_line] != '\n':
while line[i_line] != '|' and line[i_line] != '\n':
i_line += 1
while line[i_line] == '\n' or line[i_line] == ' ' or line[i_line] == '|':
i_line -= 1
all_have_eps = True
fim_producao = False
if line[i_line] == '>':
while all_have_eps == True and fim_producao == False:
while line[i_line] != '<':
if(line[i_line] == '=' or line[i_line] == '|'):
fim_producao = True
break
i_line -= 1
i_line += 1
est = splitNT(line)
for i in Estados:
if i.nome == estado:
for j in Estados:
if j.nome == est:
if 'ε' in j.first:
all_have_eps = True
else:
all_have_eps = False
for k in i.follow:
if k not in j.follow:
has_changed = True
j.follow.append(k)
while line[i_line] != '<':
i_line -= 1
i_line -= 1
while line[i_line] != '\n' and line[i_line] != '|':
i_line += 1
if line[i_line] == '|':
i_line += 1
#the function open the file and iterate over it.
def resolve_follow():
global i_line, Estados, has_changed
#open file in read mode
has_changed = False;
with open("GLC.txt", "r") as File:
for line in File:
read_line_follow(line)
#Everytime has_changed is set, it means some follow set has changed in last iteration;
#so, the function reopen the file and iterate over it again.
def resolve_follow2():
global i_line, Estados, has_changed
#open file in read mode
has_changed = False;
with open("GLC.txt", "r") as File:
for line in File:
read_line_follow2(line)
#Put the "Dollar Sign" ($) in the initial state's follow set.
def put_dollar_sign():
global Estados
for e in Estados:
if e.nome == 'S':
e.follow.append('$')
return
######################################################################
#Main Function
def main():
global Estados, has_changed
##### FIRST ######
has_changed = True
while has_changed:
resolve_first()
##################
##### FOLLOW #####
put_dollar_sign()
resolve_follow()
has_changed = True
while has_changed:
resolve_follow2()
##################
##### PRINT RESULTS #####
imprime_first()
imprime_follow()
#########################
####### EXECUTE PROGRAM ######
main()
|
599e389fd6a37b9119e663c23bb75c67e686d90e | lukelu389/programming-class | /python_demo_programs/2020/example_20201127.py | 2,582 | 4.03125 | 4 | # practice
# Below are the two lists convert it into the dictionary
# keys = ['Ten', 'Twenty', 'Thirty', 'Hello']
# values = [10, 20, 30, 'Hi']
# expected output: {'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Hello': 'Hi'}
# create a dictionary from two lists, one list has all keys, one list has all values
def build_dictionary(keys, values):
dic = {}
for i in range(len(keys)):
dic[keys[i]] = values[i]
return dic
# homework
# merge following two dictionaries into one
# dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
# dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
# expected output
# hidden condition: for the same keys in both dictionary, they have the same value
# {'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
def merge(dic1, dic2):
# loop through dic1, put each key value into dic2, and return dic2
for key, value in dic1.items():
if key not in dic2:
dic2[key] = value
else:
dic2[key] = dic1[key] + dic2[key]
return dic2
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
print(merge(dict1, dict2))
# merge following two dictionaries into one
# for the same key in both dictionary, combine the value
# dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
# dict2 = {'Thirty': 300, 'Fourty': 40, 'Fifty': 50}
# expected output
# {'Ten': 10, 'Twenty': 20, 'Thirty': 330, 'Fourty': 40, 'Fifty': 50}
# dic = {}
# s = set()
# student = {'Atonio', 'Tim'}
# print(type(student))
# l = [1, 1, 1, 1]
# s = set(l)
# print(s)
#
# s.add(2)
# print(s)
#
# s.add(1)
# print(s)
#
# s.remove(1)
# print(s)
# s.remove(1)
# print(s)
# basket = {'orange', 'banana', 'pear', 'apple'}
# print(basket)
# for fruit in basket:
# print(fruit, end=':)')
empty_set = set()
empty_set.add(1)
print(empty_set)
empty_set.update({2, 3, 4})
print(empty_set)
# exercise
# how to determine if a string has no duplicate characters
# s = "abc"
# s = "aab"
# s = "abc"
# if len(s) == len(set(s)):
# print('none duplicate characters')
# a = {1, 2, 3}
# b = {2, 4}
# print(a - b)
# print(b - a)
# homework
# given a dictionary, create a set with all keys and values from the dictionary
# dic = {"one": 1, "two": 2}
# {"one", "two", 1, 2}
dic = {"one": 1, "two": 2}
s = set()
for key, value in dic.items():
s.add(key)
s.add(value)
# set update
s1 = {1, 2}
s2 = {3, 4}
s1.update(1)
s1 = s1 | s2
# equal to
s1 |= s2
# check a given set has no elements in common with other given set
s1 = {1, 2}
s2 = {3, 4}
if len(s1 & s2) == 0:
print("no common") |
8ba63fdd070ef490570285c17d8669b8d8ffb5b0 | lukelu389/programming-class | /python_demo_programs/2020/prime_number.py | 273 | 4.375 | 4 | # write a python program to check if a number is prime or not
number = int(input('enter a number:'))
n = 1
counter = 0
while n <= number:
if number % n == 0:
counter += 1
n += 1
if counter > 2:
print('not prime number')
else:
print('prime number') |
3404c6cc7af2350bf12592921226a9f4a87da618 | lukelu389/programming-class | /python_demo_programs/2021/example_20210319.py | 1,529 | 4.1875 | 4 | # s = 'abcdefgh'
# print(s[0:2])
# print(s[:2]) # implicitly start at 0
# print(s[3:]) # implicitly end at the end
#
# # slice from index 4 to the end
# print(s[4:])
# to achieve the conditional, need to use if keyword
# a = 6
# b = 5
# if b > a:
# print('inside if statement')
# print('b is bigger than a')
# # exit the if
# print('program finish')
# a = a + 1
# input = -9
# if input > 0:
# print('positive')
# else:
# print('not positive')
# a = 2
# b = 3
# using if, else statement, print the bigger number
# if a > b:
# print(a)
# else:
# print(b)
# a = 3
# b = 2
# # given two variables, print the positive variables
# if a > 0
# print(a)
#
# if b > 0:
# print(b)
# given a variable, print the variable if it is the even number
# hint: use % operator to find the even or odd
# a = 3
# if a % 2 == 0:
# print("a is an even number")
# else:
# print("a is an odd number")
# number = 0
# if number > 0:
# print("positive")
# elif number < 0:
# print("negative")
# else:
# print("zero")
# because input() takes all value as string, need convert to int
# by using int()
# a = int(input("enter the value for a:"))
# b = int(input("enter the value for b:"))
#
# if a > b:
# print("a is bigger")
# elif a < b:
# print("b is bigger")
# else:
# print("a is equal to b")
a = int(input("enter a value for a: "))
if a > 0:
print("a is positive")
if a % 2 == 0:
print("a is even")
else:
print("a is odd")
else:
print("a is negative") |
1d4bac21899ddd993ad41cdf80a0c2ad350b8104 | lukelu389/programming-class | /python_demo_programs/2021/example_20210815.py | 1,644 | 4.1875 | 4 | # class Person:
# def __init__(self, name):
# self.name = name
# def method1(self):
# return 'hello'
# p1 = Person('jerry')
# print(p1.name)
# Person.method1()
# class = variables + methods
# variable: static variable vs instance variable
# method: static method vs instance method
# class is customized data structure
# class is the blueprint of object, we use class to create object
class Person:
# constructor
def __init__(self, name, age):
# instance variable is created in the constructor
self.name = name
self.age = age
# instance method
def say_hi(self):
return 'hi'
p1 = Person('jerry', 10)
p2 = Person('tom', 20)
print(p1.name)
print(p1.age)
print(p2.name)
print(p2.age)
p1.say_hi()
p2.say_hi()
class Student:
def __init__(self, student_name, student_id):
self.student_name = student_name
self.student_id = student_id
def get_info(self):
return self.student_name + ":" + str(self.student_id)
def __str__(self):
return self.student_name
peter = Student('peter', 1)
print(peter.get_info())
print(peter)
class Grade:
def __init__(self):
self.grades = []
'''
Give two dictionaries, create thrid dictionary with the unique key and value from both dictionaries
d1 = {'a': 1, 'b': 3, 'c': 2}
d2 = {'a': 2, 'b': 2, 'd': 3}
d3 = {'c': 2, 'd': 3}
'''
d1 = {'a': 1, 'b': 3, 'c': 2}
d2 = {'a': 2, 'b': 2, 'd': 3}
d3 = {}
for key1, value1 in d1.items():
if key1 not in d2:
d3[key1] = value1
for key2, value2 in d2.items():
if key2 not in d1:
d3[key2] = value2
print(d3)
|
2ad3a01fc1c2ef2e1e45304656cd37e027a1b85d | lukelu389/programming-class | /python_demo_programs/2021/example_20210207.py | 403 | 3.65625 | 4 | # list = [0, 1, 2, 3]
# [1, 3, 5, 7]
# [i*2+1 for i in list]
list = [3, 8, 9, 5]
# res = []
# for i in list:
# if i % 3 == 0:
# res.append(True)
# else:
# res.append(False)
res = [True if i % 3 == 0 else False for i in list]
list = ['apple', 'orange', 'pear']
res = []
for i in list:
res.append(i[0].upper())
res = [i[0].upper() for i in list]
[(i, len(i)) for i in list] |
92c67fbb46180ca6d3abc13cdbf9fb24d005cefb | lukelu389/programming-class | /python_demo_programs/2021/example_20210126.py | 2,619 | 3.78125 | 4 | # questions = ['name', 'quest', 'favorite color']
# answers = ['lancelot', 'the holy grail', 'blue']
# l = (1, 2)
# # for i in questions:
# # print(i)
# # for i in answers:
# # print(i)
#
# # print(zip(questions, answers))
# # zip(questions, answers) -> [('name', 'lancelot'), ('quest', 'the holy grail'), ('favorite color', 'blue')]
# for i in zip(questions, answers, l):
# print(i)
# l1 = [1, 2, 3]
# l2 = [2, 4, 5]
# # [3, 6, 8]
# l = []
# for i, j in zip(l1, l2):
# l.append(i + j)
# l = (3, 2, 1)
# l = sorted(l)
# print(l)
#
# a = [3, 4, 1]
# a.sort()
# print(a)
#
# basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
# # remove the duplicate and sort the list
# basket = sorted(set(basket))
# print(basket)
# def power(x):
# return x ** 2
#
# l = [power(x) for x in range(10)]
# l = [2, 3, -4, -5]
# res = ['positive' if i > 0 else 'not positive' for i in l]
# print(res)
#
# # given [3, 8, 9, 5] generate a new list, inside the list if the number is divisible by 3,
# # append True, else append False
# numbers = [3, 8, 9, 5]
# res = [True if i % 3 == 0 else False for i in numbers]
# l = [(i,j) for i in range(5) for j in range(i)]
# print(l)
# l = []
# for i in range(5):
# for j in range(i):
# l.append((i, j))
# homework
# solve the question use anything you learned so far
# given a list of numbers and an integer called target,
# find two numbers from the list such that they add up to target
# it's guaranteed in the list that such pair exists
# [3, 2, 1, 4, 5, 6] target=6
# return 1, 6
l = [3, 2, 1, 4, 5, 6]
target = 6
sorted(l)
left = 0
right = len(l) - 1
while left < right:
tmp = l[left] + l[right]
if tmp == target:
print(l[left], l[right])
elif tmp < target:
left += 1
elif tmp > target:
right -= 1
# index = 0
# while index < len(l):
# print(l[index])
# index +=1
#
# def sum(list, target):
# # for i in list:
# # for j in list:
# # if i + j == target:
# # print(i, j)
# i = 0
# while i < len(list):
# j = i + 1
# while j < len(list):
# if list[i] + list[j] == target:
# print(list[i], list[j])
# j += 1
# i += 1
#
#
# def sum(list, target):
# targetList = [tuple((i, j)) for i in list for j in list if i + j == target]
# finalList = [tuple((sorted(i))) for i in targetList]
# return sorted(set(finalList))
#
# print(sum([3, 2, 1, 4, 5, 6], 7))
# l = ['apple', 'orange', 'pear']
# res = []
# for i in l:
# res.append((i, len(i)))
#
# res = [(i, len(i)) for i in l] |
6d7f89a6f38bcb3765ff3e6f5a954bfed6b27f3c | lukelu389/programming-class | /python_demo_programs/2020/factorial.py | 231 | 4.15625 | 4 |
# use a loop to calculate n*(n-1)*(n-2)*(n-3)*...2*1,
# and return the result
def factorial(n):
result = 1
while n > 0:
result = result * n
n -= 1
return result
print(factorial(5))
print(factorial(3)) |
899a93327d5bce8e523b1622bf8b859a5c1b7c30 | lukelu389/programming-class | /python_demo_programs/2020/string_index.py | 353 | 3.90625 | 4 | s = 'abcd'
# print(s[0])
# print(s[1])
# print(s[2])
# print(s[3])
# print(s[0:2])
# print(s[0:2] == "ab")
# s = 'Arthur'
# # print(s[3:6])
# # print(s[1:4])
# # print(s)
# print(s[:2])
# print(s[::-1])
# a = 7
# b = 7
#
# if a > b:
# print('a is bigger than b')
# elif a < b:
# print('a is less than b')
# else:
# print('a b are equal')
|
62499768bba965433aadc0831f82058a25027723 | lukelu389/programming-class | /python_demo_programs/2020/example_20201113.py | 1,442 | 4.09375 | 4 |
# # dictionary pairs have int key, string value
# sample = {0: "Yan", 1: "Gary", 2: "Gilbert", 3: "Hangbing", 4: "Justin", 5: "Nick", 6: "Yijun Zhu"}
# print(sample[5])
# # add a new key-value pair
# sample[7] = "new student"
# print(sample[7])
#
# sample[7] = "new teacher"
# print(sample[7])
#
# sample2 = {"key": "value"}
# sample3 = {1: "one", 2: 2}
#
# # about the key, python defines only immutable item can be the key
# # for example, list is mutable, so you cannot have list as dictionary key
# sample4 = {(1, 2): 1}
# sample5 = {1: [1, 2, 2]}
# practice, create a dictionary using loop, who has the content {0 : 1, 1 : 2, 2 : 3, ... 9: 10}
# sample6 = {}
# for i in range(9):
# sample6[i] = i + 1
#
# print(sample6)
# sample = {1:100, 2:200}
# print(sample[1])
# print(sample.get(1))
#
# # print(sample[0])
# print(sample.get(100, "value not exists"))
# # del sample[1]
# v = sample.pop(1)
# print(v)
# print(sample)
# homework: create a dictionary using loop,
# where the sum of each key and value equals to 10
# example:
# d = {0: 10, 1:9, 2: 8, 3: 7, 4: 6, 5:5, 6:4, 7:3, 8:2, 9:1, 10:0}
# # list cannot be the dictionary key, because dictionary key has to be immutable
# # tuple can be the dictionary key
# d = {}
# # key is not in dictionary, new key/value is added
# d[1] = 'one'
# print(d)
# # key is in the dictionary, value is updated
# d[1] = 'ONE'
# print(d)
d = {}
for i in range(11):
d[i] = 10 - i
print(d)
|
ea53f0ecbeee4c3c1a35d5a2d2569b8a70cf4ea2 | lukelu389/programming-class | /python_demo_programs/2020/example_20201018.py | 1,389 | 4.125 | 4 | # homework
# write a python function takes two lists as input, check if one list contains another list
# [1, 2, 3] [1, 2] -> true
# [1] [1, 2, 3] -> true
# [1, 2] [1, 3] -> false
def contain(list1, list2):
# loop through list1 check if each element in list1 is also in list2
list2_contains_list1 = True
for i in list1:
if i not in list2:
list2_contains_list1 = False
# loop through list2 check if each element in list2 is also in list1
list1_contains_list2 = True
for i in list2:
if i not in list1:
list1_contains_list2 = False
return list1_contains_list2 or list2_contains_list1
# print(contains([1, 2, 3], [1, 2]))
# print(contains([1], [1, 2, 3]))
# print(contains([1, 2], [1, 3]))
# l = [[1, 2], 3]
# print(1 in l)
# print([1, 2] in l)
# write a python function that takes a list and a int, check if list contains two values that sum is the input int
# case1 [1, 2, 3], 4 -> True
# case2 [1, 2, 3], 10 -> False
# case3 [1, 3, 5], 4 -> True
# case4 [4, 2, 1], 5 ->
def pair_sum(list, sum):
i = 0
while i < len(list):
j = i + 1
while j < len(list):
if list[i] + list[j] == sum:
return True
j += 1
i += 1
return False
# write a python function that takes a list and a int, check if list contains two values that diff is the input int
|
2a483c17bbe52a294c1a45c98e46a07039610f86 | lukelu389/programming-class | /python_demo_programs/2021/example_20210403.py | 333 | 3.96875 | 4 | class MyClass:
num = 12345 # <- class variable
# construct method receives the passed in value when creating object
def __init__(self, name, age):
self.name = name # <- instance variable
self.age = age
# class method
def greet(self):
return "hello"
a = MyClass("Tom", 1)
print(a.name)
|
9e63c534debc5b8bb2adcfd7493ce18e8acd1bf7 | lukelu389/programming-class | /python_demo_programs/2020/example_20201025.py | 1,532 | 4.25 | 4 | # # write a python function that takes a list and a int, check if list contains any two values that diff of the two values
# # is the input int
# # [1, 2, 3] 1 -> true
# # [1, 2, 3] 4 -> false
#
# def find_diff(list, target):
# for i in list:
# for j in list:
# if j - i == target:
# return True
#
# return False
#
#
# l = ["1", "2", "3"]
# print(l)
# l[0] = 100
# print(l)
#
# s = 'abc'
# # question: what's the similar part between list and string
# # 1. contains multiple items
# # [1, 2, 3] '123'
# # 2. index
# # 3. loop
# # 4. len()
# # different: list -> mutable(changeable), string -> immutable(unchangeable)
#
# list = [1, 2, 3]
#
# string = 'abc'
# # string[0] = 'w'
#
# string_new = string + 'w' # this does not change the string, it creates a new string
# print(string)
# print(string_new)
#
# print(list.count(3))
# a = [1, 2, 3]
b = 1, 2, 3
# print(type(a))
print(type(b))
x, y = b
# unpack
print(x)
print(y)
# print(z)
# # write a function takes a list and tuple, check if all values in tuple also in the list
# def contains(l, t):
# for i in t:
# if i not in l:
# return False
# return True
#
# # write a function that takes a tuple as input, return a list contains the same value as tuple
# def tuple_to_list(tuple):
# list = []
# for i in tuple:
# list.append(i)
# return list
# write a function that takes a list and a value, delete all the values from list which is equal to the given value
# [1, 2, 2, 3] 2 -> [1, 3] |
12720f4c953a952aaebf3737a248c5e61c947773 | lukelu389/programming-class | /python_demo_programs/2020/nested_conditionals.py | 1,370 | 4.15625 | 4 | # a = 3
# b = 20
# c = 90
#
# # method 1
# if a > b:
# # compare a and c
# if a > c:
# print('a is the biggest')
# else:
# print('c is the biggest')
# else:
# # a is smaller than b, compare b and c
# if b > c:
# print('b is the biggest')
# else:
# print('c is the biggest')
#
# # method 2
# # and/or/not
# a = int(input('enter value a:'))
# b = int(input('enter value b:'))
# c = int(input('enter value c:'))
#
# if a > b and a > c:
# print('a is the biggest')
# elif b > a and b > c:
# print('b is the biggest')
# else:
# print('c is the biggest')
# print('Welcome come to the door choosing game')
# print('There are two door, 1 and 2, which one do you choose?')
#
# door = input('you choose:')
#
# if door == "1":
# print('There is a bear here, what do you do?')
# print('1. Run away')
# print('2. Scream at the bear')
# print('3. Give bear a cheese cake')
#
# bear = input('your choose:')
#
# if bear == "1":
# print('bear eats your legs off.')
# elif bear == "2":
# print('bear eats your face off')
# elif bear == "3":
# print('bear is happy, you are safe')
#
# elif door == "2":
# print('there is tiger.')
# a = int(input('enter a number:'))
# if a % 2 == 0:
# print(str(a) + " is even")
# else:
# print(str(a) + " is odd.")
|
e7858de37139b8012d40948dba3830c1726e9422 | lukelu389/programming-class | /python_demo_programs/2020/break_continue.py | 356 | 3.71875 | 4 | # a = range(3)
# print(list(a))
# range(10) -> [0, 1, 2, ..., 9]
# for i in range(10):
# if i == 5:
# break
# print(i, "hello")
#
# print('finish')
# for i in range(10):
# if i == 6:
# continue
# print(i)
# n = 1
# while n < 10:
# if n == 6:
# break
# print(n)
# n += 1
#
# print('finish')
# print(n) |
e98b2c293445fb59504836725d5a9642b6ecdc58 | vijaykanth1729/Python-Programs-Interview-Purpose | /element_search.py | 559 | 4.09375 | 4 | '''
Write a function that takes an ordered list of numbers
(a list where the elements are in order from smallest to largest)
and another number. The function decides whether or not the
given number is inside the list and returns (then prints) an appropriate boolean.
'''
def element_search(ordered_list, number):
if number in ordered_list:
return True
else:
return False
if __name__=='__main__':
ordered_list = [1,2,3,4,5,6,7,8]
number = int(input("Enter a number to search: "))
print(element_search(ordered_list, number))
|
82fd4d0ada2e7508236c2b5ffaa9ad4f3a7a2345 | vijaykanth1729/Python-Programs-Interview-Purpose | /input_to_year.py | 250 | 4.03125 | 4 | from datetime import datetime
year=datetime.now().year
name = input("Enter Your Name: ")
print(f"Hello Mr.{name}")
age = int(input("How old are you: "))
new_data = str((year-age)+100)
print(f"{name} you will be 100 years old in the year {new_data}")
|
ebdba2efa6a80d17470217c55478dcfb9e3250e2 | vijaykanth1729/Python-Programs-Interview-Purpose | /diamond_problem.py | 605 | 3.625 | 4 | '''
A
B C
D
'''
'''
MRO (method resolution order) rule tells that if a method is not available in class d,
then it verifies the method in class B, if not available
then it checks in class C.
in this case, class B method is executed..
'''
class A:
def method(self):
print("This is method from class A")
class B(A):
def method(self):
print("This is method from class B")
class C(A):
def method(self):
print("This is method from class C")
class D(B, C):
# def method(self):
# print("This is method from class D")
pass
d1 = D()
d1.method()
|
8a4df0a858c7823dc4f4b614ae81ff658abf6675 | vijaykanth1729/Python-Programs-Interview-Purpose | /Ab-inbev/unzip_file.py | 315 | 3.78125 | 4 | from zipfile import ZipFile, ZIP_STORED
f = ZipFile('files7.zip', 'r', ZIP_STORED) # for performing unzip operation..
names = f.namelist()
print(names)
print('')
for name in names:
print('FileName: ',name)
print('The content of this file: ')
f1 = open(name, 'r')
print(f1.read())
print('*'*10)
|
a0b7bbca5f8d4cbd1638a54e0e7c5d78302139f8 | vijaykanth1729/Python-Programs-Interview-Purpose | /list_remove_duplicates.py | 776 | 4.3125 | 4 | '''
Write a program (function!) that takes a list and returns a new
list that contains all the elements of the first list minus all the duplicates.
Extras:
Write two different functions to do this - one using a loop and constructing a
list, and another using sets.
Go back and do Exercise 5 using sets, and write the solution for that in a
different function.
'''
original = []
def remove_duplicates(my_list):
print("Original data: ", my_list)
data = set(my_list)
original.append(data)
def using_loop(my_list):
y = []
for i in my_list:
if i not in y:
y.append(i)
print("Using loop to remove duplicates: ",y)
remove_duplicates([1,2,3,4,5,4,2])
using_loop([1,2,3,4,5,4,2])
print("Using set function to remove duplicates:", original)
|
b91da36a1584fdc853640416324ba7470a51eb2c | tasos-bouas/tic-tac-toe | /tic-tac-toe.py | 4,177 | 3.875 | 4 | def DisplayBoard(board):
row = 0
for i in range(1,14):
if i == 1 or i == 5 or i == 9 or i == 13:
print("+-------+-------+-------+")
elif i == 2 or i == 4 or i == 6 or i == 8 or i == 10 or i == 12:
print("|", "|", "|", "|",sep=" ")
else:
for column in range(3):
print("|", board[row][column],"", sep=" ", end="")
print("|")
row += 1
#VictoryFor(board,'X')
def EnterMove(board):
x = True
while x:
ans = int(input("Enter your move: "))
if ans >= 1 and ans <= 9:
if any(ans in x for x in board):
for i in range(3):
for j in range(3):
if ans == blist[i][j]:
a = i
b = j
break
else:
continue
break
board[a][b] = "O"
return
else:
print("The field is occupied!")
else:
print("Wrong answer!")
def MakeListOfFreeFields(board):
flist = board[:][:]
i = 1
for row in range (3):
for column in range(3):
if flist[row][column] == column +i:
return False
i += 3
print("Tie!")
return True
def VictoryFor(board, sign):
x = False
y = False
if sign == "O":
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] == sign:
x = True
for j in range(3):
if sign == board[0][j] == board[1][j] == board[2][j]:
x = True
if sign == board[0][0] == board[1][1] == board[2][2] or sign == board[0][2] == board[1][1] == board[2][0]:
x = True
else:
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] == sign:
y = True
for j in range(3):
if sign == board[0][j] == board[1][j] == board[2][j]:
y = True
if sign == board[0][0] == board[1][1] == board[2][2] or sign == board[0][2] == board[1][1] == board[2][0]:
y = True
if x == True:
print("Congratulation You won!")
return True
elif y == True:
print("Computer Won! Don't Worry You Can Try Again!")
return True
else:
return False
def DrawMove(board):
if a == True:
x = True
while x:
for i in range (1):
num = randrange(1, 10)
for i in range(3):
for j in range(3):
if num == board[i][j]:
board[i][j] = "X"
x = False
DisplayBoard(board)
else:
board[1][1] = "X"
DisplayBoard(board)
return True
def clear():
os.system('clear')
from random import randrange
from time import sleep
import os
while True:
a = False
board = []
i = 1
for row in range(3):
x = [column + i for column in range(3)]
board.append(x)
i += 3
blist = board[:][:]
a = DrawMove(board)
while VictoryFor(board, "O") == False and VictoryFor(board, "X") == False and MakeListOfFreeFields(board) == False:
EnterMove(board)
clear()
DisplayBoard(board)
if VictoryFor(board, "O") == True:
break
elif VictoryFor(board, "X") == True:
break
clear()
DrawMove(board)
sleep(2)
gameon = input('\nDo you want to play again?(Y = YES or N = NO): ')
if gameon == 'Y' or gameon == 'y':
continue
elif gameon == 'N'or gameon == 'n':
metr = "."
for i in range(1, 4):
clear()
print(f'Terminating The Program{metr * i}')
sleep(1)
break
else:
clear()
print('Wrong Answer! Im Going To Terminate The Program!')
sleep(3)
metr = "."
for i in range(1, 4):
clear()
print(f'Terminating The Program{metr * i}')
sleep(1)
break
|
c43de8857ff0fe4041ef73387297793d9030c59a | Rojas-Andres/Desarrollo-de-problamas-usando-python-flask-y-mongo | /Punto 2/Cifrado cesar/cifrado.py | 5,186 | 4.0625 | 4 | #Comence por A:1 porque en el documento enviado lo desarrollaron asi para el ejemplo, tambien se tomo la letra Ñ porque
#Somos latinos
dic={
"A":1,
"B":2,
"C":3,
"D":4,
"E":5,
"F":6,
"G":7,
"H":8,
"I":9,
"J":10,
"K":11,
"L":12,
"M":13,
"N":14,
"Ñ":15,
"O":16,
"P":17,
"Q":18,
"R":19,
"S":20,
"T":21,
"U":22,
"V":23,
"W":24,
"X":25,
"Y":26,
"Z":27
}
#Desplazamiento cesar
while True:
try:
des=int(input("Digite el desplazamiento cesar\n\t:"))
break
except:
print("Has digitado mal el desplazamiento , recuerda que deben de ser numeros ")
while True:
valor = input("Digite S para el cifrado cesar y N para descifrar\n\t:").upper()
if valor in ('S','N'):
if valor=='S':
cifrado="cifrado cesar"
else:
cifrado= "descifrado cesar"
break
while True:
try:
cadena=str(input("Digite la cadena para aplicar el {} \n\t:".format(cifrado))).upper()
break
except:
print("Recuerda que es una cadena , no deben de ser numeros ")
#Declaramos la cadena cesar para luego llenarla
cesar = ""
#Esta funcion busca la llave en el diccionario la letra
def busca_llave(dic,letra):
for llave,valor in dic.items():
if llave==letra:
return llave,valor
#Esta funcion busca el numero al que esta enlazada la letra del diccionario
def busca_valor(dic,indice):
for llave,valor in dic.items():
if valor==indice:
return llave,valor
#Mostramos valores especiales para que el algoritmo no se caiga
valores_especiales=["1","2","3","4","5","6","7","8","9","0"," ",",",".","!","?","¡","¿","-","<",">","*","'",'"',"(",")"]
if valor=='S':
#Recorremos la cadena
for i in range(len(cadena)):
#Si el desplazamiento es positivo
if des > 0:
letra=cadena[i]
if letra in valores_especiales:
cesar+=letra
pass
else:
letra,indice = busca_llave(dic,cadena[i])
indice += des
if indice > 27:
#Encontramos la diferencia para volver a empezar
dif = indice - 27
letra,valor = busca_valor(dic,dif)
cesar+=letra
else:
#Buscamos la letra por el indice
letra,valor = busca_valor(dic,indice)
cesar+=letra
#Si el desplazamiento es negativo
elif des < 0:
letra = cadena[i]
if letra in valores_especiales:
cesar+=letra
pass
else:
letra,indice = busca_llave(dic,cadena[i])
indice +=des
if indice <= 0:
#Encontramos la diferencia para empezar desde la letra Z
#dif = 27 - indice
dif = 27 + indice
#print(dif,i)
letra,valor = busca_valor(dic,dif)
cesar+=letra
else:
#Buscamos la letra por el indice
letra,valor = busca_valor(dic,indice)
cesar+=letra
else:
cesar=cadena
#Significa que vamos a decifrar el mensaje
else:
for i in range(len(cadena)):
#Si el desplazamiento es positivo
if des > 0:
letra=cadena[i]
if letra in valores_especiales:
cesar+=letra
pass
else:
letra,indice = busca_llave(dic,cadena[i])
indice = indice - des
#print(letra,indice)
if indice > 27:
#Encontramos la diferencia para volver a empezar
dif = 27 - indice
#print(dif)
letra,valor = busca_valor(dic,dif)
cesar+=letra
elif indice <=0:
dif = 27 + indice
letra,valor = busca_valor(dic,dif)
cesar+=letra
else:
#Buscamos la letra por el indice
letra,valor = busca_valor(dic,indice)
cesar+=letra
#Si el desplazamiento es negativo
elif des < 0:
letra=cadena[i]
if letra in valores_especiales:
cesar+=letra
pass
else:
letra,indice = busca_llave(dic,cadena[i])
indice -= des
if indice > 27:
#Encontramos la diferencia para volver a empezar
dif = indice - 27
letra,valor = busca_valor(dic,dif)
cesar+=letra
else:
#Buscamos la letra por el indice
letra,valor = busca_valor(dic,indice)
cesar+=letra
else:
cesar = cadena
print("Cadena original : {}".format(cadena))
print("{} : {}".format(cifrado,cesar)) |
4e9833cf7f21845f6c64cee80c347d82a37a02b3 | abdullahnoble/Intro-to-Webd | /hacker_rank 2.py | 277 | 3.734375 | 4 | from collections import OrderedDict
d = OrderedDict()
for _ in range(int(input())):
item, space , quantity = input().rpartition(' ')
if item not in d:
d[item] = int(quantity)
else:
d[item] += int(quantity)
for i, q in d.items():
print(i, q)
|
e27f13f5d021969e253aa6d5157180bc30a7dc47 | stevehaigh/python-exercises | /rna.py | 339 | 3.609375 | 4 | # Convert a DNA sequence to corresponding RNA sequence.
#
import sys
if len(sys.argv) < 2 or not sys.argv[1]:
print "Please specify file containing a DNA sequence"
sys.exit()
DNAseq = open(sys.argv[1], "r").read()
RNAseq = DNAseq.replace('T', 'U')
with open("rna.txt", "w") as RNAfile:
RNAfile.write(RNAseq)
print "done"
|
f71a8b917462f1f7fea0cd2c79cc1c8bfa426a50 | balwantrawat777/assignment-15 | /assignment 15.py | 773 | 3.65625 | 4 | #QUESTION 1
import re
email="zuck26@facebook.com" "page33@google.com" "jeff42@amazon.com"
output=re.findall("(\w+)@([A-Z0-9]+)\.([A-Z]{2,3})",email,flags=re.IGNORECASE)
print(output)
#QUESTION 2
import re
text = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better."
t=re.findall("[bB]\w+",text,flags=re.IGNORECASE)
print(t)
#QUESTION 3
import re
sentence = "A, very very; irregular_sentence"
output=re.sub("[,_;]"," ",sentence)
print(output)
#OPTIONAL QUESTION
import re
tweet = '''Good advice! RT @TheNextWeb: What I would do differently if I was learning to code today http://t.co/lbwej0pxOd cc: @garybernhardt #rstats'''
r=' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|((\w+:\/\/\S+))"," ",tweet).split())
print(r) |
54398f9ffb92228b89e18e91f4d765d2bcd1bbe3 | zilunzhang/puzzles | /puzzles-BFS-DFS/puzzle_tools.py | 5,106 | 3.921875 | 4 | """
Some functions for working with puzzles
"""
from puzzle import Puzzle
# set higher recursion limit
# which is needed in PuzzleNode.__str__
# uncomment the next two lines on a unix platform, say CDF
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, (2**29, -1))
import sys
sys.setrecursionlimit(10**6)
def depth_first_solve(puzzle):
"""
Return a path from PuzzleNode(puzzle) to a PuzzleNode containing
a solution, with each child containing an extension of the puzzle
in its parent. Return None if this is not possible.
@type puzzle: Puzzle
@rtype: PuzzleNode
"""
def dfs(puzzle_1, seen):
if puzzle_1.fail_fast():
return None
elif puzzle_1.is_solved():
return PuzzleNode(puzzle_1)
else:
cur_node = PuzzleNode(puzzle_1)
for extension in puzzle_1.extensions():
# check if current extension has been used
if str(extension) not in seen:
seen.add(str(extension))
child = dfs(extension, seen)
# check whether child is None
# if it doesn't find the solution, child would always
# be None
if child:
# we found solution, build reference between child
# and parent until the first node
child.parent = cur_node
cur_node.children.append(child)
# we call return here, so the for loop in every
# recursion step would stop, hence each node only
# has one child (we only append it once)
return cur_node
seen_ = set()
seen_.add(str(puzzle))
return dfs(puzzle, seen_)
def breadth_first_solve(puzzle):
"""
Return a path from PuzzleNode(puzzle) to a PuzzleNode containing
a solution, with each child PuzzleNode containing an extension
of the puzzle in its parent. Return None if this is not possible.
@type puzzle: Puzzle
@rtype: PuzzleNode
"""
# helper function
def get_path(node):
"""
Get the root_node with the path to the target node.
@type node: PuzzleNode
@rtype: PuzzleNode
"""
current_node_ = node
while current_node_.puzzle is not None and \
current_node_.parent is not None:
current_node_.parent.children = [current_node_]
current_node_ = current_node_.parent
return current_node_
root_node = PuzzleNode(puzzle)
pending_que = [root_node]
seen = set()
while pending_que:
current_node = pending_que.pop(0)
if current_node.puzzle.is_solved():
return get_path(current_node)
elif str(current_node.puzzle) not in seen:
if not current_node.puzzle.fail_fast():
seen.add(str(current_node.puzzle))
for ext in current_node.puzzle.extensions():
if str(ext) not in seen:
child_node = PuzzleNode(ext, parent=current_node)
pending_que.append(child_node)
# Class PuzzleNode helps build trees of PuzzleNodes that have
# an arbitrary number of children, and a parent.
class PuzzleNode:
"""
A Puzzle configuration that refers to other configurations that it
can be extended to.
"""
def __init__(self, puzzle=None, children=None, parent=None):
"""
Create a new puzzle node self with configuration puzzle.
@type self: PuzzleNode
@type puzzle: Puzzle | None
@type children: list[PuzzleNode]
@type parent: PuzzleNode | None
@rtype: None
"""
self.puzzle, self.parent = puzzle, parent
if children is None:
self.children = []
else:
self.children = children[:]
def __eq__(self, other):
"""
Return whether PuzzleNode self is equivalent to other
@type self: PuzzleNode
@type other: PuzzleNode | Any
@rtype: bool
>>> from word_ladder_puzzle import WordLadderPuzzle
>>> pn1 = PuzzleNode(WordLadderPuzzle("on", "no", {"on", "no", "oo"}))
>>> pn2 = PuzzleNode(WordLadderPuzzle("on", "no", {"on", "oo", "no"}))
>>> pn3 = PuzzleNode(WordLadderPuzzle("no", "on", {"on", "no", "oo"}))
>>> pn1.__eq__(pn2)
True
>>> pn1.__eq__(pn3)
False
"""
return (type(self) == type(other) and
self.puzzle == other.puzzle and
all([x in self.children for x in other.children]) and
all([x in other.children for x in self.children]))
def __str__(self):
"""
Return a human-readable string representing PuzzleNode self.
# doctest not feasible.
"""
return "{}\n\n{}".format(self.puzzle,
"\n".join([str(x) for x in self.children]))
|
19f7f545bfd4eff755300906a7336fa5692757d1 | zinh/advent-of-code-2018 | /day15/game.py | 2,364 | 3.90625 | 4 | from board import Board
import pdb
class Game:
def __init__(self, lines, attack_point = 3):
self.board = Board(lines)
self.attack_point = attack_point
self.elf_win = True
def run(self):
turn_count = 0
while not self.turn():
turn_count += 1
return turn_count, self.total_hit_point()
# one game turn
def turn(self):
ended = True
for unit in self.board.units():
if not unit.is_dead():
target = self.attack(unit)
if target:
ended = False
if target.is_dead() and target.is_elf():
self.elf_win = False
return True
elif self.move(unit):
ended = False
target = self.attack(unit)
if target is not None and target.is_dead() and target.is_elf():
self.elf_win = False
return True
return ended
# move a unit
def move(self, unit):
paths = []
for opponent in self.board.opponents(unit):
distance, next_step, target = self.board.find_shortest(unit, opponent)
if distance is not None:
paths.append((distance, next_step, target))
if paths:
paths.sort(key=lambda x: (x[0], x[2].position[0], x[2].position[1]))
_, next_step, target = paths[0]
self.board.move_unit(unit, next_step)
return next_step
return None
def attack(self, unit):
neighbor_units = [cell for cell in self.board.neighbors(unit) if unit.is_opponent_of(cell)]
#if unit.position == (2, 3):
# pdb.set_trace()
if neighbor_units:
neighbor_units.sort(key=lambda u: (u.hit_point, u.position[0], u.position[1]))
target = neighbor_units[0]
unit.attack(target, self.attack_point)
if target.is_dead():
self.board.remove(target.position)
return target
return None
def total_hit_point(self):
return sum([unit.hit_point for unit in self.board.units()])
def print_hit_point(self):
for unit in self.board.units():
print(unit.position, unit.hit_point)
def __str__(self):
return str(self.board)
|
dd22a8411a9d8848bfa25f34e3e58ef71ca4b09a | zinh/advent-of-code-2018 | /day15/cell.py | 861 | 3.5 | 4 | class Cell:
def __init__(self, position, cell_type):
self.position = position
self.type = cell_type
self.hit_point = 200
def is_unit(self):
return self.type == 'E' or self.type == 'G'
def is_opponent_of(self, other):
return (self.type == 'E' and other.type == 'G') or (self.type == 'G' and other.type == 'E')
def is_moveable(self):
return self.type == '.'
def attack(self, other, point = 3):
if self.is_elf():
other.hit_point -= point
else:
other.hit_point -= 3
def is_dead(self):
return self.hit_point <= 0
def is_wall(self):
return self.type == '#'
def is_elf(self):
return self.type == 'E'
def __str__(self):
return "({}, {}), HP={}".format(self.position[0], self.position[1], self.hit_point)
|
bb3c2b979426ab217b7cf3bbdadb12d4c8aa2e05 | ThtGuyBro/Python-sample | /Dict.py | 307 | 4.125 | 4 | words = {"favorite dessert": "apple pie","never eat": "scallop","always have" : "parachute","don't have" :"accident","do this" : "fare","bug" : "flea"}
print(words['bug'])
words['parachute']= 'water'
words['oar']= 'girrafe'
del words['never eat']
for key, value in words.items():
print(key)
|
0fd872f83272cd79893013134f174cdc153a333b | sdnnet3/python | /10_OOP_02of03.py | 263 | 3.796875 | 4 | """
Let's Learn Python #11 - Overriding & File Mng. - OOP 2 of 3
"""
class BaseClass(object):
def test(self):
print ('ham')
class InClass(BaseClass):
def test(self):
print ("Hammer Time")
i = InClass()
i.test()
b = BaseClass()
b.test()
|
5ecba5e1ff3c45fc0b074e483a95260f7dcb48c0 | sdnnet3/python | /type_class.py | 442 | 3.859375 | 4 |
class MyClass(object):
def __init__(self):
self.x = 5
"""
Example:
TypeClass = type("TypeClass", (), {"x":5})
TypeClass TypeClass - these should be the same
(object,) - comma defaults to a tuple
(object, BaseClass, etc)
"""
TypeClass = type("TypeClass", (object,), {"x":5})
m = MyClass()
t = TypeClass()
print (t.x, m.x)
|
dc48605f4aec1a64d4190f6363fd9d02050c927a | felipemlrt/begginer-python-exercises | /08_classesI/Example.py | 195 | 3.59375 | 4 | class basic_math:
def sum(x, y):
return x + y
def subtract(x,y):
return x - y
def multiply(x, y):
return x * y
if __name__ == "__main"":
bm = basic_math()
print(bm.sum(5,5))
|
a5c89600f1343b8059680634e0ca7caed0bcebe9 | felipemlrt/begginer-python-exercises | /06_FuntionsI/Exercise.py | 1,923 | 4.3125 | 4 | #!/usr/bin/env python3
#1)
#Create a function that receives a operator ( + - * or / ), values X and Y, calculates the result and prints it.
#Crie uma função que receva um oprador ( + - * or / ), valores X e Y, e calcule o resultando apresentando este ao usuário.
#2)
#Create a function that tell if a number is odd or even.
#Crie uma função que retorne se um número é par ou ímpar.
#3)
#Create a function that receives a memory size in Bytes, converts it to Giga Bytes then prints the resulting size in GB. Example 1024MB = 1GB. Use binary not decimal.
#Crie uma funço que receba um tamanho de memória em Bytes e o converta no equivalente em Giga Bytes apresentando o resultado.
#4)
#Create a function that receives a series of prices and prints the subtotal after each one is given.
#Crie uma função que receba uma serie de preços e apresente o subtotal apos cada novo item inserido.
#5)
#Create a function that prints a given x number x times. Example: print 5, 5 times, 3, 3 times, 9, 9 times and so on.
#Crie uma função que apresente um núemro x, x vezes. Exemplo: apresentar 5, 5 vezes, 3, 3 vezes e assim por diante
#6)
#Create a function that generate a random number.
#Crie uma função que gere um numero randonico.
#7)
#Create a function that calculates the area of a circle of a given r radius.
#
#8)
#Create a function that converts a time in hours, minutes, seconds to a total in miliseconds. Tip 1h = 60m, 1m = 60s, 1s = 1000ms.
#
#9)
#Create a function that receives a list of login/password sets and compares it to another list printing those that are present in both.
#
#10)
#Create a function that counts seconds. Use a chronometer to compare with your code.
#Crie uma função que conte segundos. Use um cronometro para comparar com o seu código.
#11)
#Create a function that receives a data and a number, then calculates what day will be the date + the number given days.
#
|
cd12a5192994e593a3eec07aad7ef181954d194c | eryl/windpower | /scripts/merge_csvs.py | 583 | 3.65625 | 4 | import argparse
import pandas as pd
from pathlib import Path
parser = argparse.ArgumentParser("Merge the input csv files")
parser.add_argument('csv_files', help="files to merge", type=Path, nargs='+')
parser.add_argument('--output-file', help="Where to write output, to standard out if not given", type=Path)
args = parser.parse_args()
merged_data = pd.concat([pd.read_csv(csv_file) for csv_file in args.csv_files])
if args.output_file is not None:
print(f"Writing data to {args.output_file}")
merged_data.to_csv(args.output_file, index=False)
else:
print(merged_data)
|
fc7fe301cf229ffec3e2ba02c4f452042e340173 | jinyesong/Python | /base/practice4/4.1_list.py | 121 | 3.734375 | 4 | num = 12345
list_num = list(str(num))
print(list_num)
sum = 0
for i in list_num:
sum += int(i)
print(sum) |
47b2b9d03b9c39190f6a5bbc3aaed01b58706815 | dlimla/Data-Structures | /heap/max_heap.py | 5,140 | 4.125 | 4 | class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
# pass
self.storage.append(value)
value_index = len(self.storage) - 1
self._bubble_up(value_index)
def delete(self):
# pass
# so first we have to see if the tree has any values in it
if not self.storage:
return False
# if there is only one node in there then easy peasy we deletye
elif len(self.storage) == 1:
deleted = self.storage.pop()
# if the tree has more then one
elif len(self.storage) > 1:
# we swap the top value with lowest value which is usually athe farthest right
self.storage[0], self.storage[len(self.storage) - 1] = self.storage[len(self.storage) - 1], self.storage[0]
# then we deleted the last value
deleted = self.storage.pop()
# and then we make sure the first value is the largest by sending in the first value in index '0' then that function will run shifting nodes until the highest value is at the top
self._sift_down(0)
else:
deleted = False
return deleted
def get_max(self):
# this is pretty straightfoward since the max should be at the top
return self.storage[0]
# pass
def get_size(self):
# this is also pretty straighfoward since we just need to find the len of the array
return len(self.storage)
# pass
# this bubble up is mostly for when you first insert a node into to heaps
def _bubble_up(self, index):
# pass
# here we get teh index from the "insert" function from the top
# and while it's larger then '0' which it usually is it will loop until it breaks
while index > 0:
# here with a mathmatical equation we can find the parent index
# this is found starting by putting the tree as an array with it we can find the parent of each child with this function "2n+1" and "2n+2" since each node can only ever have two children
# take this tree here
# 20
# 13 9
# 8 5 3 7
# 6 2
# we can convert this into an array like so
# 0 1 2 3 4 5 6 7 8 --> index
# [20,13,9,8,5,3,7,6,2] we take each line of the tree as such and insert left to right
# and with this array we can find the location of each parent's child
# take index '2' for example which is '9' by putting '2' into the equation
# 2n+1 so 2 * 2 + 1 we get the index of '5' which is '3' and with the 2n+2 we get index of '6' whic is '7'
# with the above tree we can see that '3' and '7' are indeed both children of '9' so this equation works and opposite works as well with the number of the index we can divide it with (index -1)//2 which will give us our parent
# so take the number '7' which has the index of '6' we input the equation 6-1/2 and floor it so it ends up as '2' which is the location of the number '9' and with the tree we can see it is indeed the index of the parent of that specified index
parent = (index - 1)//2
# with it we can now compair with the number at the current index with the parent index
# if it's larger then the parent...
if self.storage[index] > self.storage[parent]:
# ...then we swap
self.storage[index], self.storage[parent] = self.storage[parent], self.storage[index]
# then we reassign the child's index with the parents index, if not then child is at it's valid spot and we stop
index = parent
else:
# with this break
break
# while this function is when adjusting or deleting a node on a heap tree
# the main funcationality of this...well function is to check if the child is larger then the parent, if it is then swap the nodes.
def _sift_down(self, index):
# pass
# here we first set variables to find the index and it's children like the equation above we can find it with the '2n+1' and '2n+2'
max = index
left_of_max = (index * 2) + 1
right_of_max = (index * 2) + 2
# so first we check the left side
# if so then we switch out the max with the current index
# if the current index AND the value at the index on the left of max is both less then the lenght of the storage AND the value of the index of the child then swap the max value
if len(self.storage) > left_of_max and self.storage[max] < self.storage[left_of_max]:
max = left_of_max
# and now we check the right
# and the same goes here
if len(self.storage) > right_of_max and self.storage[max] < self.storage[right_of_max]:
max = right_of_max
# now if the max is not equal to the given index then the parent is not the highest value and therefore it is swapped and since we have to keep checking on EVERY parent we recursivly call the function to run again but this time we insert the current max value
if max != index:
self.storage[index], self.storage[max] = self.storage[max], self.storage[index]
self._sift_down(max) |
b321b25ea686aa1330dc45942cca8305c77b6bbe | jakerjohnson94/molecules_ICPC | /find_intersections.py | 773 | 4.09375 | 4 | # """
# Write a function that will find the intersection with the widest
# angle between the strings (that is, lowest index pairs)
# that will maximize the potential interior area.
# """
def find_intersections(w1, w2):
"""
# Return a sorted list of tuples that represent intersection points.
# The sorting order should be from best to worst (e.g. lowest indices
# to highest) Return None if no intersections are found.
"""
intersections = []
for i, x in enumerate(w1):
for j, y in enumerate(w2):
if x == y:
intersections.append((i, j))
intersections.sort(key=lambda x: sum(x))
return intersections if intersections else None
words = ('OIMDIHEIAFNL', 'CHJDBJMHPJKD')
print(find_intersections(*words))
|
7013c110a2e2f976b23da251ba9f42b59657311e | CodecoolBP20161/python-pair-programming-exercises-2nd-tw-szilvi_mark | /passwordgen/passwordgen_module.py | 857 | 3.9375 | 4 | import random
import string
strong_or_weak = input("Strong or weak password would you like to choose?")
def passwordgen():
global strong_or_weak
for_weak_password = ['hahika', 'hihike', 'ilovecheese']
if strong_or_weak == "strong":
list_password = []
random_lenght = random.randint(8, 14)
for i in range(0, random_lenght+1):
random_char = random.randint(33, 127)
list_password.append(str(chr(random_char)))
return str(list_password)
elif strong_or_weak == "weak":
return random.choice(for_weak_password)
def main():
if strong_or_weak == "strong":
print("Your strong password is:")
elif strong_or_weak == "weak":
print("Your weak password is:")
result = passwordgen()
print(result.strip("[]"))
if __name__ == '__main__':
main()
|
068980cb4b9170e148c723ef1b5c0f395a9f02ac | telboon/Project-Euler | /oddEven.py | 170 | 4.25 | 4 | #!/usr/bin/python3
oddEven=50
if oddEven%2==1:
print(str(oddEven)+" is odd!")
elif oddEven%2==0:
print(str(oddEven)+" is even!")
else:
print("This shouldn't run!")
|
2a4ed91c06d6c216a527dfed4522e356df88f858 | Bahrom21/python_lessons | /12.07.2021/12.07.2021.py | 521 | 3.703125 | 4 | """
def fun(num):
yig = 0
for i in str(num):
yig+=int(i)
print(yig)
fun(n)
Oʏʙᴇᴋ Nᴀʀᴢᴜʟʟᴀʏᴇᴠ, [12.07.21 11:47]
[Переслано от Oʏʙᴇᴋ Nᴀʀᴢᴜʟʟᴀʏᴇᴠ]
# 4 - masala.
n = int(input("n = "))
"""
# def xona_yigindi(a):
# yigindi = 0
# for i in range(len(str(a))):
# yigindi += a // (10 ** i) % 10
#
# print(yigindi)
def xona_yigindi(a):
summa = 0
a = str(a)
for i in a:
summa += int(i)
print(summa)
xona_yigindi(n) |
5167eaf105aa7f58b823c69bf773b84947875abb | Bahrom21/python_lessons | /Funksiyalar/15_07_datetime.py | 625 | 3.5625 | 4 | """
vaqt=dt.datetime.now()
print(vaqt.year)
print(vaqt.month)
print(vaqt.day)
print(vaqt.hour)
print(vaqt.minute)
print(vaqt.second)
def vaqt(t)
print(f"soat:{t.hour}:{t.minute} bo`ldi")
vaqt(t)
"""
"""
x=dt.datetime(2021, 7, 15)
print(dt)"""
"""
import datetime
x = datetime.datetime(2021,7,15)
print(x)
"""
"""
import datetime as dt
x=dt.datetime.now().second:
print(x)
print(x.strftime("%B"))
"""
import datetime as dt
x = dt.datetime.now().second
while True:
print(dt.datetime.now().second - x)
if x + 5 == dt.datetime.now().second:
print("salom")
x = dt.datetime.now().second
break |
d36f2a6c38ed2a89b03f9efeaa7960171361f300 | Bahrom21/python_lessons | /21-31.06.2021/29.06.py | 79 | 3.859375 | 4 | n = 3
for i in range(1,n+1):
for j in range(1,n+1):
print(i,'x', j,'=', i*j)
|
907939bff91f3602da522c7de0c0b1da537c85e3 | Bahrom21/python_lessons | /21-31.06.2021/4-masala 25.06.py | 143 | 3.59375 | 4 | import math
a=int(input("a="))
x=int(input("x="))
y=int(input("y="))
G=(math.cos(2*abs(y+x)-(x+y))**(4*x*x))/(math.atan(x+a)**4*x**5)
print(G) |
b996f8a64ba54db420f34ca501851f241b672787 | Bahrom21/python_lessons | /05.07.2021/4-masala 05.07.2021.py | 362 | 3.96875 | 4 | """#matrix = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
B = [[], [], [], [], [], [], [], [], []]
for i in range(3):
for j in range(3):
B[i][j] = int(input(f"[{i}][{j}]="))
print(B)#"""
# 3x3 matrisa xar elementi alohida qatorga chiqsin
numberlist = [1,2,3]
numberlist1 = [5,6,7]
numberlist2 = [8,9,10]
print(numberlist)
print (numberlist1)
print(numberlist2) |
409de30ab1bc103b081f5dbc4675a3a17d9a1c8d | Bahrom21/python_lessons | /21-31.06.2021/3-masala 25.06.py | 107 | 3.609375 | 4 | import math
y=int(input("y="))
h=int(input("h="))
A=(math.tan(y**3-h**4)+h**2)/(math.sin(h)**2+y)
print(A) |
0b829978bc66ee64f7cd1123a800124119d1169d | Bahrom21/python_lessons | /21-31.06.2021/1-masala 29.06.py | 191 | 3.609375 | 4 | qidirilayotgan_son=int(input("qidirilayotgan raqamingizni kiriting"))
for i in range(1,11):
if qidirilayotgan_son == i:
print("bor")
break
else:
print("yo`q")
|
2ec734f5bcc997c81263a4fabd67efc3a51df4d8 | Bahrom21/python_lessons | /13.07.2021/13.07 dars.py | 591 | 3.515625 | 4 | # REKURSIYA.
#masala. 1 dan n gacha bo'lgan natural sonlarni ekranga chiqarish dasturi.
"""
def birdanNgacha(n):
if n==1:
print(n)
else:
print(n)
birdanNgacha(n-1)
birdanNgacha(10)"""
"""
def birdanNgacha(k, n):
if n==k:
print(k)
else:
print(k)
birdanNgacha(k+1, n)
birdanNgacha(1, 10)
"""
# MASALA. K dan n gacha bo'lgan natural sonlarni ekranga chiqarish dasturi.
"""def birdanNgacha(k, n):
if n==k:
print(f"{k}, {n}")
else:
print(f"{k}, {n}")
birdanNgacha(k+1, n)
birdanNgacha(1, 20)
"""
|
dbb99274b99980f61fad44d019c6055e8b7ff8c8 | arifkhan1990/hackerrank-solution | /Python3/Python3 language/Lists.py | 648 | 3.71875 | 4 | # Name : Arif Khan
# Judge: HACKERRANK
# University: Primeasia University
# problem: Lists
# Difficulty: Medium
# Problem Link: https://www.hackerrank.com/challenges/python-lists/problem
#
if __name__ == '__main__':
arr = []
N = int(input())
for i in range(0,N):
data1 = input().split()
data = data1[0]
ar = data1[1:]
if data != "print":
data += "("+ ",".join(ar) +")"
eval("arr."+data)
else :
print(arr) |
72107b37729b1d33683462e27ddc32993e149e7a | arifkhan1990/hackerrank-solution | /Python3/Python3 language/Mutations.py | 573 | 3.75 | 4 | # Name : Arif Khan
# Judge: HACKERRANK
# University: Primeasia University
# problem: Mutations
# Difficulty: Easy
# Problem Link: https://www.hackerrank.com/challenges/python-mutations/problem
#
def mutate_string(string, position, character):
string = string[:position]+character+string[position+1:]
return string
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new) |
8320e270cc0ef7f8767336dfcb0dcf7ffe538e01 | tocodeil/webinar-live-demos | /20200326-clojure/patterns/04_recursion.py | 658 | 4.15625 | 4 | """
Iteration (looping) in functional languages is usually accomplished
via recursion.
Recursive functions invoke themselves,
letting an operation be repeated until it reaches the base case.
"""
import os.path
# Iterative code
def find_available_filename_iter(base):
i = 0
while os.path.exists(f"{base}_{i}"):
i += 1
return f"{base}_{i}"
print(find_available_filename_iter('hello'))
# ---
# Recursive code
def find_available_filename_rec(base, i=0):
name = f"{base}_{i}"
if not os.path.exists(name):
return name
return find_available_filename_rec(base, i + 1)
print(find_available_filename_rec('hello'))
|
8045ee48406d08ba6bad22b7549ea55d191ffd56 | elizabethendri/Batch-Gradient-Stochastic-Gradient-Descent | /HW-02.py | 1,076 | 3.78125 | 4 | # Elizabeth Endri
# CSC 481 - Artificial Intelligence
# HW 02
# This program implements batch gradient descent and stochastic descent algorithms
# to find the linear regression equation
# Initial Weights w0=.25 w1= .25 α = 0.0001 or 1/t
# Repeat until convergence
# how fast our model learns (learning rate)
alpha = 0.0001
initial_b = 0
initial_m = 0
iterations = 1000000
# weights
w0 = 0.25
w1 = 0.25
x_points = [2, 4, 6, 7, 8, 10]
y_points = [5, 7, 14, 14, 17, 19]
for i in range(iterations):
summation = 0
summation2 = 0
for j in range(6):
summation += y_points[j] - (w0 + w1 * x_points[j])
summation2 += (y_points[j] - (w0 + w1 * x_points[j])) * x_points[j]
w0 = w0 + alpha * summation
w1 = w1 + alpha * summation2
print(w0)
print(w1)
# STOCHASTIC
for i in range(iterations):
for i in range(6):
w0 = w0 + alpha * (y_points[i] - (w0 +w1 * x_points[i]))
w1 = w1 + alpha * (y_points[i] - (w0 + w1 * x_points[i])) *x_points[i]
print(w0)
print(w1)
|
43d5ef9aa2cb9bb9e0ccff7721c27cb81607a065 | soft9000/Python1000 | /Python1100/Study/MyBannerSet.py | 315 | 3.75 | 4 | #!/usr/bin/env python3
prefix = set()
prefix.add("Pig")
prefix.add("Cat")
prefix.add("Pig")
prefix.add("Dog")
for dat in prefix:
print(dat)
prefix2 = set(("pig", "Mouse", "Pig", "Dog"))
print(prefix2.intersection(prefix))
print(prefix2.union(prefix))
prefix = frozenset()
prefix.add("Pig")
|
fb5f69f7dd0a77dfdfcce1df40f7be08a3644a89 | soft9000/Python1000 | /Python1100/Study/MyListDelete.py | 375 | 3.59375 | 4 | # File: MyListDelete.py
# OKAY! Rational item removal
zList = ["This", "is", "a", "Test"]
zPop = zList.pop(0)
print("Popped:", zPop)
print("Result:", zList)
# ERROR! Irrational removal
zList = ['Mary', 'had', 'a', 'little', 'lamb!']
zList.pop(-100) # IndexError: pop index out of range
zList.pop(99) # IndexError: pop index out of range
print(zList)
|
140f987ff550f9f0b83cd93ef7bcd6de4f295310 | soft9000/Python1000 | /Python1100/Study/SimpleInputLoop.py | 219 | 3.953125 | 4 |
zOpts = ("Loop", "Break")
while True:
for ss, opt in enumerate(zOpts, 1):
print(ss, ".)", opt)
zChoice = input("What number? ")
if zChoice is "2":
break
print("Looping ...")
|
fc0d283efec47c1f9a4b19eeeff42ba58db258c7 | EdmondTongyou/Rock-Paper-Scissors | /main.py | 2,479 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Edmond Tongyou
CPSC 223P-01
Tues March 9 14:47:33 2021
tongyouedmond@fullerton.edu
"""
# Importing random for randint()
import random
computerScore = 0
ties = 0
userScore = 0
computerChoice = ""
userChoice = ""
# Loops until the exit condition (Q) is met otherwise keeps asking for
# one of three options (R, P, S), every loop the computer choice is
# decided via randint and then compares the user choice to the
# computer choice. If user wins, adds 1 to userScore same with computer
# win. If a tie is found adds 1 to the ties. If the inputted letter is
# not R P S or Q then the loop repeats until a valid option is inputted
while 'Q' not in userChoice:
computerChoice = random.randint(0, 2)
print ("Please input one: (R, P, S, Q) > ", end = " ")
userChoice = input()
userChoice = userChoice.upper()
if 'R' in userChoice or 'P' in userChoice or 'S' in userChoice:
if computerChoice == 0:
print("Computer chose Rock", end = '. ')
if 'R' in userChoice:
print("Call it a draw.")
ties += 1
elif 'P' in userChoice:
print("You win.")
userScore += 1
else:
print("Computer wins.")
computerScore += 1
elif computerChoice == 1:
print("Computer chose Paper", end = '. ')
if 'R' in userChoice:
print("Computer wins.")
computerScore += 1
elif 'P' in userChoice:
print("Call it a draw.")
ties += 1
else:
print("You win.")
userScore += 1
else:
print("Computer chose Scissors", end = '. ')
if 'R' in userChoice:
print("You win.")
userScore += 1
elif 'P' in userChoice:
print("Computer wins.")
computerScore += 1
else:
print("Call it a draw.")
ties += 1
elif 'Q' in userChoice:
continue
else:
print("Invalid option, input again.")
continue
# Prints out the results for each score then compares the scores to see who won
# or if a tie was found.
print("Computer: " , computerScore)
print("You: ", userScore)
print("Ties: ", ties)
if computerScore > userScore:
print("Computer Won!")
elif computerScore < userScore:
print("You Won!")
else:
print("It's a tie!") |
84ae781762294928dbcdf26133b537c39a2ee7ad | rshamsy/lpthw-exs | /lphw/ex7.py | 341 | 3.71875 | 4 | tryString = "x {}"
for i in range(1,10):
print(tryString.format(i))
tryString_2 = "x"*5
print("\nx*5: " + tryString_2, end=' ')
# ", end=' '" causes the next print statement to coninue on the same line after a space, and not on next line
print("a b c d")
print("\nwith end='':")
print("\nx*5: " + tryString_2, end='')
print("a b c d")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.