blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
0d74d350f93fe1e2d12024f7cc24f48d27e5224f | pzabauski/Homework | /Homework2/#2.py | 3,641 | 4.25 | 4 | # Модуль calendar
# Пользователь вводит дату своего рождения в формате DD.MM.YYYY.
# Вывести название дня недели, в который родился пользователь.
# Пользователь вводит название дня недели. Вывести ближайший месяц и год, когда этот день недели выпадал на 1-ое число.
import calendar
import datetime
# Часть 1 v.1
a = input('Введите дату в формате DD.MM.YYYY\n')
if len(a) == 10 and a[2] == "." and a[5] == '.':
year = int(a[6:len(a)])
month = int(a[3:5])
day = int(a[0:2])
d = calendar.weekday(year, month, day)
# Это работает не так. Должно быть:
# text_calendar = calendar.TextCalendar()
# print(text_calendar.formatweekday(d, 9))
# А можно было вместо использования классов просто использовать calendar.day_name:
# print(calendar.day_name[d])
self = calendar.TextCalendar.formatweekday
print(calendar.TextCalendar.formatweekday(self, d, 9)) # Что здесь значит self, почему без него не работает?
else:
print('Дата введена в неверном формате ')
# Часть 1 v.2
print('Часть 1 v.2')
a = input('Введите дату в формате DD.MM.YYYY\n')
if len(a) == 10 and a[2] == "." and a[5] == '.':
year = int(a[6:len(a)])
month = int(a[3:5])
day = int(a[0:2])
d = calendar.weekday(year, month, day)
print(calendar.day_name[d])
else:
print('Дата введена в неверном формате ')
# Часть 1 v.3
print('Часть 1 v.3')
a = input('Введите дату в формате DD.MM.YYYY\n')
if len(a) == 10 and a[2] == "." and a[5] == '.':
year = int(a[6:len(a)])
month = int(a[3:5])
day = int(a[0:2])
d = calendar.weekday(year, month, day)
text_calendar = calendar.TextCalendar()
print(text_calendar.formatweekday(d, 9))
else:
print('Дата введена в неверном формате ')
# Часть 2
x = input('Введите день недели:\n')
week_days = {'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6}
dates = []
number_of_days = []
today = datetime.date.today()
# Создаем списки под каждый день недели
# в списке dates - даты когда день недели приходится на 1ое число
# в списке number of days - сколько от сегодня до даты в dates
# Индексы списков всегда будут совпадать по каждой итерации
# Вызываем в списке dates индекс соотв. минимальному количеству дней в списке number of days
if x in week_days:
for a in range(2018, 2019):
for b in range(1, 12):
if calendar.weekday(a, b, 1) == week_days[x]:
dates.append(datetime.date(a, b, 1))
number_of_days.append(abs(today - datetime.date(a, b, 1)))
else:
continue
z = dates[number_of_days.index(min(number_of_days))]
z1 = int(z.month)
z2 = int(z.year)
print('Ближайший месяц: %d' % z1)
print('Ближайший год: %d' % z2)
else:
print('Неправильно введен день недели, см. варианты ниже:\n')
print(week_days.keys())
|
a0f4da105b8fe154a002be9c26ffb4e938cd32fd | Djphoenix719/rl-search | /benchmarks/misc_util.py | 368 | 3.5 | 4 | def print_banner(text: str, header_char: str = "-", footer_char: str = "-", size: int = 50) -> None:
"""
Print a nicely formatted banner with a line of header and footer characters
:param text:
:param header_char:
:param footer_char:
:param size:
:return:
"""
print(header_char * size)
print(text)
print(footer_char * size)
|
ad36a00ddb252a48269726cce87f575e047c7b5a | itnks/Dominos | /Node.py | 3,683 | 4 | 4 | class Node(object):
def __init__(self, data, next):
self.data = data
self.next = next
###########################################
###########################################
class SingleList(object):
head = None
tail = None
def show(self):
print "Showing list data:"
current_node = self.head
while current_node is not None:
print current_node.data, " -> ",
current_node = current_node.next
print None
def append(self, data):
node = Node(data, None)
if self.tail is None:
self.tail = self.head = node
else:
self.head.next = node
self.head = node
def appendH(self, data):
node = Node(data, None)
if self.tail is not None:
self.head = node
else:
while(self.head.next != None):
self.head = self.head.next
self.head = node
# current = self.head
# while current is not None:
# #self.head = self.head.next
# current = current.next
#self.head = node
# self.head.next = self.head #and self.head.next = self.head.next.next
def printHead(self):
print self.head.data
#from random import shuffle
zero = [[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6]]
one = [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6]]
two = [[2,2],[2,3],[2,4],[2,5],[2,6]]
three = [[3,3],[3,4],[4,5],[3,6]]
four = [[4,4],[4,5],[4,6]]
five = [[5,5],[5,6]]
six = [[6,6]]
deck = []
deck.append(zero)
deck.append(one)
deck.append(two)
deck.append(three)
deck.append(four)
deck.append(five)
deck.append(six)
i = 0
tails = []
for size in deck:
for size0 in size:
# print(size0)
# print(" ")
tails.append(size0)
p1 = []
p2 = []
p3 = []
p4 = []
i1 = 0
i2 = 0
#shuffle(tails)
for x in tails:
if len(p1) != 7:
p1.append(x)
# print("p1: ", x)
tails.remove(x)
elif len(p2) != 7:
p2.append(x)
# print("p2: ", x)
tails.remove(x)
for x in tails:
if len(p3) != 7:
p3.append(x)
# print("p3: ", x)
tails.remove(x)
"""
for x in tails:
while len(p4) != 7:
p4.append(x)
# print("p4: ", x)
tails.remove(x)
"""
s = 0
while len(p4) != 7:
p4.append(tails[s])
tails.remove(tails[s])
s + s+1
"""
print(tails)
print(p1)
print(p2)
print(p3)
print(p4)
"""
def pla(place, p):
lis = []
if len(place) == 0:
place.append(p)
elif place[0][0] == p[0]:
place = [p] + place
elif place[-1][1] == p[1]:
place.append(p)
else:
print("inv")
return place
place = []
pla(place, p1[1])
print(place)
a = [2,3]
b = [0,3]
c = [6,2]
f = [4,6]
pla(place, a)
pla(place, c)
pla(place, f)
print(pla(place, b))
print(place)
##########################
d = SingleList()
#d.append(p1)
#d.append(p2)
#d.append(p3)
#d.append(p4)
def move(index, node):
if node.head is None:
node.append(index)
print("yes")
else:
print("no")
#move(p1[0], d)
"""
d.append(10)
d.append(5)
d.append(15)
d.append(3)
d.show()
d.printHead()
d.appendH(6)
d.printHead()
d.show()
"""
|
eb048e9a054390e51acf4cfe935fad82002eb834 | asiegman/learning_snippets | /boolean.py | 1,327 | 3.921875 | 4 | #!/usr/bin/env python
# Truth in python means the built-in boolean True, or a non-zero, non-None value
# False means zero, none, or the boolean False
# "Truthiness" may vary from language to language, but boolean logic does not
true = True
true = bool(17)
true = bool(-1.25)
false = bool(None)
false = bool(0)
false = False
# 'and' operations must both be True or non-zero to equate to True
true = True and True
false = True and False
false = False and False
false = False and True
# 'or' operations must have one or the other "True"
false = False or False
true = True or False
true = False or True
# boolean operations go from inside to outside of (), and left to right
true = True and False or True
# work: (True and False) or True
# False or True
# True
false = True and False and True
# work: (True and False) and True
# False and True
# False
# Using paranthesis () can help clarify things if you want something to
# evaluate first, just like order of operations in math
true = True or (False and True)
# work: True or (False)
# work: True
# Be explicit, wrap things in () if it helps readability
# This prevents unintended order-of-operations bugs
boolean = (2 <= 2) and ("Alpha" == "Bravo")
# work: boolean = (True) and (False)
# work: boolean = False
|
0aad5b4eadf57b44acea4384ffebeb4498dc7d88 | LeonardoBrabo/Informatorio | /Programacion Web/EstructurasdeControl/3_NivelFacil.py | 455 | 3.671875 | 4 | usuario = str(input("id: "))
password = str(input("pass: "))
print("usuario creado")
print(" ")
print("loguearse:")
us =str(input("id: "))
contra = str(input("pass:" ))
cont= 0
while cont <5:
if us != usuario or contra != password:
us =str(input("id: "))
contra = str(input("pass:" ))
cont+= 1
else:
print("USUARIO CORRRECTO")
break
if cont == 5:
print("USUARIO BLOQUEADO")
#Por Leonardo Brabo
|
b77587f138ad09828aeb999ebb915b2c292c777a | kaisjessa/Project-Euler | /pe058.py | 803 | 3.8125 | 4 | import math
'''
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
'''
def spiral(x):
diagonals = []
count = 0
increment = 2
i=1
while(i <= x**2):
diagonals.append(i)
count += 1
i += increment
if count % 4 ==0:
increment += 2
return(diagonals)
def is_prime(x):
if(x<2):
return False
if(x==2):
return True
if(x%2==0):
return False
for i in range(3, math.ceil(math.sqrt(x))+1, 2):
if x % i == 0:
return False
return True
#each entry is ([all numbers on diagonals, all primes on diagonals])
#dynamic_array = [[[0], [0]], [[0], [0]], [[3, 5, 7, 9], [3, 5, 7]]]
ratio = 1
i = 3
count = 5
primes = 3
while ratio >= 0.1:
i += 2
arr = spiral(i)[-4:]
count += 4
for a in arr:
if(is_prime(a)):
primes += 1
ratio = float(primes)/count
print(i) |
ab1b942c870d1bb964c6e9e8eb2e7c41fa505e0a | kaisjessa/Project-Euler | /pe028.py | 272 | 3.515625 | 4 | '''
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
'''
def cycle(x):
total = 0
count = 0
increment = 2
i=1
while(i <= x**2):
total += i
count += 1
i += increment
if count % 4 ==0:
increment += 2
return(total)
print(cycle(10)) |
ecea765e44dae66b75770ea5f0a1ce7fbcb831cc | SurajSarangi/Python | /Python/chefdil.py | 138 | 3.53125 | 4 | t=int(input())
while(t>0):
s=input()
c=s.count("1")
if(c%2==1):
print("WIN")
else:
print("LOSE")
t=t-1 |
446b90dd052e0c3b0101711aa94ee2ea223cb5c2 | SurajSarangi/Python | /Python/File_encryption/encrypt_file.py | 447 | 3.703125 | 4 | """Encrypting an entire file"""
f1=open("input.txt",'r')
f2=open("output.txt",'w')
for m in f1:
for i in m:
if i==' ':
f2.write(' ')
elif i=='.':
f2.write('.')
elif i=='\n':
f2.write('\n')
elif ord(i)>=65 and ord(i)<=90:
j=ord(i)+5
if j>ord('Z'):
k=j-ord('Z')
j=ord('A')+k-1
f2.write(chr(j))
else:
j=ord(i)+5
if(j>ord('z')):
k=j-ord('z')
j=ord('a')+k-1
f2.write(chr(j))
f1.close()
f2.close() |
8493bad14ffd7c0f298789e3fafc55469c9f8476 | KarthikPeneti/test | /hungry.py | 103 | 3.890625 | 4 | hungry = input("are you hungy?")
if hungry =="yes":
print("eat something")
else:
print("okay")
|
c11d7e04f135c6249c737f71924ea1e3d610027e | ParagDasAssam/Calculator_pythontk_code | /testing_cal.py | 1,171 | 3.671875 | 4 | from tkinter import*
import tkinter.messagebox
def beenClicked():
radioValue = relStatus.get()
tkinter.messagebox.showinfo("you clicked", radioValue)
return
def changeLabel():
name= "Thanks for the click " + yourName.get()
labelText.set(name)
yourName.delete(0,END)
yourName.insert(0, "My name is parag")
return
app = Tk()
app.title("GUI EXAMPLE")
app.geometry('450x300+200+200')
labelText = StringVar()
labelText.set("Click button")
label1 = Label(app, textvariable=labelText, height=4)
label1.pack()
checkBoxVal = IntVar()
checkBox1 = Checkbutton(app, variable = checkBoxVal, text="Happy?")
checkBox1.pack()
custName = StringVar(None)
yourName = Entry(app, textvariable=custName)
yourName.pack()
relStatus = StringVar()
relStatus.set(None)
radio1 = Radiobutton(app, text="Single", value="Single", variable = relStatus, command=beenClicked).pack()
radio1 = Radiobutton(app, text="Married", value="Married", variable = relStatus, command=beenClicked).pack()
button1 = Button(app, text="Click Here", width=20, command=changeLabel)
button1.pack(side='bottom', padx=15, pady=15)
app.mainloop()
|
74ab3200ab835a3fffc9f9a457e354b9e3ca92e0 | miguelgrubin/python-examples | /concurrencia/hilo.py | 567 | 3.578125 | 4 | import threading
import time
class Hilo(threading.Thread):
"""
El hilo dura tanto como dure el main().
El stdout y stderr (print y errores) es es mismo que el main()
"""
def __init__(self):
threading.Thread.__init__(self)
self.setDaemon(True)
self.contador_segundos = 0
def run(self):
while True:
self.contador_segundos += 1
time.sleep(1)
print(self.contador_segundos)
def main():
h = Hilo()
h.start()
time.sleep(10)
if __name__ == '__main__':
main()
|
f5041687b224782c671fbbeaeb79dcd7dcca9524 | ChrisPoche/Coding_Dojo_Work | /Python/Python_basics/findChar.py | 287 | 4 | 4 | #Take a list of words, print a new list of those words that contain a specific character
word_list = ['hello','world','my','name','is','Anna']
char = 'a'
new_wl = []
for x in range(0,len(word_list)):
if word_list[x].find(char) != -1:
new_wl.append(word_list[x])
print new_wl
|
9cac20b09bf506f6bc3ac592f124239772ab1f18 | ChrisPoche/Coding_Dojo_Work | /Python/Python_basics/compareList.py | 426 | 3.875 | 4 | list_one = ['celery','carrots','bread','cream']
list_two = ['celery','carrots','bread','cream']
if len(list_one) != len(list_two):
same = False
else:
for x in range(0,len(list_one)):
if list_one[x] == list_two[x]:
same = True
elif list_one[x] != list_two[x]:
same = False
if same == False:
print "The lists are not the same"
else:
print "The lists are the same" |
f9ab383be53502c4965649e02942735da0e937a0 | ChrisPoche/Coding_Dojo_Work | /Python/OOP/car.py | 1,116 | 4.09375 | 4 | #Create a class that allows the user to input price, speed, fuel, and mileage. Place a conditional that any car above $10,000 receive a 15% tax, the default otherwise being 12%
#Create 6 instances
class Car(object):
def __init__(self,price,speed,fuel,mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if self.price >= 10000:
self.tax = 0.15
else:
self.tax = 0.12
def display_all(self):
print "Price: {}".format(self.price)
print "Speed: {}".format(self.speed)
print "Fuel: {}".format(self.fuel)
print "Mileage: {}".format(self.mileage)
print "Tax: {}".format(self.tax)
Car1 = Car(2000,"35 mph","Full","15 mpg")
Car2 = Car(5000,"5 mph","Not Full","105 mpg")
Car3 = Car(18000,"15 mph","Kind of Full","95 mpg")
Car4 = Car(9000,"45 mph","Empty","25 mpg")
Car5 = Car(20000,"35 mph","Empty","15 mpg")
print "Car1"
Car1.display_all()
print "Car2"
Car2.display_all()
print "Car3"
Car3.display_all()
print "Car4"
Car4.display_all()
print "Car5"
Car5.display_all()
|
df0897a57a4ff7b72d57c0ee153a2171435e6d23 | weaver-viii/hh_scraping | /HH_crawler/statistics.py | 1,247 | 3.6875 | 4 | # This module is for calculating and analysing scraped data.
import csv
import re
import collections
import pandas as pd
def analyse_data(filename):
with open('./' + filename, newline='') as data:
reader = csv.reader(data, delimiter='"')
for row in reader:
if len(row) > 2:
salary_items = re.findall(r'\d+.\d+', row[1])
salary = [int(re.sub(r'\xa0', '', i)) for i in salary_items]
salary_list.extend(salary)
skills = row[0].split(',')
skills.remove('')
yield skills
return salary_list
salary_list = []
print('Input filename to analyze data:')
file_name = str(input())
skills_list = []
for ele in analyse_data(file_name):
skills_list.extend(ele)
skills_numbers = collections.Counter(skills_list)
skills_sum = sum(skills_numbers.values())
top_skills = skills_numbers.most_common(10)
persent_list = [(k[1] / skills_sum * 100).__round__() for k in top_skills]
mean_salary = (sum(salary_list) / len(salary_list)).__round__()
stats_table = pd.DataFrame({'Skills, amount': top_skills, '%': persent_list})
print(stats_table)
print('------------------------------')
print('Mean salary(rub) : ', mean_salary)
|
f4ac6f727eda468a18aaaeb59489940150419e63 | Tanushka27/practice | /Class calc.py | 423 | 4.125 | 4 | print("Calculator(Addition,Subtraction,Multiplication and Division)")
No1=input("Enter First value:")
No1= eval(No1)
No2= input("Enter Second value:")
No2= eval(No2)
Sum= No1+No2
print (" Sum of both the values=",Sum)
Diff= No1-No2
print("Difference of both values=",Diff)
prod= No1*No2
print("Product of both the values=",prod)
Div= No1/No2
print ("Division of the value is=",Div)
mod= No1%No2
print ("remainder is=",mod)
|
122fcf7b577d4fb5e5c7c3f45f0c267a0fcf6939 | leonardodma/robot202_AL | /aula02/Atividade2/atividade4.py | 3,551 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Referências:
# https://www.geeksforgeeks.org/circle-detection-using-opencv-python/
# https://www.geeksforgeeks.org/python-opencv-cv2-line-method/
import math
import cv2
import numpy as np
from matplotlib import pyplot as plt
import time
import sys
import auxiliar as aux
def encontra_circulo(img, codigo_cor):
# MAGENTA
hsv_1, hsv_2 = aux.ranges(codigo_cor)
# convert the image to grayscale, blur it, and detect edges
hsv = cv2.cvtColor(img , cv2.COLOR_BGR2HSV)
gray = cv2.cvtColor(img , cv2.COLOR_BGR2GRAY)
color_mask = cv2.inRange(hsv, hsv_1, hsv_2)
segmentado = cv2.morphologyEx(color_mask, cv2.MORPH_CLOSE, np.ones((10, 10)))
segmentado = cv2.adaptiveThreshold(segmentado,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,3.5)
kernel = np.ones((3, 3),np.uint8)
segmentado = cv2.erode(segmentado,kernel,iterations = 1)
circles=cv2.HoughCircles(segmentado, cv2.HOUGH_GRADIENT,2,40,param1=50,param2=100,minRadius=5,maxRadius=100)
return circles
if len(sys.argv) > 1:
arg = sys.argv[1]
try:
input_source=int(arg) # se for um device
except:
input_source=str(arg) # se for nome de arquivo
else:
input_source = 0
cap = cv2.VideoCapture(input_source)
# Parameters to use when opening the webcam.
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
lower = 0
upper = 1
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
circles_magenta = encontra_circulo(frame, '#FF00FF')
circles_ciano = encontra_circulo(frame, '#5dbcce')
x_m, y_m, r_m = None, None, None
x_c, y_c, r_c = None, None, None
if circles_magenta is not None:
circles_magenta = np.uint16(np.around(circles_magenta))
# Desenha círculos da cor Magenta
for pt in circles_magenta[0, :]:
x_m, y_m, r_m = pt[0], pt[1], pt[2]
# Draw the circunference of the circle.
cv2.circle(frame, (x_m, y_m), r_m, (0, 255, 255), 2)
# Draw a small circle (of radius 1) to show the center.
cv2.circle(frame, (x_m, y_m), 1, (0, 255, 255), 3)
if circles_ciano is not None:
circles_ciano= np.uint16(np.around(circles_ciano))
# Desenha círculos da cor ciano
for pt in circles_ciano[0, :]:
x_c, y_c, r_c = pt[0], pt[1], pt[2]
# Draw the circunference of the circle.
cv2.circle(frame, (x_c, y_c), r_c, (0, 255, 255), 2)
# Draw a small circle (of radius 1) to show the center.
cv2.circle(frame, (x_c, y_c), 1, (0, 255, 255), 3)
centro_ciano = tuple([x_c, y_c])
centro_magenta = tuple([x_m, y_m])
print(centro_ciano)
angle = None
if centro_ciano[0] != None or centro_magenta[0] != None:
try:
line = cv2.line(frame, centro_ciano, centro_magenta, (255, 0, 0), 6)
angle = math.atan2(y_m - y_c, x_m - x_c)
angle = angle * (180/math.pi)
print(angle)
except:
pass
if angle != None:
cv2.putText(frame, "Angulo: %.2f graus" % (angle),(frame.shape[1] - 600, frame.shape[0] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), 2)
cv2.imshow("Detected Circle", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows() |
cf440450ee2e0f43cb330bc4bb1d9807fac865da | NickGervais/geocoder | /request_impl.py | 1,442 | 3.796875 | 4 | # this library works best on linux running python2.*
import requests
# this is my registered api key for google maps I recieved from Google
apiKey = "AIzaSyBdHvCMgUN-3Oy7HdkzW3AguKBDpuodSYw"
# the base url endpoint to retreive our json data from
url = "https://maps.googleapis.com/maps/api/geocode/json"
#asks the user to enter an address or city
location = input("Entery an address or city: \n")
# in this step, we would the parameters that we need to add to our base endpoint
params = {'address':location, 'key':apiKey}
# in this step we make restful api get call using the the requests
# library and also the url and parameters we built above
response = requests.get(url =url, params = params)
# next we take our response to that the restful api call and extract the json data from it
data = response.json()
# next we take a look at the status of this json
# if the status is OK then we proceed.
if data['status'] == 'OK':
# in these next few lines we extract the information we need from the json object
place_id = data['results'][0]['place_id']
lat = data['results'][0]['geometry']['location']['lat']
lng = data['results'][0]['geometry']['location']['lng']
# next we simply print this information.
print(location,'\n')
print('ID: ', place_id, '\n')
print('Latitude: ', lat, '\n')
print('Longitude: ', lng, '\n')
else:
# if the status was not OK, then we simply print out the status of the response.
print(data['status']) |
1a291ceda2a85d32ffe909d388b2eccde42fac93 | mgrelewicz/metaheur | /funkcja_celu.py | 1,053 | 3.796875 | 4 | # -*- coding: utf-8 -*-
#
#### Funkcja celu: chcemy uzyskać różnicę (diff) żeby móc ją minimalizować
def goal(subset):
size = len(subset)
print('size: ', size)
if (size%2 == 0):
A_size = size//2
B_size = size//2
else:
A_size = size//2
size += 1
B_size = size//2
size -= 1
print('sizeA: ', A_size)
print('sizeB: ', B_size)
for i in range(0, A_size, 1):
subset_A.append(subset[i])
for j in range(A_size, size, 1):
subset_B.append(subset[j])
print('subsetA: ', subset_A[:5])
print('subsetB: ', subset_B[:5])
sum_A = sum(subset_A)
sum_B = sum(subset_B)
print('SumA: ', sum_A)
print('SumB: ', sum_B)
if (sum_A >= sum_B):
diff = (sum_A - sum_B)
else:
diff = (sum_B - sum_A)
print('Diff: ', diff)
if diff == 0:
print('bingo!')
else:
print('Potrzebna optymalizacja!')
return diff
|
9d92a7bc359ecc7b3e6417c0cd58130f6902c181 | XxAGMGxX/Python | /Ejercicio 3 - comisión.py | 689 | 3.984375 | 4 | # 3 Un vendedor recibe un sueldo base más un 10% extra por comisión de sus ventas.
# El vendedor desea saber cuánto dinero obtendrá por concepto de comisiones por las tres
# ventas que realiza en el mes y el total que recibirá en el mes tomando en cuenta su sueldo
class comisión:
SalarioBase=float(input("El salario base es de:"))
V1=float(input("Valor de la primera venta:"))
V2=float(input("Valor de la segunda venta:"))
V3=float(input("Valor de la tercera venta:"))
TVentas= V1 + V2 + V3
Comi= TVentas*0.1
TRecibir= SalarioBase + Comi
print("Su comision por concepto de ventas es de: $",Comi)
print("Sueldo a recibir:$",TRecibir)
|
26acbd3eee6d7771699b14d9ce641302ca48a204 | XxAGMGxX/Python | /Ejercicio 8 - NumMayor.py | 547 | 3.78125 | 4 | class NMay:
def __init__(self):
pass
def NM(self):
num1 = int(input("Ingrese el primer número: "))
num2 = int(input("Ingrese el segundo número: "))
num3 = int(input("Ingrese el tercer número: "))
if num1 > num2 and num1 > num3:
print("El número mayor es {}".format(num1))
elif num2 > num1 and num2 > num3:
print("El número mayor es {}".format(num2))
else:
print("El número mayor es {}".format(num3))
NMay = NMay()
NMay.NM()
|
55f3518c31f9c80c2f41761aea229bfddad4f748 | 5nizza/spec-framework | /structs.py | 2,784 | 3.671875 | 4 | from enum import Enum
class Automaton:
"""
An automaton has three types of states: `acc`, `dead`, normal.
For a run to be accepted, it should satisfy:
G(!dead) & GF(acc)
Thus, in the automaton `dead` states has the property that they are `trap` states.
If there are no `acc` states, acc is set to True.
If there are no `dead` states, dead is set to False.
"""
def __init__(self,
states,
init_state,
acc_states,
dead_states,
is_safety, # `safety` means an automaton encodes rejecting finite traces
edges: 'tuple of ((src,dst),set of labels) where label is a tuple of literals'):
self.states = states
self.init_state = init_state
self.acc_states = acc_states
self.dead_states = dead_states
self.edges = edges
self.propositions = self._get_propositions()
self.is_safety = is_safety
assert self.acc_states
assert not (self.is_safety and len(self.dead_states) == 0), str(self)
def _get_propositions(self):
propositions = set()
for ((src, dst), labels) in self.edges:
for label in labels:
for lit in label:
atom = lit.strip('~').strip('!')
propositions.add(atom)
return tuple(propositions) # fixing the order
def __str__(self):
return 'states: %s, init_state: %s, acc_states: %s, dead_states: %s, edges: %s' % \
(self.states, self.init_state, self.acc_states, self.dead_states, self.edges)
class SmvModule:
def __init__(self, name, module_inputs, desc, module_str, has_bad, has_fair):
self.module_inputs = tuple(module_inputs)
self.name = name
self.desc = desc
self.module_str = module_str
self.has_bad = has_bad
self.has_fair = has_fair
def __str__(self):
return 'module: %s (%s), def:\n%s' % (self.name, self.desc, self.module_str)
class SpecType(Enum):
AUTOMATON_SPEC = 1
LTL_SPEC = 2
PLTL_SPEC = 3
ORE_SPEC = 4
class PropertySpec:
def __init__(self,
desc,
is_positive: bool or None,
is_guarantee: bool or None,
data,
type: SpecType):
self.desc = desc
self.is_positive = is_positive
self.is_guarantee = is_guarantee
self.data = data
self.type = type
def __str__(self):
return "Spec(desc=%s, data=%s, %s, %s)" % \
(self.desc,
self.data,
['assumption', 'guarantee'][self.is_guarantee],
['bad trace', 'good trace'][self.is_positive])
__repr__ = __str__
|
f6f148f4868656e492c2e059ba7447dc6728cc3e | wahabtobibello/coding-challenges | /palindrome.py | 233 | 3.953125 | 4 | def is_palindrome(word):
word_len = len(word)
for i in range(word_len // 2):
if word[i] != word[word_len - i - 1]:
return False
return True
print(is_palindrome('level'))
print(is_palindrome('levels')) |
f07a39588b1aa7f5152e5d226c392037883a2630 | DincerDogan/VeriBilimi | /Python/2-)VeriManipulasyonu(NumPy&Pandas)/22-gruplama.py | 465 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 18:13:18 2020
@author: baysan
"""
# Genellikle gruplama ve toplulaştırma işlemleri bir arada kullanılır
import pandas as pd
df = pd.DataFrame({'gruplar':['A','B','C','A','B','C'],
'veri':[10,11,52,23,42,55]},
columns = ['gruplar','veri'])
print(df)
print(df.groupby('gruplar').mean()) # yakaladığımız grupların ortalamasını aldık
|
4097c8f49d7b54290561a950db2f8adeb229251e | DincerDogan/VeriBilimi | /Python/2-)VeriManipulasyonu(NumPy&Pandas)/15-dataframe_olusturmak.py | 907 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 18:25:44 2020
@author: baysan
"""
# Pandas DataFrame Oluşturmak
import pandas as pd
import numpy as np
df = pd.DataFrame([1,2,45,67,879,90],columns=["degisken_adi"]) # ilk argüman hangi veriyi DataFrame'de kullanacağımız ve 2. argüman ise kolon adı (opsiyonel)
print(df)
nd = np.arange(1,10).reshape((3,3))
df = pd.DataFrame(nd,columns=['var1','var2','var3'])
print(df)
print(df.columns) # değişken isimlerini getirir
df.columns = ('deg1','deg2','deg3') # değişken isimlerini değiştirebiliyoruz
print(df)
print(df.axes) # satır ve sütun bilgilerini verir
print(df.ndim) # boyut sayısını verir
print(df.shape) # kaça kaçlık
print(df.size) # kaç elemanlı
print(df.values) # sadece değerleri verir ve ndarray nesnesine çevirir
print(df.head(2)) # baştan 2 veri
print(df.tail(2)) # sondan 2 veri |
7b55b2a1410f0a58b21441cb6a4e8573b348ae4d | DincerDogan/VeriBilimi | /Python/2-)VeriManipulasyonu(NumPy&Pandas)/11-matematiksel_islemler.py | 575 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 13:45:08 2020
@author: baysan
"""
import numpy as np
nd = np.arange(1,10)
print(nd*2) # tüm elemanları 2 ile çarptık
# Tabi bunun diğer matematiksel operatörler ile kullanmak da mümkündür
print(nd - 1) # tüm elemanlardan 1 çıkarttık
# ufunc
"""
aslında yukarıdaki örnekleri yaptığımızda da numpy arrayleri içerisinde
otomatik olarak ufunc fonksiyonları çalışmaktadır
"""
print(np.subtract(nd,1)) # nd arrayindeki her bir elemandan 1 çıkarır
print(np.log(nd))
|
b4769ee2822cfa377653c8def27939fd2f9f9df5 | barcelona123456/python3 | /eeree.py | 194 | 3.53125 | 4 | def baesu_sum(start, end, baesu):
hap=0
i=start
while i<=end:
if i%baesu==0:
hap=hap+i
i=i+1
return hap
print("합계:",baesu_sum(1,10,4))
|
e077b1c72ee610365cb97ee67ef6df3a09388609 | yangdissy/TDClass01 | /Lesson-2-开发环境的搭建/homework/01007-朱旭/十进制转换工具.py | 618 | 3.59375 | 4 | print('欢迎使用十进制转换器!\n')
while True:
parm = input('请输入一个整数(输入Q结束程序)\n:')
check = parm.isdigit()
if parm == 'Q' or parm == 'q':
print('\n谢谢您的使用!\n')
break
elif check != True:
print( '\n\n请输入一个整数类型!\n')
continue
num = int(parm)
parm = str('parm')
#print('\t十六进制:0x%x' % num)
print('\t十六进制 : {0}'.format('%#x' % num))
print('\t八进制 : {0}'.format('%#o' % num))
print('\t二进制 :', bin(num), '\n'* 6)
|
32358716203d93542ec747525edbf0402d745558 | madhavpalshikar/branch-cicd | /s.py | 586 | 3.59375 | 4 | def countStaircases(N):
memo = [[0 for x in range(N + 5)]
for y in range(N + 5)]
for i in range(N + 1):
for j in range (N + 1):
memo[i][j] = 0
memo[3][2] = memo[4][2] = 1
for i in range (5, N + 1) :
for j in range (2, i + 1) :
if (j == 2) :
memo[i][j] = memo[i - j][j] + 1
else :
memo[i][j] = (memo[i - j][j] +
memo[i - j][j - 1])
answer = 0
for i in range (1, N + 1):
answer = answer + memo[N][i]
return answer
print(countStaircases(3))
print(countStaircases(4))
print(countStaircases(5))
print(countStaircases(200)) |
8c5b3fea27a70800e65b257a501d4eb91eef6b62 | peterevans/Project-Euler | /6sum-square-difference.py | 305 | 3.671875 | 4 | #!/usr/bin/env python
# encoding: utf-8
import sys
import os
def squarediff(max):
i = 0
sumsquare = 0
while i <= max:
sumsquare = sumsquare + i**2
i = i + 1
i = 0
squaresum = 0
while i <= max:
squaresum = squaresum + i
i = i + 1
return squaresum**2 - sumsquare
print squarediff(100)
|
29e06294d27ef41d9b4644924c25b8f77b8b919c | rahulgitsit/codeforces | /Petya and Strings.py | 161 | 3.859375 | 4 | line1 = input()
line2 = input()
if str.lower(line1) == str.lower(line2):
print(0)
elif str.lower(line1) > str.lower(line2):
print(1)
else:
print(-1) |
7f9b965f9bff8e93521fc37b4ccf8387acae461f | rajeevvarma16/cs101 | /lists.py | 480 | 4 | 4 | # Define a procedure, greatest,
# that takes as input a list
# of positive numbers, and
# returns the greatest number
# in that list. If the input
# list is empty, the output
# should be 0.
def greatest(list_of_numbers):
greatest = 0
if len(list_of_numbers) > 0:
for elem in list_of_numbers:
if elem > greatest:
greatest = elem
return greatest
return 0
print greatest([4,23,1])
#>>> 23
print greatest([])
#>>> 0 |
9ab6fc2ba3ae33bc507d257745279687926d62d2 | khushbooag4/NeoAlgo | /Python/ds/Prefix_to_postfix.py | 1,017 | 4.21875 | 4 | """
An expression is called prefix , if the operator appears in the expression before the operands. (operator operand operand)
An expression is called postfix , if the operator appears in the expression after the operands . (operand operand operator)
The program below accepts an expression in prefix and outputs the corresponding postfix expression .
"""
# prefixtopostfix function converts a prefix expression to postfix
def prefixtopostfix(exp):
stack = []
n = len(exp)
for i in range(n - 1, -1, -1):
if exp[i].isalpha():
stack.append(exp[i])
else:
op1 = stack.pop()
op2 = stack.pop()
stack.append(op1 + op2 + exp[i])
print("the postfix expresssion is : " + stack.pop())
# Driver Code
if __name__ == "__main__":
exp = input("Enter the prefix expression : ")
prefixtopostfix(exp)
"""
Sample I/O:
Enter the prefix expression : *+abc
the postfix expresssion is : ab+c*
Time complexity : O(n)
space complexity : O (n)
"""
|
9adc4c2e16a6468b7c39231425c0c7f2a3b6f843 | khushbooag4/NeoAlgo | /Python/ds/Sum_of_Linked_list.py | 2,015 | 4.25 | 4 | """
Program to calculate sum of linked list.
In the sum_ll function we traversed through all the functions of the linked list and calculate
the sum of every data element of every node in the linked list.
"""
# A node class
class Node:
# To create a new node
def __init__(self, data):
self.data = data
self.next = None
# Class Linked list
class LinkedList:
# create a empty linked list
def __init__(self):
self.head = None
# Function to insert elements in linked list
def push(self, data):
newNode = Node(data)
temp = self.head
newNode.next = self.head
# If linked list is not None then insert at last
if self.head is not None:
while (temp.next != self.head):
temp = temp.next
temp.next = newNode
else:
newNode.next = newNode # For the first node
self.head = newNode
# Function to print given linked list
def print_List(self):
temp = self.head
if self.head is not None:
while (True):
print(temp.data)
temp = temp.next
if (temp == self.head):
break
# Function to calculate sum of a Linked list
def sum_ll(self, head):
sum_ = 0
temp = self.head
if self.head is not None:
while True:
sum_ += temp.data
temp = temp.next
return sum_
# Initialize lists as empty by creating Linkedlist objects
head = LinkedList()
# Pushing elements into LinkedList
n = int(input("Enter the no. of elements you want to insert: "))
for i in range(n):
number = int(input(f"Enter Element {i + 1}: "))
head.push(number)
print("Entered Linked List: ")
head.print_List()
sum_ = head.sum_ll(head)
print(f"\nSum of Linked List: {sum_}")
"""
Time Complexity: O(n)
Space Complexity: O(n)
SAMPLE INPUT/OUTPUT:
Entered Circular Linked List:
20 30 40 50
Sum of Linked List: 140
"""
|
ca903edb902b818cd3cda5ad5ab975f12f99d467 | khushbooag4/NeoAlgo | /Python/search/three_sum_problem.py | 2,643 | 4.15625 | 4 | """
Introduction:
Two pointer technique is an optimization technique which is a really clever way of using
brute-force to search for a particular pattern in a sorted list.
Purpose:
The code segment below solves the Three Sum Problem. We have to find a triplet out of the
given list of numbers such that the sum of that triplet equals to another given value.
The Naive Approach is to calculate the sum of all possible triplets and return the one with
the required sum or None. This approach takes O(N^3) time to run. However, by using Two pointer
search technique we can reduce the time complexity to O(N^2).
Method:
Three Sum Problem using Two Pointer Technique
"""
def three_sum_problem(numbers, sum_val):
"""
Returns a triplet (x1,x2, x3) in list of numbers if found, whose sum equals sum_val, or None
"""
# Sort the given list of numbers
# Time complexity: O(N.logN)
numbers.sort()
size = len(numbers)
# Two nested loops
# Time complexity: O(N^2)
for i in range(size-3+1):
# Reduce the problem to two sum problem
two_sum = sum_val - numbers[i]
# Initialize the two pointers
left = i+1
right = size-1
# Search in the array until the two pointers overlap
while left < right:
curr_sum = numbers[left] + numbers[right]
# Update the pointers
if curr_sum < two_sum:
left += 1
elif curr_sum > two_sum:
right -= 1
else:
# Return the numbers that form the desired triplet
return "({},{},{})".format(numbers[i], numbers[left], numbers[right])
# No triplet found
return None
def main():
"""
Takes user input and calls the necessary function
"""
# Take user input
numbers = list(map(int, input("Enter the list of numbers: ").split()))
sum_val = int(input("Enter the value of sum: "))
# Find the triplet
triplet = three_sum_problem(numbers, sum_val)
if triplet is None:
print(f"No triplet found with sum: {sum_val}")
else:
print(f"{triplet} is the triplet with sum: {sum_val}")
if __name__ == "__main__":
# Driver code
main()
"""
Sample Input 1:
Enter the list of numbers: 12 3 4 1 6 9
Enter the value of sum: 24
Sample Output 1:
(3,9,12) is the triplet with sum: 24
Time Complexity:
For sorting: O(N.log N)
For two-pointer technique: O(N^2)
T = O(N.log N) + O(N^2)
T = O(N^2)
""" |
f9e6bfee3042b3a877fe84856ed539acc1c6f687 | khushbooag4/NeoAlgo | /Python/math/Sieve-of-eratosthenes.py | 980 | 4.21875 | 4 | '''
The sieve of Eratosthenes is an algorithm for finding
all prime numbers up to any given limit. It is
computationally highly efficient algorithm.
'''
def sieve_of_eratosthenes(n):
sieve = [True for i in range(n + 1)]
p = 2
while p ** 2 <= n:
if sieve[p]:
i = p * p
while i <= n:
sieve[i] = False
i += p
p += 1
length = len(sieve)
for i in range(2, length):
if sieve[i]:
print(i, end=" ")
def main():
print("Enter the number upto which prime numbers are to be computed: ")
n = int(input())
print("The number of prime numbers less than " + str(n) + " is :")
sieve_of_eratosthenes(n)
if __name__ == "__main__":
main()
'''
Sample I/O:
Enter the number upto which prime numbers are to be computed:
30
The number of prime numbers less than 30 is :
2 3 5 7 11 13 17 19 23 29
Time complexity : O(n*(log(log(n))))
Space complexity : O(n)
'''
|
8d08dac477e5b8207c351650fef30b64da52c64a | khushbooag4/NeoAlgo | /Python/math/roots_of_quadratic_equation.py | 1,544 | 4.34375 | 4 | ''''
This is the simple python code for finding the roots of quadratic equation.
Approach : Enter the values of a,b,c of the quadratic equation of the form (ax^2 bx + c )
the function quadraticRoots will calculate the Discriminant , if D is greater than 0 then it will find the roots and print them otherwise it will print Imaginary!!
'''
import math
class Solution:
def quadraticRoots(self, a, b, c):
d = ((b*b) - (4*a*c))
if d<0:
lst=[]
lst.append(-1)
return lst
D = int(math.sqrt(d))
x1 = math.floor((-1*b + D)/(2*a))
x2 = math.floor((-1*b - D)/(2*a))
lst = []
lst.append(int(x1))
lst.append(int(x2))
lst.sort()
lst.reverse()
return lst
# Driver Code Starts
if __name__ == '__main__':
# For the values of a,b,c taking in a list in one line eg : 1 2 3
print("Enter the values for a,b,c of the equation of the form ax^2 + bx +c")
abc=[int(x) for x in input().strip().split()]
a=abc[0]
b=abc[1]
c=abc[2]
# Making a object to class Solution
ob = Solution()
ans = ob.quadraticRoots(a,b,c)
if len(ans)==1 and ans[0]==-1:
print("Imaginary Roots")
else:
print("Roots are :",end=" ")
for i in range(len(ans)):
print(ans[i], end=" ")
print()
'''
Sample Input/Output:
Enter the values for a,b,c of the equation of the form ax^2 + bx +c
1 2 1
Output:
Roots are : -1 -1
Time Complexity : O(1)
Space Complexity : O(1)
'''
|
e88f786eb63150123d9aba3a3dd5f9309d825ca1 | khushbooag4/NeoAlgo | /Python/math/positive_decimal_to_binary.py | 876 | 4.59375 | 5 | #Function to convert a positive decimal number into its binary equivalent
'''
By using the double dabble method, append the remainder
to the list and divide the number by 2 till it is not
equal to zero
'''
def DecimalToBinary(num):
#the binary equivalent of 0 is 0000
if num == 0:
print('0000')
return
else:
binary = []
while num != 0:
rem = num % 2
binary.append(rem)
num = num // 2
#reverse the list and print it
binary.reverse()
for bit in binary:
print(bit, end="")
#executable code
decimal = int(input("Enter a decimal number to be converted to binary : "))
print("Binary number : ")
DecimalToBinary(decimal)
'''
Sample I/O :
Input :
Enter a decimal number to be converted into binary: 8
Output:
Binary number:
1000
Time Complexity : O(n)
Space Complexity : O(1)
'''
|
170fef88011fbda1f0789e132f1fadb71ebca009 | khushbooag4/NeoAlgo | /Python/cp/adjacent_elements_product.py | 811 | 4.125 | 4 | """
When given a list of integers,
we have to find the pair of adjacent
elements that have the largest product
and return that product.
"""
def MaxAdjacentProduct(intList):
max = intList[0]*intList[1]
a = 0
b = 1
for i in range(1, len(intList) - 1):
if(intList[i]*intList[i+1] > max):
a = i
b = i+1
max = intList[i]*intList[i+1]
return(a, b, max)
if __name__ == '__main__':
intList = list(map(int, input("\nEnter the numbers : ").strip().split()))
pos1, pos2, max = MaxAdjacentProduct(intList)
print("Max= ", max, " product of elements at position ", pos1, ",", pos2)
"""
Sample Input - Output:
Enter the numbers : -5 -3 -2
Max= 15 product of elements at position 0 , 1
Time Complexity : O(n)
Space Complexity : O(1)
"""
|
99f2401aa02902befcf1ecc4a60010bb8f02bc32 | khushbooag4/NeoAlgo | /Python/other/stringkth.py | 775 | 4.1875 | 4 | '''
A program to remove the kth index from a string and print the remaining string.In case the value of k
is greater than length of string then return the complete string as it is.
'''
#main function
def main():
s=input("enter a string")
k=int(input("enter the index"))
l=len(s)
#Check whether the value of k is greater than length
if(k>l):
print(s)
#If k is less than length of string then remove the kth index value
else:
s1=''
for i in range(0,l):
if(i!=k):
s1=s1+s[i]
print(s1)
if __name__== "__main__":
main()
'''
Time Complexity:O(n),n is length of string
Space Complexity:O(1)
Input/Output:
enter a string python
enter the index 2
pyhon
'''
|
1904bdc89188cfe9834d5a50ca780780a9c44680 | Lwq1997/leetcode-python | /primary_algorithm/array/moveZeroes.py | 972 | 3.75 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/4/12 21:37
# @Author : Lwq
# @File : plusOne.py
# @Software: PyCharm
"""
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
"""
class Solution:
@staticmethod
def moveZeroes(arr):
"""
移动0
:type arr: object
"""
length = len(arr)
j = 0
for i in range(length):
if arr[i] != 0:
arr[j] = arr[i]
j += 1
arr[j:] = (length - j) * [0]
return arr
if __name__ == '__main__':
nums1 = [1, 2, 2, 1, 0, 1, 0, 0, 2, 5, 3, 6]
nums2 = [9, 90, 1, 4, 0, 2, 5, 0, 0, 5, 9]
res1 = Solution.moveZeroes(nums1)
res2 = Solution.moveZeroes(nums2)
print(res1)
print(res2)
|
051ee1ec695fa379fab13a5a72e9914e5773b1ef | Lwq1997/leetcode-python | /primary_algorithm/array/twoSum.py | 1,029 | 3.71875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/4/12 21:37
# @Author : Lwq
# @File : plusOne.py
# @Software: PyCharm
"""
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
class Solution:
@staticmethod
def twoSum(arr, target):
"""
两数之和
使用字典结构
:type arr: object
"""
hashmap = {}
for index, num in enumerate(arr):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num], index]
hashmap[num] = index
if __name__ == '__main__':
nums1 = [2, 2, 11, 15]
target = 4
res1 = Solution.twoSum(nums1, target)
print(res1)
|
787f0fa89302f42e391d89e853be6ca2b8172f77 | trancongtu550/Python4 | /lab1.py | 1,213 | 3.640625 | 4 | #Chương 3 bài 1
print(min(2,3,4))
print(max(2,(-3),7,4,5))
print(max(2,(-3),min(4,7),-5))
#Chương 3 bài 2
print(min(max(3, 4), abs(-5)))
print(abs(min(4, 6, max(2, 8))))
print(round(max(5.572, 3.258), abs(-2)))
#Chương 3 bài 3
def triple(num):
return num * 3
triple(3)
#Chương 3 bài 4
def absolute_difference(number1, number2):
return abs(number1 - number2)
absolute_difference(3, 7)
#Chương 3 bài 5
def km_to_miles(km):
return km / 1.6
km_to_miles(5)
#Chương 3 bài 6
def average_grade(grade1, grade2, grade3):
return (grade1 + grade2 + grade3) / 3
average_grade(80, 95, 90)
#Chương 3 bài 7
def top_three_avg(grade1, grade2, grade3, grade4):
total = grade1 + grade2 + grade3 + grade4
top_three = total - min(grade1, grade2, grade3, grade4)
return top_three / 3
return max(average_grade(grade1, grade2, grade3),
average_grade(grade1, grade2, grade4),
average_grade(grade1, grade3, grade4),
average_grade(grade2, grade3, grade4))
return (grade1 + grade2 + grade3) / 3
top_three_avg(50, 60, 70, 80)
#Chương 3 bài 8
def weeks_elapsed(day1, day2):
return (day1+day2)%7
weeks_elapsed(3,20)
#Chương 3 bài 9
def square(num):
return num*3
square(3) |
e0a1152fc86e3c24a44baa42a4ad2cc5f0baa460 | GerardProsper/Python-Basics | /Lesson 4_10152020.py | 4,341 | 3.828125 | 4 |
##Find Longest Substring / Guessing Game - Python Basics with Sam
##sen = 'Hi Sam, nice to meet you'
##split = sen.split()
##>>> split
##['Hi', 'Sam,', 'nice', 'to', 'meet', 'you']
##
##
##comma = 'Sam,Tom,Pete,Matt'
##new = comma.split(',')
##>>> new
##['Sam', 'Tom', 'Pete', 'Matt']
##name = input("Please enter names use commas: ").split(',')
##
##names = [ i.strip() for i in name ]
##
##
##print(names)
##
##Please enter names use commas: Sam, Tom, Pete, Matt
##['Sam', 'Tom', 'Pete', 'Matt']
##
##w/o strip()
##Please enter names use commas: Sam, Tom, Pete, Matt
##['Sam', ' Tom', ' Pete', ' Matt']
##
##w/o split(',')
##Please enter names use commas: Sam, Tom, Pete, Matt
##['Sam,', 'Tom,', 'Pete,', 'Matt']
# can add to a string using += but cannot -=
##>>> x += 'S'
##>>> x
##'abcaafahbaabdfgzS'
##>>> x -= m
##Traceback (most recent call last):
## File "<pyshell#13>", line 1, in <module>
## x -= m
##NameError: name 'm' is not defined
##x = 'abcaafahbaabdfgz'
##
##sub = x[0]
##long, length = sub, 1
##
##for letter in x[1:]:
## print('------New Loop---------')
## print(letter,'Main letter')
## print(sub,'Main sub')
## if ord(sub[-1]) <= ord(letter):
## print('---------if-----------')
## print(sub,'sub 1')
## print(letter, 'letter 1')
## sub += letter
## print (sub, 'sub 2')
## print (letter, 'letter 2')
## print(len(sub),'is sub Length')
## print(length,'is OR/New Length')
## if len(sub) > length:
## print(length, 'is old length in if statement')
## length = len(sub)
## print(length, 'is new length in if statement')
## print(long, 'long 1')
## long = sub
## print (long, 'long 2')
## print (sub, 'sub 3')
## else:
## print('--------else-------')
## print(sub,'sub 4')
## sub = letter
## print(letter,'letter 3')
## print (sub, 'sub 5')
##
##print('---- FINALLY----')
##print(long,'long 3')
##print('---- FINALLY----')
##dad ='dadaddadaadada'
##
##count, place = 0,0
##
##while dad.find('dad',place) >= 0:
## place = dad.find('dad',place) + 1
## print(place, 'place')
## count += 1
## print(count, 'count')
##>>> from math import pi
##>>> pi
##3.141592653589793
##>>> import math
##>>> dir(math)
##['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
##>>> math.pi
##3.141592653589793
##from string import ascii_lowercase as lower
##import re
##
##x = 'abcaafahbaabdfgz'
##
##abc = ''
##
####for letter in lower:
#### abc += letter + '*'
#### print (abc)
##
####abc = '*'.join(lower)
####abc += '*'
##
##abc = 'a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*'
##
##pat = re.compile(abc)
##
##print (max(pat.findall(x),key=len))
##ans = False
##
##high = 100
##low = 0
##
##input('Think of a number between 1 to 100. Press enter to continue.')
##
##while not ans:
## guess = (high - low)//2 + low
## print(guess,' Guess')
## print(low,' Low')
## print(high,' High')
## print(f'Is your number {guess}')
## resp = input("""Enter 'h' to indicate the guess is too high.
##Enter 'l' to indicate the guess is too low.
##Enter 'c' to indicate I guessed correctly.
##Enter Answer: """).lower()
## print()
## if resp == 'h':
## high = guess
## elif resp == 'l':
## low = guess
## elif resp == 'c':
## ans = True
## print('Thanks for playing with me')
##import re
##
##dad ='dadaddadaadada'
##
##found = re.findall(r'(?=(\w\w\w))',dad)
##
##dads = [dad for dad in found if dad == 'dad']
##
##print(len(dads))
x = 4
def add(x):
print(x + 2)
add(2)
|
e45468bee33c3ba54bed011897de4c87cdf5b669 | GerardProsper/Python-Basics | /Lesson 1_10102020.py | 2,366 | 4.3125 | 4 |
## Intro to Python Livestream - Python Basics with Sam
name = 'Gerard'
####print(name)
##
##for _ in range(3):
## print(name)
##
##for i in range(1,5):
## print(i)
l_5=list(range(5))
##
##for i in range(2,10,2):
## print(i)
##for num in l_5:
## print(num)
## print(num*2)
## print()
##
##letters = 'PTJB'
##
##for letter in letters:
## print(letter + name[1:])
##def hello():
## name = input("Enter name:")
## print('Hello ' + name)
##
##hello()
##def blank():
## print()
##
##def blank_3():
## blank()
## blank()
## blank()
##
##def blank_9():
## blank_3()
## blank_3()
## blank_3()
##
##blank_9()
numbers = [1,-5,2,-4,0,6,-10,3]
##for number in numbers:
## if number % 2 == 0:
## print(number, "is even")
## else:
## print (number, "is odd")
##
##for number in numbers:
## if number == 0:
## print ("Zero")
## elif number > 0:
## print ("positive")
## else:
## print("negative")
##
##def even(x):
## """ enter number to be checked if even"""
## if x % 2 == 0:
## return True
##def even(x):
## return x % 2 == 0
##
##def odd(y):
## return y % 2 != 0
##
##print (even(4))
##
##print (odd(3))
##for row in range (5):
## for col in range(5):
## print(col,end='') ##cannot use 'sep' as only calling out col and not row. 'end' makes a row become column (or everything one line) https://www.youtube.com/watch?v=1CGZ9YDCeWg
## print() # if have print with 'for col' then it's the same as just print(col) as print () supersedes print (col, end=''). Putting it here makes it break after finishing col
##
##
##01234
##01234
##01234
##01234
##01234
##
##
##>>> for row in range (5):
## for col in range (5):
## print(col,end='')
##
##
##0123401234012340123401234
##
##
##>>> for row in range (5):
## for col in range (5):
## print(col,end='')
## print()
##
##
##0
##1
##2
##3
##4
##0
##1
##2
##3
##4
##0
##1
##2
##3
##4
##0
##1
##2
##3
##4
##0
##1
##2
##3
##4
##
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
people = [" Malaysia", "Singapore", "China"]
for x in adj:
for y in fruits:
for z in people:
print(x,y,z)
|
22d29d020b8139c01351ead5349f8a113532db32 | salonisingh-23/completePy | /speechToText.py | 415 | 3.546875 | 4 | import speech_recognition as sr
AUDIO_FILE = ("sample.wav")
r=sr.Recognition() #initialize the recognizer
with sr.AudioFile(AUDIO_FILE) as source:
audio=r.record(source)
#reads the audio file
try:
print("audio file contains "+r.recognize_google(audio))
except sr.UnknownValueError :
print("Google Speech Recognition could not understand audio")
except sr.RequestError :
print("Could not get it") |
b212b74cc8399bfaf1e38e9d03aee77cf1c1baff | kevintfrench/python | /lists3_ages.py | 232 | 4.0625 | 4 | ages=[]
age = int(input("Enter an age of a group member. Enter -1 when done")
# operators "!=" means "does not equal"
while (age != -1):
ages.append(age)
age = int(input("Enter an age of a group member. Enter -1 when done")) |
7db4fe90424179bd3c01b5c2c567b9256ed9c2d7 | asadalarma/python_crash_course | /basic_calculator.py | 158 | 4.21875 | 4 | # In this calculator we will add two numbers
num1 = input("Enter Number1: ")
num2 = input("Enter Number2: ")
result = float(num1) + float(num2)
print(result) |
571a49102f9a3ec4f8263c31ae17223662191e1f | KhalidHaji/Digital-Clock-with-Python | /clock.py | 535 | 3.578125 | 4 | from tkinter import *
from tkinter import Label, Tk
from time import strftime
root=Tk()
root.title("SAACAD")
root.geometry("350x150")
root.resizable(0,0)
text_font=("ds-digital",50)
background = "#f2e750"
foreground= "#363529"
border_width = 25
def time_clock():
string= strftime("%H:%M:%S")
label.config(text=string)
label.after(1000, time_clock)
label = Label(root, font=text_font, bg=background, fg=foreground, bd=border_width)
label.grid(row=0, column=1)
time_clock()
root.mainloop() |
f5af116e98419b83db0fa3e9a155dba805773e22 | lananovikova10/learn_python_l1 | /price.py | 690 | 3.546875 | 4 |
#Создайте функцию format_price, которая принимает один аргумент price
#Приведите price к целому числу (тип int)
#Верните строку "Цена: ЧИСЛО руб."
#Вызовите функцию, передав на вход 56.24 и положите результат в переменную
#Выведите значение переменной с результатом на экран
def format_price(price):
int_price = int(price)
#создаем новую, не перезаписываем
return f'Цена: {int_price} руб.'
formatted_price = format_price(56.24)
print(formatted_price) |
9cc813a9c85692783780488b2a7e0bd8ad1a3546 | Veklis/Veklis | /move zeroes to left.py | 404 | 3.875 | 4 | def move_zeros_to_left(A):
if len(A) < 1:
return
lengthA = len(A)
write = lengthA - 1
read = lengthA - 1
while(read >= 0):
if A[read] != 0:
A[write] = A[read]
write -= 1
read -= 1
while(write >= 0):
A[write]=0;
write-=1
v = [1, 10, 20, 0, 59, 63, 0, 88, 0]
print("Original Array:", v)
move_zeros_to_left(v)
print("After Moving Zeroes to Left: ", v)
|
58100c6dc1fc24c789e2e560fc4c2b818a5d1b4b | ania4data/HTML_SQL_Webscraping | /Python/excercise/oop3_j_udemy.py | 1,119 | 3.8125 | 4 |
class Account():
'''
create an account with account ower and
initial money, capable of adding removing (conditional)
from the account
'''
def __init__(self, name, amount=0):
self.owner = name
self.amount = amount
def deposit(self, add_amount):
self.amount += add_amount
return f'Deposit Accepted'
def withdraw(self, withdraw_amount):
tmp = self.amount - withdraw_amount
if tmp < 0:
return f'Funds Unavailable'
else:
self.amount = tmp
return f'Withdrawal Accepted'
def __str__(self):
'''
overwrite the object memory address
and using print comes to __str__
'''
return f'Account owner: {self.owner}\nAccount balance: ${self.amount}'
def __del__(self):
print('Account of {} with content ${} was deleted'.format(self.owner, self.amount))
if __name__ == '__main__':
acct = Account('Anoosheh',100)
print(acct)
#Account owner: Jose
#Account balance: $100
print(acct.owner, 'Anoosheh')
print(acct.amount, '100')
print(acct.deposit(50), 'Deposit Accepted')
print(acct.withdraw(75), 'Withdrawal Accepted')
print(acct.withdraw(500), 'Funds Unavailable!')
del acct |
f056f4e1ec699fb1f6ff0157f3afabae4d081dfc | Wrangler416/afs200 | /week5/lambda/lambda.py | 233 | 4.09375 | 4 | #create a function that takes one argument,
# and that argument will be multiplied with an unknown given number.
def func_compute(num):
return lambda x : x * num
result = func_compute(2)
print("Double the number =", result(30))
|
a5336ab6b2ac779752cab97aee3dcca16237a4d7 | dkrajeshwari/python | /python/prime.py | 321 | 4.25 | 4 | #program to check if a given number is prime or not
def is_prime(N):
if N<2:
return False
for i in range (2,N//2+1):
if N%i==0:
return False
return True
LB=int(input("Enter lower bound:"))
UB=int(input("Enter upper bound:"))
for i in range(LB,UB+1):
if is_prime(i):
print(i) |
a4f7aa89a626dc4c5615c2d8eab8fd8a39f77fd7 | dkrajeshwari/python | /assignment 1/fib.py | 308 | 4.03125 | 4 | def fibo(n):
if n <= 1:
return n
else:
return(fibo(n-1) + fibo(n-2))
num = int(input("Enter the number"))
#temp=0
if num <= 0:
print("Cannot find fibonacci")
else:
print("Fibonacci series:")
for i in range(num):
#temp=fibo(i)
print(fibo(i))
|
204a83101aee7c633893d87a111785c3884829de | dkrajeshwari/python | /python/bill.py | 376 | 4.125 | 4 | #program to calculate the electric bill
#min bill 50rupee
#1-500 6rupees/unit
#501-1000 8rupees/unit
#>1000 12rupees/unit
units=int(input("Enter the number of units:"))
if units>=1 and units<=500:
rate=6
elif units>=501 and units<=1000:
rate=8
elif units>1000:
rate=12
amount=units*rate
if amount<50:
amount=50
print(f"Units used:{units},Bill amount:{amount}")
|
644828ddfcfb3079cb8e429e3e6457cc9481d669 | dkrajeshwari/python | /python/sum.py | 188 | 4.03125 | 4 | #program to find the sum of series of factorial
N=int(input("Enter the number:"))
sum=0
for i in range (1,N+1):
for j in range(1,i+1):
sum+=1/i
print(f"result is {sum}")
|
6115e3eac9a36d7298c5668846494abd78dae49c | dkrajeshwari/python | /lab question/13.py | 191 | 3.859375 | 4 | def showInfo(student_dict):
for key,value in student_dict.items():
print(f"{key}:{value}")
student_dict={"ncet-ec01":"rajesh","ncet-ec02":"mahesh"}
showInfo(student_dict) |
ef9edd99d38e1c343caee4f82c1dbcadd72b1ef3 | dkrajeshwari/python | /ds/4.py | 404 | 3.859375 | 4 | def binarysearch(lst,key):
l=0
h=len(lst)-1
while l<=h:
mid=(l+h)//2
if lst[mid]==key:
return mid
elif key>lst[mid]:
l=mid+1
else:
h=mid-1
return -1
ele=20
res=binarysearch([1,2,3,4,5,6,7,8],ele)
if res==-1:
print(f"{ele} is not found")
else:
print(f"{ele} is found at:{res}")
|
3481309475c25990054d95fcf8d5aa9bc8dd7fa0 | peRFectBeliever/TechNotes | /pythonNotes/samplePgms/basics/3_AllBasics.py | 158 | 3.859375 | 4 | print("Python basics - all in 1")
myInt=7
print(f'Integer value stored on myInt is : {myInt}')
myFloat1=7.0
print(myFloat1)
myFloat2=float(7)
print(myFloat2)
|
660f154a44ced73336e03755dd3e66f3a35ee152 | Wintellect/WintellectWebinars | /2017-04-06 - Pythonic Code Through 5 Examples/tip5_slots/clses.py | 346 | 3.5 | 4 | class House:
def __init__(self, beds, price, date=None):
self.date = date
self.price = price
self.beds = beds
house = House(3, 102000)
print(house.price)
house.other = "New!"
print(house.other)
print(house.__dict__)
house2 = House(5, 104000)
print(house2.__dict__)
print(id(house2.__dict__), id(house.__dict__))
|
00a42f3e5c64d5cdc9d1dabfb1de2398e46da0df | Wintellect/WintellectWebinars | /2017-04-20-python-for-dotnet-kennedy/dungeon_game/game.py | 2,204 | 4.0625 | 4 | #! /usr/bin python3
from creature import Creature
from room import Room
def main():
print_header()
room = build_rooms()
play(room)
def print_header():
print("*" * 80)
print(" Welcome to the dungeon")
print(" Where dragons come to play")
with open('logo.txt') as fin:
text = fin.read()
print(text)
def build_rooms():
dragon = Creature(12, 'Green dragon')
cave = Room(name='A dark cave', creature=dragon)
starting = Room('The main hall', right=cave)
return starting
def play(room):
you = Creature(12, 'wizard')
last_room = room
while True:
if last_room != room:
last_room = room
print("You enter a room: " + room.name)
action = input("What do you want to do? [L]ook? [F]ight, Move: L, R, F: ").strip().lower()
if action == 'l':
if room.creature:
print("There is a {} here!".format(room.creature.name))
elif room.left:
print("There is a {} to left".format(room.left.name))
elif room.right:
print("There is a {} to right".format(room.right.name))
elif room.forward:
print("There is a {} ahead".format(room.forward.name))
else:
print("Here is nothing to see")
if action == 'f':
if room.creature:
print("You fight the {}!".format(room.creature.name))
if you.fight(room.creature):
print("You have defeated {}".format(room.creature.name))
with open('winning.txt') as fin:
print(fin.read())
break
else:
print("You have died.")
with open('losing.txt') as fin:
print(fin.read())
break
else:
print("Here is nothing to see")
if action == 'l' and room.left:
room = room.left
if action == 'r' and room.right:
room = room.right
if action == 'f' and room.forward:
room = room.forward
if __name__ == '__main__':
main()
|
63b8ac0396ab073fbdc8072f82601c585d90c47a | Wintellect/WintellectWebinars | /2017-04-06 - Pythonic Code Through 5 Examples/tip3_lambdas/lambdas.py | 413 | 3.96875 | 4 | # as predicate
def find_numbers(nums, test):
lst = list()
for i in nums:
if test(i):
lst.append(i)
return lst
#
# def is_even(n):
# return n % 2 == 0
result = find_numbers([1, 2, 3, 8, 3, 2, 87, 54, 55, 88, -2, -10],
lambda n: n % 2 == 0)
print(result)
# sorting example
result.sort()
print(result)
result.sort(key=lambda v: abs(v))
print(result)
|
6a92d1aa3bd84b46fa6bb4736db0a426558215b2 | talvane-lima/Cryptography | /CifradorCesar.py | 1,528 | 3.71875 | 4 | #coding: utf-8
def cifrador_cesar(texto, key=1):
texto_cifrado = ""
for n in texto:
if n < 'a' or n > 'z':
texto_cifrado += n
continue
if n == 'z':
texto_cifrado += 'a'
else:
texto_cifrado += chr(ord(n) + key)
return texto_cifrado
file = open('pt-BR.dic', 'r')
aux_dic = file.read().split("\n")
dic = []
for n in aux_dic:
dic.append(n.split("/")[0].replace('á', "a").replace('ã', "a").replace('à', "a").replace('â', "a").replace('é', "e").replace('ê', "e").replace('í', "i").replace('ó', "o").replace('ô', "o").replace('õ', "o").replace('ú', "u").replace('ç', "c").lower())
dic_string = "".join(dic)
count_dic = {}
letter = ord('a')
while chr(letter) != 'z':
count_dic.update({chr(letter):dic_string.count(chr(letter))})
letter += 1
import operator
count_dic = sorted(count_dic.items(), key=operator.itemgetter(1))[::-1]
file = open('texto.txt', 'r')
texto = file.read().replace('á', "a").replace('ã', "a").replace('à', "a").replace('â', "a").replace('é', "e").replace('ê', "e").replace('í', "i").replace('ó', "o").replace('ô', "o").replace('õ', "o").replace('ú', "u").replace('ç', "c").lower()
count_dic_texto = {}
letter = ord('a')
texto_cifrado = cifrador_cesar(texto)
while chr(letter) != 'z':
count_dic_texto.update({chr(letter):texto_cifrado.count(chr(letter))})
letter += 1
count_dic_texto = sorted(count_dic_texto.items(), key=operator.itemgetter(1))[::-1]
output = []
for i in range(27):
texto_cifrado = cifrador_cesar(texto_cifrado)
print texto_cifrado |
10e72372df58c2e9aec57a9c175e0402b464144a | thinhntr/pos | /utils.py | 2,901 | 3.9375 | 4 | from typing import Collection, Iterable, List, Sized, Tuple, Union
import readline
def lcs(s1: str, s2: str, len1: int, len2: int) -> int:
"""Longest Common Subsequence using recursive method"""
if 0 in (len1, len2):
return 0
elif s1[len1 - 1] == s2[len2 - 1]:
return 1 + lcs(s1, s2, len1 - 1, len2 - 1)
else:
return max(lcs(s1, s2, len1 - 1, len2), lcs(s1, s2, len1, len2 - 1))
def dp_lcs(X: str, Y: str):
"""Longest Common Subsequence implementation using dynamic programming"""
m = len(X)
n = len(Y)
L: List[List[int]] = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
continue
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
return L[m][n]
def clrscr():
"""Clear terminal screen"""
print("\n" * 100)
def is_not_valid_input(value: str) -> bool:
"""Return True if `value` is not valid to set to a product"""
return " ".join(value.strip().split()) == ""
def to_valid_price(value: Union[str, int]) -> int:
"""Convert `value` to int type
If `value` is a string then preprocess and convert it to int
Raises
------
RuntimeError
If `value` can't be convert to a positive integer
"""
if isinstance(value, str):
value = value.replace(" ", "")
if not value.isdecimal():
raise RuntimeError(f"Can't convert{value} to int")
value = int(value)
return value
def construct_poll(
choices: Collection[Union[str, int]], choices_values: Collection[str]
) -> List[Tuple[str, str]]:
"""Merges options and option_values into a list to create a poll
Raises
------
ValueError
If len(options) != len(options_values)
"""
if len(choices) != len(choices_values):
raise ValueError("len of choices and contents doesn't match")
return list(zip(map(str, choices), choices_values))
def get_choice(
poll: Collection[Tuple[str, str]], title: str = "Choose one of these"
) -> Union[str, int, None]:
"""
Create a poll and get user's choice
"""
print(title)
valid_choices = ["c"]
for option in poll:
print(f" {option[0]}) {option[1]}")
valid_choices.append(str(option[0]))
print(" c) Cancel")
choice = input("Your choice: ").strip()
if choice == "c" or choice not in valid_choices:
return None
return int(choice) if choice.isnumeric() else choice
def rlinput(prompt: str, prefill: str = ""):
"""
Read user's input. Default input is set with `prefill`
"""
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return input(prompt)
finally:
readline.set_startup_hook() |
458273bb73e4b98f097fbb87cfa531f994f55fc7 | vaishnavi59501/DemoRepo1 | /samplescript.py | 2,635 | 4.59375 | 5 | #!/bin/python3
#this scipt file contains list,tuple,dictionary and implementation of functions on list,tuple and Dictionary
#list
#list is collection of objects of different types and it is enclosed in square brackets.
li=['physics', 'chemistry', 1997, 2000]
list3 = ["a", "b", "c", "d"]
print(li[1]) #accessing first element in list li
print(li) #diplaying the list li
print(li[:2]) #displaying range of elements in list
print(li*2) #displaying list li two times using repetition operator(*)
l=li+list3
print(l) #concatenating two lists and displaying it
#updating list
li[2]='physics'
print(li)
a=1997
print(a in li) #returns true if a is member of list otherwise false
print(len(li)) #returns the no of elements in list
print(max(list3)) #returns maximum element in list list3
print(min(list3)) #returns minimum element in list list3
list3=list3+["e","f"] #adding elements to the list
print(list3)
tuple1=(1,2,3,4,5)
print("tuple :",tuple1) #converting sequence of elements (e.g. tuple) to list
print("tuple converted to list ",list(tuple1))
print(list1.count(123)) #returns the number of occurence of the element in the list
print(list3)
del list3[3] #deletes the element at index 3 in list3
print(list3)
#tuple
#tuple is similar to list but the difference is elements are enclosed using braces () and here updating tuple is not valid action.
tup=(23,) #declaring tuple with single element along with character comma
print(tup)
print(tup+(34,36,37)) #adding elements to tuple
print(len(tup)) #returns the no of elements in tuple
print(tuple(li)) #converts list li to tuple
#Dictionary
#Dictionary is kind of hash table type whicl has key-value pairs
dict1={1:"apple",2:"orange"} #declaring dictionary with key:value pair, here key can be of numeral or string datatype
print(dict1)
print(dict1[2]) #getting the value of key 2
print(dict1.keys()) #extracting keys set from dictionary
print(dict1.values()) #extracting values set form dictionary
dict1[3]="grapes" #adding new key value pair
print(dict1)
#del dict1[3]
print(dict1[1])
print(len(dict1)) # returns the no of key-value pairs in dictionary dict1
print(str(dict1)) # displays dict1 in string representation
print(type(dict1)) # returns the type of dict1
dict2=dict1.copy() #copying dict1 to dict2
print(dict2)
dict3=dict.fromkeys(list3,"value") #converting list to dictionary with default value-"value"
print(dict3)
print(dict1.get(2)) #accessing value of key 2 in dictionary
print(dict1.get(4,"pears"))
print(dict1)
dic={4:"avacado"}
dict1.update(dic) #adding new key-value pair to existing dict1 by update() method
print(dict1)
|
d70ecbb5a0f9044e20525c95899d8660edc77e11 | pure-escapes/FizzBuzzerAPI | /src/FizzBuzzer/testFizzBuzzer.py | 3,963 | 3.515625 | 4 | # -*- coding: utf-8 -*-
'''
Created on 22 Sep 2017
@author: Christos Tsotskas
'''
import unittest
import json
import xmlrunner
from FizzBuzzer import FizzBuzzer
class testFizzBuzzer(unittest.TestCase):
def setUp(self):
self.FizzBuzzer = FizzBuzzer()
def tearDown(self):
pass
def test_return_Fizz_when_integer_number_is_devisible_by_number_three(self):
expected_value = 'Fizz'
user_input = 3
received_value = self.FizzBuzzer.check_User_Input(user_input)
error_message = "%s was not returned as an output, when %d was provided as an input! The method returned %s, whereas %s was expected" % (expected_value, user_input, received_value , expected_value)
self.assertEquals(received_value, expected_value, error_message)
def test_return_Buzz_when_integer_number_is_devisible_by_number_five(self):
expected_value = 'Buzz'
user_input = 5
received_value = self.FizzBuzzer.check_User_Input(user_input)
error_message = "%s was not returned as an output, when %d was provided as an input! The method returned %s, whereas %s was expected" % (expected_value, user_input, received_value , expected_value)
self.assertEquals(received_value, expected_value, error_message)
def test_return_number_as_a_string_when_integer_number_is_neither_devisible_by_number_five_nor_three(self):
user_input = 7
expected_value = str(user_input)
received_value = self.FizzBuzzer.check_User_Input(user_input)
error_message = "%s was not returned as an output, when %d was provided as an input! The method returned %s, whereas %s was expected" % (expected_value, user_input, received_value , expected_value)
self.assertEquals(received_value, expected_value, error_message)
def test_return_FizzBuzz_when_integer_number_is_devisible_by_number_five_and_three(self):
expected_value = 'FizzBuzz'
user_input = 15
received_value = self.FizzBuzzer.check_User_Input(user_input)
error_message = "%s was not returned as an output, when %d was provided as an input! The method returned %s, whereas %s was expected" % (expected_value, user_input, received_value , expected_value)
self.assertEquals(received_value, expected_value, error_message)
def test_an_exception_is_raised_if_a_bad_input_is_provided(self):
user_input = "somethingBad!"
with self.assertRaises(Exception) as context:
self.FizzBuzzer.check_User_Input(user_input)
error_message = 'an exception with message "Integer was expected" should have been raised'
self.assertTrue('Integer was expected' in str(context.exception), error_message)
def test_a_json_file_is_generated_as_an_output(self):
expected_value = 'FizzBuzz'
check_for_json_type_output = False
received_output = None
user_input = 15
received_json_output = self.FizzBuzzer.get_output(user_input)
try:
received_output = json.loads(received_json_output)
check_for_json_type_output = True
except ValueError as exception_of_value:
print('invalid json: %s' % exception_of_value)
self.assertTrue(check_for_json_type_output,"a valid json file was expected!")
read_output = received_output['output']
error_message = "The parsed valued of FizzBuzzer should be 'FizzBuzz', whereas %s was received" %(read_output)
self.assertEquals(read_output, expected_value, error_message)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
|
ba69b0fe11f7c48d04be3ec552d73b265f7131ba | z3li3us/python-specialization-coursera-coding-assignments | /FILE ACCESS HARD/FAH.py | 469 | 3.59375 | 4 | #filename:mbox-short.txt
fname=input("Enter file name : ")
try:
fh=open(fname)
except:
print("WRONG FILE")
exit()
count=0
total=0
for line in fh:
line=line.rstrip()
if not line.startswith('X-DSPAM-Confidence'):
continue
count=count+1
#print(line,count)
#for x in line:
num=float(line[19:])
#print(num)
total=total+num
#print(count,total,total/count)
print("Average spam confidence:",total/count)
|
0ea2a79b3ba2a4253f43b34e996f402ccd15020c | nachommartin/ejercicios-bucles | /ejer7.py | 346 | 3.90625 | 4 | year = int (input ("Introduce el año"))
if year > 0:
if year % 400 == 0:
print ("es bisiesto")
if year % 4 == 0:
if year % 100 == 0:
year = ("no es bisiesto")
else:
year = ("es bisiesto")
print (year)
else:
print ("no es bisiesto")
else:
print ("Error") |
230140f32be64724d9a351c557ff853d258e7cee | lechodiman/IIC2233-Learning-Stuff | /Threads/lock_codebasics.py | 634 | 3.578125 | 4 | import time
import threading
class Value:
def __init__(self, value):
self.value = value
def deposit(balance, lock):
for i in range(100):
time.sleep(0.01)
lock.acquire()
balance.value += 1
lock.release()
def withdraw(balance, lock):
for i in range(100):
time.sleep(0.01)
with lock:
balance.value -= 1
balance = Value(200)
lock = threading.Lock()
d = threading.Thread(target=deposit, args=(balance, lock))
w = threading.Thread(target=withdraw, args=(balance, lock))
d.start()
w.start()
d.join()
w.join()
print('Balance: {}'.format(balance.value))
|
a373bb36bab20b9f5b20da3017693f0eb55f259a | lechodiman/IIC2233-Learning-Stuff | /Input Output/pickle_module.py | 415 | 3.53125 | 4 | import pickle
from linked_lists import LinkedList
# example_dict = {1: "6", 2: "2", 3: "f"}
#
# pickle_out = open('dict.pickle', 'wb')
# pickle.dump(example_dict, pickle_out)
# pickle_out.close()
pickle_in = open('dict.pickle', 'rb')
example_dict = pickle.load(pickle_in)
pickle_in.close()
my_list = LinkedList(2, 3, 4, 5, "s", example_dict)
with open('my_list.pickle', 'wb') as wf:
pickle.dump(my_list, wf)
|
c47c367fd30e78ed7c100e11b11cf2a03a63c401 | lechodiman/IIC2233-Learning-Stuff | /Simulation/ayu_9_sim.py | 3,029 | 3.609375 | 4 | import random
from collections import deque
class Jugador:
def __init__(self, id):
self.id = id
self.habilidad = random.uniform(1, 10)
self.jugados = 0
def win_vs(self, oponent):
p = random.choice([True, False])
if self.habilidad > oponent.habilidad and p:
return True
else:
return False
@property
def retirarse(self):
if self.jugados > random.uniform(1, 10):
return True
else:
return False
def __repr__(self):
return "Jugador {}".format(self.id)
class Simulacion:
def __init__(self, jugadores=3, tiempo_max=70):
self.cola = deque()
self.jugando = deque()
self.lista_eventos = list()
for i in range(jugadores):
self.cola.append(Jugador(i))
self.id = i + 1
self.tiempo_max = tiempo_max
def ordenar_lista(self):
self.lista_eventos.sort(key=lambda x: x[0])
def tiempo_llegada(self, tiempo):
self.lista_eventos.append((tiempo + random.expovariate(1 / 15), 'llegada'))
def tiempo_partido(self, tiempo):
self.lista_eventos.append((tiempo + random.uniform(4, 5), 'fin partido'))
def llenar_mesa(self, tiempo):
if len(self.jugando) < 2:
if len(self.jugando) == 0:
if len(self.cola) >= 1:
self.jugando.append(self.cola.popleft())
if len(self.jugando) == 1:
if len(self.cola) >= 1:
self.jugando.append(self.cola.popleft())
if len(self.jugando) == 2:
print("[{}] Comienza partido entre {}, {}".format(tiempo, *self.jugando))
self.tiempo_partido(tiempo)
def llegada_personas(self, tiempo):
self.tiempo_llegada(tiempo)
p = Jugador(self.id)
self.id += 1
self.cola.append(p)
print('[{}] LLegó la persona {}'.format(tiempo, p))
def fin_partido(self, tiempo):
j1 = self.jugando.popleft()
j2 = self.jugando.popleft()
if j1.win_vs(j2):
if not j2.retirarse:
self.cola.append(j2)
self.jugando.append(j1)
else:
if not j1.retirarse:
self.cola.append(j1)
self.jugando.append(j2)
print('[{}] Termino el partido entre {} y {}'.format(tiempo, j1, j2))
self.llenar_mesa(tiempo)
def run(self):
tiempo = 0
self.tiempo_llegada(tiempo)
while len(self.lista_eventos) != 0:
tiempo, evento = self.lista_eventos[0]
self.lista_eventos = self.lista_eventos[1:]
if tiempo > self.tiempo_max:
tiempo = self.tiempo_max
break
self.llenar_mesa(tiempo)
if evento == 'llegada':
self.llegada_personas(tiempo)
elif evento == 'fin partido':
self.fin_partido(tiempo)
self.ordenar_lista()
s = Simulacion()
s.run()
|
34d799a217052d39488adf4039d7f23e75dbcb48 | oscarmorrison/CodeChallenges | /30stringCompress.py | 338 | 3.796875 | 4 | string = "aaaabbbccaaa"
def compress(string):
compressed = ""
character = string[0]
count = 1
for i in range(1,len(string)):
if string[i] == character:
count += 1
else:
compressed += str(count)+character
character = string[i]
count = 1
compressed += str(count)+character
return compressed
print(compress(string)) |
88bacc3f7875b30717226c775557e592a790d306 | haachama/pythonPractice | /practice11.py | 459 | 3.546875 | 4 | import pandas as pd
# 題目:
# 將以下問卷資料的職業(Profession)欄位缺失值填入字串'others',更進一步將字串做編碼。 此時用什麼方式做編碼比較適合?為什麼?
q_df = pd.DataFrame([['male', 'teacher'], ['male', 'engineer'], ['female', None], ['female', 'engineer']],columns=['Sex','Profession'])
q_df = q_df.fillna('others')
a = pd.get_dummies(q_df[['Profession']])
q_df = pd.concat([q_df, a], axis=1)
print(q_df) |
46d85c6a471072788ab8ec99470f0b27e9d1939d | cscosu/ctf0 | /reversing/00-di-why/pw_man.py | 1,614 | 4.125 | 4 | #!/usr/bin/env python3
import sys
KEY = b'\x7b\x36\x14\xf6\xb3\x2a\x4d\x14\x19'
SECRET = b'\x13\x59\x7a\x93\xca\x49\x22\x79\x7b'
def authenticate(password):
'''
Authenticates the user by checking the given password
'''
# Convert to the proper data type
password = password.encode()
# We can't proceed if the password isn't even the correct length
if len(password) != len(SECRET):
return False
tmp = bytearray(len(SECRET))
for i in range(len(SECRET)):
tmp[i] = password[i] ^ KEY[i]
return tmp == SECRET
def get_pw_db(file_name):
'''
Constructs a password database from the given file
'''
pw_db = {}
with open(file_name) as f:
for line in f.readlines():
entry, pw = line.split('=', 1)
pw_db[entry.strip()] = pw.strip()
return pw_db
def main():
'''
Main entry point of the program. Handles I/O and contains the main loop
'''
print('Welcome to pw_man version 1.0')
password = input('password: ')
if not authenticate(password):
print('You are not authorized to use this program!')
sys.exit(1)
pw_db = get_pw_db(sys.argv[1])
print('Passwords loaded.')
while True:
print('Select the entry you would like to read:')
for entry in pw_db.keys():
print('--> {}'.format(entry))
selected = input('Your choice: ')
try:
print('password for {}: {}'.format(selected, pw_db[selected]))
except KeyError:
print('unrecognized selection: {}'.format(selected))
print('please')
if __name__ == '__main__':
main()
|
2aa12cdf32b8c5a527f0b6872704ed5287c829b7 | paulatoledo30/BCC325 | /definitions1.py | 1,060 | 3.765625 | 4 | class Agent():
"""
Implements the interface for an agent
"""
def __init__(self,env):
"""
Constructor for the agent class
Args:
env: a reference to an environment
"""
self.env = env
def act(self):
"""
Defines the agent action
Raises:
NotImplementedError:If the method is not implemented or not overidden.
"""
raise NotImplementedError('act')
class Environment:
"""
Implements the interface for an Environment
"""
def initial_percepts(self):
"""
Returns the environment initial percepts
Raises:
NotImplementedError: If the method is not implemented or not overidden.
"""
raise NotImplementedError('initial_percepts')
def signal(self,action):
"""
Returns the environment initial percepts
Raises:
NotImplementedError: If the method is not implemented or not overidden.
"""
raise NotImplementedError('signal') |
590af34c8f60677f8669c29d83830073422a75b4 | lewisc4/Song-Genre-Predictor | /Predictions/genre_predictor.py | 8,164 | 3.65625 | 4 | '''
Script to perform song genre classification based on their lyrics
'''
# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import SGDClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.pipeline import Pipeline
from sklearn.ensemble import VotingClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report, plot_confusion_matrix
''' Function to call data cleaning, data preparing and prediction functions '''
def main(csv_data):
# Remove classes we don't want to use
classes_to_remove = ['indie', 'edm']
new_class_df = remove_classes(csv_data, classes_to_remove)
# Clean the data
print("Cleaning data...")
cleaned_df = clean_data(new_class_df)
# Gather testing and training sets
print("Preparing Data...")
train_lyrics, train_genres, test_lyrics, test_genres = prepare_data(cleaned_df)
# Perform all model predictions and cross-validate using voting classifier
print("Performing Classifications...")
voting_classifier(train_lyrics, train_genres, test_lyrics, test_genres)
''' This function removes any classes we don't want to use for predictions '''
def remove_classes(csv_data, classes_to_remove):
removed = csv_data['genre'].isin(classes_to_remove)
new_data = csv_data[~removed]
return new_data
''' This function performs additional data cleansing to existing data set and saves it to a CSV '''
def clean_data(csv_data):
invalid_songs = []
# Checks if the song only contains ascii characters.
for index, row in csv_data.iterrows():
if len(row['cleaned_lyrics']) != len(row['cleaned_lyrics'].encode()):
invalid_songs.append(index) # Store index of invalid song
# Remove invalid lines based on index
valid_df = csv_data.drop(invalid_songs)
# Remove any numbers that may be in dataset
valid_df['cleaned_lyrics'] = valid_df['cleaned_lyrics'].str.replace('\d+', '')
# Make all songs the same length
shortest_song = min(valid_df['cleaned_lyrics'].str.len())
valid_df['cleaned_lyrics'] = valid_df['cleaned_lyrics'].str[0:shortest_song]
# Write cleaned data to csv
cleaned_headers = ['genre', 'song', 'group', 'cleaned_lyrics']
valid_df.to_csv('Data/CleanedGenres.csv', columns=cleaned_headers)
return valid_df
''' This function gets testing and training sets for predicitons '''
def prepare_data(csv_data):
# Make sure same number of songs from each sub-genre is used
genre_cnts = csv_data.groupby("genre")["song"].count()
min_genre_cnt = min(genre_cnts)
genre_splits = csv_data.groupby("genre").head(min_genre_cnt)
genre_splits = genre_splits.sample(frac=1)
# Split data: 80% training, 20% testing
train_idxs = np.random.rand(len(genre_splits)) < 0.80
train_data = genre_splits[train_idxs]
test_data = genre_splits[~train_idxs]
# Get cleaned lyrics and associated GROUP
train_lyrics = train_data["cleaned_lyrics"]
train_genres = train_data["group"]
test_lyrics = test_data["cleaned_lyrics"]
test_genres = test_data["group"]
return(train_lyrics, train_genres, test_lyrics, test_genres)
''' Multinomial naive Bayes classification model '''
def multinomNB_model(train_lyrics, train_genres, test_lyrics, test_genres):
# Define pipeline
multinom_pipe = Pipeline([
('tfidfv', TfidfVectorizer(ngram_range=(1,2), smooth_idf=True, use_idf=False, max_df=0.5)),
('mnb', MultinomialNB(alpha=0.02864, fit_prior=False))])
# Fit an predict model
multinom_pipe.fit(train_lyrics, train_genres)
multinom_preds = multinom_pipe.predict(test_lyrics)
# Get accuracies for this model
print("Multinomial Naive Bayes Results: ")
get_acc(multinom_preds, multinom_pipe, test_lyrics, test_genres, "Multinomial Naive Bayes Confusion Matrix", 'MNB')
# Return for voting classifier
return multinom_pipe
''' Bernoulli naive Bayes classification model '''
def bernoulliNB_model(train_lyrics, train_genres, test_lyrics, test_genres):
# Define pipelie
bern_nb_pipe = Pipeline([
('tfidfv', TfidfVectorizer(ngram_range=(1,2), smooth_idf=True, use_idf=False, max_df=0.5, binary=True)),
('bnb', BernoulliNB(alpha=0.02864, fit_prior=False))])
# Fit and predict model
bern_nb_pipe.fit(train_lyrics, train_genres)
bern_preds = bern_nb_pipe.predict(test_lyrics)
# Below is an example of finding the best parameters for various features of this model
# Depending on how many you are looking for, this can take a very long time
'''
grid_params = {
'bnb__alpha': np.linspace(0.0001, 0.1, 8),
}
get_best_params(bern_nb_pipe, grid_params, train_lyrics, train_genres)
'''
# Get accuracies
print("Bernoulli Naive Bayes Results: ")
get_acc(bern_preds, bern_nb_pipe, test_lyrics, test_genres, "Bernoulli Naive Bayes Confusion Matrix", 'BNB')
return bern_nb_pipe
''' Stochastic gradient descent model '''
def SGDC_model(train_lyrics, train_genres, test_lyrics, test_genres):
# Define pipelie
sgdc_lin_pipe = Pipeline([
('tfidfv', TfidfVectorizer(ngram_range=(1,2), smooth_idf=True, use_idf=False, max_df=0.5)),
('sclf', SGDClassifier(loss='modified_huber', penalty='l2',
alpha=0.0001, random_state=42,
max_iter=400, tol=None, class_weight='balanced'))
])
# Fit and predict model
sgdc_lin_pipe.fit(train_lyrics, train_genres)
sgdc_preds = sgdc_lin_pipe.predict(test_lyrics)
# Get accuracies
print("Stochastic Gradient Descent Results: ")
get_acc(sgdc_preds, sgdc_lin_pipe, test_lyrics, test_genres, "Stochastic Gradient Descent Confusion Matrix", 'SGD')
return sgdc_lin_pipe
''' Voting classifier is defined here to create all models, perform individual predictions, and voting predictions '''
def voting_classifier(train_lyrics, train_genres, test_lyrics, test_genres):
# Stores each model
estimators = []
# Create stochastic gradient descent model
sgdc_lin_pipe = SGDC_model(train_lyrics, train_genres, test_lyrics, test_genres)
estimators.append(('sdcglin', sgdc_lin_pipe))
# Create multinomial naive Bayes model
multinom_pipe = multinomNB_model(train_lyrics, train_genres, test_lyrics, test_genres)
estimators.append(('multinom', multinom_pipe))
# Create Bernoulli naive Bayes model
bern_pipe = bernoulliNB_model(train_lyrics, train_genres, test_lyrics, test_genres)
estimators.append(('bernoulli', bern_pipe))
# Create ensemble of models (voting classifier) and fit it to training data
print("Making Voting Predictions...")
ensemble = VotingClassifier(estimators, voting='hard', verbose=True)
ensemble.fit(train_lyrics, train_genres)
# Voting prediciton
vote_predicted = ensemble.predict(test_lyrics)
# Get voting accuracies
print("Results using cross validation of both models: ")
get_acc(vote_predicted, ensemble, test_lyrics, test_genres, "Voting Classifier Confusion Matrix", 'VC')
''' Based on a model's pipeline and grid parameters, find the optimal parameters'''
def get_best_params(model_pipeline, grid_params, train_lyrics, train_genres):
clf = GridSearchCV(model_pipeline, grid_params)
clf.fit(train_lyrics, train_genres)
print("Model: ", model_pipeline)
print("Best Score: ", clf.best_score_)
print("Best Parameters: ", clf.best_params_)
'''
Gets accuracies given predicted model, a fitted classifier, test data, and title for confusion matrix
Creates a plot of the confusion matrix and a classification report for overall and class accuracies
'''
def get_acc(predicted, classifier, test_lyrics, test_genres, conf_mat_title, fname):
# Class names
class_names = ['Blues', 'Rock', 'Rap', 'Country']
# Plot confusion matrix
disp = plot_confusion_matrix(classifier, test_lyrics, test_genres,
display_labels=class_names,
cmap=plt.cm.Blues,
normalize=None)
disp.ax_.set_title(conf_mat_title)
# plt.show()
save_name = 'Plots/' + fname + '.png'
plt.savefig(save_name)
# Classification report to get accuracies
class_report = classification_report(test_genres, predicted, target_names=class_names)
print(class_report)
''' Runs the script given a path to data file '''
if __name__ == "__main__":
# Load data in to Pandas DF
data_location = "Data/Genres.csv"
data = pd.read_csv(data_location)
main(data)
|
e4aca32ae003f3da4058cd3c0ff6ac5c59ecbf31 | KeehuanArthur/Pong-AI | /graphicstest.py | 451 | 3.75 | 4 | from graphics import *
beep = 5
def main():
print( beep )
win = GraphWin("My Circle", 500, 500)
c = Circle(Point(50,50), 10)
c.setFill('blue')
# c.draw(win)
# animation loop
x = 10
y = 10
while True:
x += 5
y += 5
# c.undraw()
j = c
j.undraw()
c = Circle(Point(x,y), 10)
c.draw(win)
win.getMouse() # pause for click in window
win.close()
main() |
8c0f814171fffa191c911d4369f9a0da1154bc1f | declarativitydotnet/declarativity | /p2_contrib/distinf/tests/runningintersection.py | 4,225 | 3.5 | 4 | #! /usr/bin/env python
# run the script:
import sys, re, os
print sys.argv
if len(sys.argv) != 2:
print 'Usage: printgraph.py <overlog output file>'
sys.exit(1)
filein = sys.argv[1]
def parse_line(line, splitter):
# print "splitter: "+splitter
temp = re.split(splitter, line)
items = re.split(',', temp[1])
# print items
i=0
for item in items:
item = item.strip()
item = item.replace('[', '')
item = item.replace(']', '')
item = item.replace('(', '')
item = item.replace(')', '')
items[i] = item
i+=1
return items
items = []
linkList = []
edgeList = []
nodeToCarried = {}
nodeToClique = {}
linkSet = {}
edgeSet = {}
nodeToSeps = {}
varToNode = {}
for line in open(filein):
# print "line: "+line
if (re.search('printSpanTreeEdge\(', line)):
splitter = 'printSpanTreeEdge\('
items = parse_line(line, splitter)
# print items
pair = [items[1], items[2]]
edgeList.append(pair)
copy = pair[:]
copy.sort()
tpair = tuple(copy)
edgeSet[tpair] = ''
elif (re.search('printLink\(', line)):
splitter = 'printLink\('
items = parse_line(line, splitter)
# print items
pair = [items[1], items[2]]
linkList.append(pair)
copy=pair[:]
copy.sort()
tpair = tuple(copy)
linkSet[tpair] = items[3]
elif (re.search('printVarCarried\(', line)):
splitter = 'printVarCarried\('
items = parse_line(line, splitter)
# print items
if (items[2] in varToNode):
listOfNodes = varToNode[items[2]]
listOfNodes.append(items[1])
else:
listOfNodes = [0]
listOfNodes.append(items[1])
varToNode[items[2]] = listOfNodes
if (items[1] in nodeToCarried):
listOfVars = nodeToCarried[items[1]]
listOfVars.append(items[2])
nodeToCarried[items[1]] = listOfVars
else:
listOfVars = [0]
listOfVars.append(items[2])
nodeToCarried[items[1]] = listOfVars
elif (re.search('printClique\(', line)):
splitter = 'printClique\('
items = parse_line(line, splitter)
# print items
if (items[1] in nodeToClique):
listOfVars = nodeToClique[items[1]]
listOfVars.append(items[2])
nodeToClique[items[1]] = listOfVars
else:
listOfVars = [0]
listOfVars.append(items[2])
nodeToClique[items[1]] = listOfVars
elif (re.search('printSeparator\(', line)):
splitter = 'printSeparator\('
items = parse_line(line, splitter)
# print items
pair = [items[1], items[2]]
pair.sort()
tpair = tuple(pair)
if (tpair in nodeToSeps):
listSeps = nodeToSeps[tpair]
if (items[3] not in listSeps):
listSeps.append(items[3])
nodeToSeps[tpair] = listSeps
else:
nodeToSeps[tpair] = list(items[3])
else:
# print "Line didn't match any splitter: "+line
continue
#items = []
#linkList = []
#edgeList = []
#nodeToCarried = {}
#nodeToClique = {}
#linkSet = {}
#edgeSet = {}
#nodeToSeps = {}
#varToNode = {}
def check(originNode, srcNode, destNode, var, count):
# if (count > 9):
# print "max depth 9, quitting"
# return False;
# else:
# count = count + 1
# print "checking: "+srcNode+" "+destNode+" "+var
result = False
neighbors= []
for (one, two) in edgeList:
if (one == srcNode and two != originNode):
if (one == srcNode and two == destNode):
return True
twoClique = nodeToClique[two]
if (var in twoClique):
result = check(srcNode, two, destNode, var, count)
if (result==True): return True
else:
result = False
return result
for node in nodeToCarried:
listOfVars = nodeToCarried[node]
listOfVars.remove(0)
nodeToCarried[node]=listOfVars
for node in nodeToClique:
listOfVars = nodeToClique[node]
listOfVars.remove(0)
nodeToClique[node]=listOfVars
finalAnswer = True
for var in varToNode:
varToNode[var].remove(0)
print "now analyzing var "+ str(var) + ": " + str(varToNode[var])
listOfNodes = varToNode[var]
if (len(listOfNodes)==1):
print "var "+var+" is in 1 node only."
continue
for i,node in enumerate(listOfNodes):
for j in range (i, len(listOfNodes)):
nodeToCheck = listOfNodes[j]
if (node == nodeToCheck): continue
# print "checking: "+node+" "+nodeToCheck+" "+var
result = check('', node, nodeToCheck, var, 0)
if (result==False):
print "OH NO!!!"
finalAnswer = False
else: print "YYAAAAHHHHH!!"
print "FINAL ANSWER: " + str(finalAnswer)
|
8fe7382e7d05ccf1b310b1a8ea2d2abc4803da83 | anjali-patel21/Practice-python | /global.py | 460 | 3.953125 | 4 | # understanding global and local variables
a = 10 # global variable
def variables():
a = 9 # local variable
print("in function a:", a)
variables()
print("outside function a:", a)
print("---------------------------------")
# if i want to use global value of 'a' inside function?
def variables2():
global a
a = 15
print("a in 2nd function:", a)
variables2()
print("a outside function:", a)
|
a000fa51d161f5f71bb881a4c50315489ab610db | anjali-patel21/Practice-python | /lambda.py | 303 | 3.96875 | 4 | # code to filter the values from given list and then changing those filtered values using anonymous function
nums = [5,6,2,9,8,7,10,12,5]
evens = list(filter(lambda n:n%2==0,nums))
print("filtered values: ",evens)
changevalue = list(map(lambda n:n+1,evens))
print("changed values: ",changevalue)
|
438658b5f7165211e7ec5dec55b63097c5852ede | alshore/firstCapstone | /camel.py | 527 | 4.125 | 4 | #define main function
def main():
# get input from user
# set to title case and split into array
words = raw_input("Enter text to convert: ").title().split()
# initialize results variable
camel = ""
for word in words:
# first word all lower case
if word == words[0]:
word = word.lower()
# add word to results string
camel += word
else:
# all other words remain in title case and
# get added to the results string
camel += word
# print results to console
print camel
# call main function
main() |
f6bbc49b11838775749c53fa20fec54990d44a5e | rodrigoschardong/Digital-Image-Processing | /png Open ( without Image Processing Libs )/image_Open.py | 4,866 | 3.5625 | 4 | """
author: Rodrigo Schardong
entity: UERGS - Universidade Estadual do Rio Grande do Sul
"""
#https://www.w3.org/TR/PNG/#8Interlace
#Libs to read file
import zlib
import numpy as np
#Libs Just to Display image and interact with them
from matplotlib import pyplot as plt
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
"""
Function name: PutInAByte
Input: pixel value
output: pixel value between 0 and 255
Doesn't required any library
"""
def PutInAByte(byte):
if(byte >= 256):
byte -= 256
return byte
"""
Function name: PNG_OPEN
Input: image file name
output: image 3D array [height, width, channels]
Required libraries: zlib, numpy
"""
def PNG_Open(image_name):
#reading file's bytes
with open(image_name, 'rb') as i:
image_b = i.read(-1)
#Getting file's info
pngLenght = len(image_b)
pngSignature = image_b[:8]
#Getting the first chunk
dataFromChunks = []
crcLenght = 4
index = 8
chunkLength = int.from_bytes(image_b[index: index + 4], "big")
index += 4
chunkType = image_b[index: index + 4].decode("utf-8")
index += 4
chunkData = image_b[index : index + chunkLength]
index += chunkLength
index += crcLenght
#Getting data from first chunk
width = int.from_bytes(chunkData[0:4], "big")
height = int.from_bytes(chunkData[4:8], "big")
bitDepth = chunkData[8]
colourType = chunkData[9]
compressionMethod = chunkData[10]
filterMethod = chunkData[11]
interlaceMethode = chunkData[12]
#print("Largura: ", width)
#print("Altura: ", height)
#Collecting compressed data
while(index <= pngLenght):
chunkLength = int.from_bytes(image_b[index: index + 4], "big")
index += 4
chunkType = image_b[index: index + 4].decode("utf-8")
index += 4
chunkData = image_b[index : index + chunkLength]
index += chunkLength
index += crcLenght
if(chunkType == "IDAT"):
dataFromChunks.append(chunkData)
#print("dataFromChunks: ", dataFromChunks)
#print("dataFromChunks lenght: ", len(dataFromChunks[0]))
#decompressing data
decompressPixels = zlib.decompress(dataFromChunks[0])
#print("Tamanho da Imagem: ", len(decompressPixels))
#print("Imagem: ", decompressPixels)
#creating images channels
out = np.zeros((height, width, 3)) # 3 channel R, G and B
#Filling the channels
index = 0
for y in range (0, height):
#Getting the filter
filterType = decompressPixels[index]
index +=1
for x in range (0, width):
if(filterType == 1):
if(x == 0):
out[y, x, 0] = decompressPixels[index]
out[y, x, 1] = decompressPixels[index + 1]
out[y, x, 2] = decompressPixels[index + 2]
else:
out[y, x, 0] = PutInAByte(decompressPixels[index] + out[y, x - 1, 0])
out[y, x, 1] = PutInAByte(decompressPixels[index + 1] + out[y, x - 1, 1])
out[y, x, 2] = PutInAByte(decompressPixels[index + 2] + out[y, x - 1, 2])
elif(filterType == 2):
out[y, x, 0] = PutInAByte(decompressPixels[index] + out[y- 1, x, 0])
out[y, x, 1] = PutInAByte(decompressPixels[index + 1] + out[y- 1, x, 1])
out[y, x, 2] = PutInAByte(decompressPixels[index + 2] + out[y- 1, x, 2])
elif(filterType == 0):
out[y, x, 0] = PutInAByte(decompressPixels[index])
out[y, x, 1] = PutInAByte(decompressPixels[index + 1])
out[y, x, 2] = PutInAByte(decompressPixels[index + 2])
else:
print("Filter type: ", filterType)
index += 3
return out
#Open Png file, display it and show pixels values of each channel from choosen position
def main(image_name, x, y):
image = PNG_Open(image_name)
print("O pixel vermelho na posicao (", x, ", ", y, ") possui valor: ", image[y, x, 0].astype(int))
print("O pixel verde na posicao (", x, ", ", y, ") possui valor: ", image[y, x, 1].astype(int))
print("O pixel azul na posicao (", x, ", ", y, ") possui valor: ", image[y, x, 2].astype(int))
if(image[y, x, 0] + image[y, x, 1] + image[y, x, 2] > (256 * 1.5)):
image[y, x, 0] = 0
image[y, x, 1] = 0
image[y, x, 2] = 0
else:
image[y, x, 0] = 255
image[y, x, 1] = 255
image[y, x, 2] = 255
plt.imshow(image.astype(int))
plt.plot() |
baee2ef5bb87ce680821d28324c8bb0609b7481b | mainuddin-rony/word-chain | /main.py | 1,872 | 3.6875 | 4 | import load_four_words_graph as four_words
import load_345_words_graph as words_345
import word_chain_finder as finder
def main():
graph_4_words = four_words.load_graph()
graph_345_words = words_345.load_graph()
while True:
chain_opt = raw_input("Enter 1 for 4-words chain or 2 for 345-words chain: \n")
if chain_opt == '1':
word1 = raw_input("Enter Start Word: \n")
word2 = raw_input("Enter End Word: \n")
if word1 == word2:
print("Words are same. Chain length is 0\n")
continue
if len(word1) != len(word2):
print("Words must be of same length. Chain length is 0\n")
continue
print('Shortest path between "%s" and "%s" using 4-words graph is:' % (word1, word2))
chain = finder.find_word_chain(word1, word2, graph_4_words)
if not None:
print(" -> ".join(chain))
print("Chain length is " + str(len(chain)-1))
elif chain_opt == '2':
word1 = raw_input("Enter Start Word: \n")
word2 = raw_input("Enter End Word: \n")
if word1 == word2:
print("Words are same. Chain length is 0\n")
continue
if len(word1) != len(word2):
print("Words must be of same length. Chain length is 0\n")
continue
print('Shortest path between "%s" and "%s" using 4-words graph is:' % (word1, word2))
chain = finder.find_word_chain(word1, word2, graph_345_words)
if not None:
print(" -> ".join(chain))
print("Chain length is " + str(len(chain) - 1))
else:
print("Please enter a valid input (1 or 2).\n")
if __name__ == '__main__':
main() |
33735735d54ebe3842fca2fa506277e2cd529734 | georgemarshall180/Dev | /workspace/Python_Play/Shakes/words.py | 1,074 | 4.28125 | 4 | # Filename:
# Created by: George Marshall
# Created:
# Description: counts the most common words in shakespeares complete works.
import string
# start of main
def main():
fhand = open('shakes.txt') # open the file to analyzed.
counts = dict() # this is a dict to hold the words and the number of them.
for line in fhand:
line = line.translate(string.punctuation) #next lines strip extra stuff out and format properly.
line = line.lower()
line = line.replace('+',' ')
words = line.split()
for word in words: # counts the words.
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
# Sort the dictionary by value
lst = list()
for key, val in counts.items():
lst.append((val, key))
lst.sort(reverse=True) # sorts the list from Greatest to least.
# print the list out.
for key, val in lst[:100]:
print(key, val)
# runs this file if it is main
if __name__ == "__main__":
main()
|
0a3ddca814b334c3681576934c12434bd4de02de | pyflask/uniqueIPvisitors | /redisOp.py | 819 | 3.625 | 4 |
class redisQ(object):
"""This class defines operations with redis queue which is used
to store all remote ip addresses sniffed from requests"""
def __init__(self, conn, qname=None):
self.conn = conn
if qname is None:
qname = "redis:Q"
self.queue = qname
def push(self, ipaddr):
return self.conn.lpush(self.queue,ipaddr)
def pop(self):
return self.conn.rpop(self.queue)
class redisHash(object):
"""This class defines operations with redis hash table (dictionary)
which is used to maintain ip addresses for unique visitors"""
def __init__(self, conn):
self.conn = conn
def set(self, ipaddr):
return self.conn.setnx(ipaddr, 'Exists')
def get(self, remoteip):
return self.conn.get(remoteip)
|
a6dcab0b8bd8c93ecc765c830d0374f6344f78d3 | BhargavKadali39/tips-to-decrease-executionTime-in-python | /using-temp.py | 393 | 3.71875 | 4 | x = 10
y = 20
temp = x
x = y
y = temp
print(x,y)
import time
start_time = time.time()
#------------------------- code area -----------------------------------------
x = 10
y = 20
temp = x
x = y
y = temp
print(x,y)
#------------------------- code area -----------------------------------------
end_time = time.time()
total_time = end_time - start_time
print("Execution time is :",total_time)
|
d85ef4cc9b3ec8018e4f060a1d5185782dcff088 | vikasb7/DS-ALGO | /same tree.py | 829 | 4.15625 | 4 | '''
Vikas Bhat
Same Tree
Type: Tree
Time Complexity: O(n)
Space Complexity: O(1)
'''
class TreeNode:
def __init__(self,val=0,left=None,right=None):
self.left=left
self.right=right
self.val=val
class main:
#Recursive
def sameTree(self,root1,root2):
if root1 and not root2:
return False
if root2 and not root1:
return False
if not root1 and not root2:
return True
if root1.val!=root2.val:
return False
return self.sameTree(root1.left,root2.left) and self.sameTree(root1.right,root2.right)
if __name__=="__main__":
t1=TreeNode(1)
t1.left=TreeNode(2)
t1.right=TreeNode(3)
t2=TreeNode(1)
t2.left=TreeNode(2)
t2.right= TreeNode(3)
v=main()
print(v.sameTree(t1,t2)) |
dad225f0531069fe83292c4633c4c8edd20b54b1 | vikasb7/DS-ALGO | /Product of Array Except Self.py | 530 | 3.671875 | 4 | '''
Vikas Bhat
Product of Array Except Self
Time Complexity : O(n)
Space Complexity: O(n)
'''
class main:
def productExceptSelf(self,nums):
res = [1]
left = 1
for i in range(len(nums) - 1, 0, -1):
res.append(res[-1] * nums[i])
res=res[::-1]
for j in range(0,len(nums)):
res[j]*=left
left*=nums[j]
return res
if __name__=="__main__":
v=main()
print(v.productExceptSelf([1,2,3,4]))
print(v.productExceptSelf([-1,1,0,-3,3]))
|
cd98de5966e85920483a3ae99ebf683c7b6a29d0 | vikasb7/DS-ALGO | /Container With Most Water.py | 528 | 3.9375 | 4 | '''
Vikas Bhat
Container With Most Water
Time Complexity: O(n)
Sapce Complexity: O(1)
'''
class main:
def maxArea(self,height):
area=1
s=0
e=len(height)-1
while s<e:
area= max(area,(e-s)*min(height[s],height[e]))
if height[s]<=height[e]:
s+=1
else:
e-=1
return area
if __name__=="__main__":
v=main()
print(v.maxArea([1,8,6,2,5,4,8,3,7]))
print(v.maxArea([1,1]))
print(v.maxArea([4,3,2,1,4])) |
33d3ee382baddb949f25456e71547781bc195029 | eljefec/eva-didi | /python/util/average.py | 526 | 3.640625 | 4 | import collections
class AverageAccumulator:
def __init__(self, maxsize):
self.maxsize = maxsize
self.samples = collections.deque()
self.sum = 0
self.average = None
def append(self, value):
self.samples.append(value)
self.sum += value
if (len(self.samples) >= self.maxsize):
popped = self.samples.popleft()
self.sum -= popped
self.average = self.sum / len(self.samples)
def get_average(self):
return self.average
|
3623a3d7e5497f9e4ce80cf559e0fdfa085c109b | Mohith22/CryptoSystem | /key_est.py | 1,438 | 4.15625 | 4 | #Diffie Helman Key Exchange
#Author : Mohith Damarapati-BTech-3rd year-NIT Surat-Computer Science
#Establishment Of Key
#Functionalities :
#1. User can initiate communication through his private key to get secretly-shared-key
#2. User can get secretly shared-key through his private key
#For Simplicity Choose -
#Prime Modulus - 10007 & Generator - 293
import sys
def findv(gen,prime,pkey):
return pow(gen,pkey,prime)
print "Welcome!!! \n"
prime = raw_input("Enter Prime Modulus Value (Public) : ")
gen = raw_input("Enter Generator Value (Public) : ")
pkey = raw_input("Enter Your Private Key (Enter It Carefully): ")
print "\n"
while True:
print "Select Your Choice : \n"
print "1. Initiate Communication - Press 1"
print "2. Get Shared-Key - Press 2"
print "\n"
while True:
choice = raw_input("Enter Your Choice: ")
print "\n"
if choice=='1':
val = findv(int(gen),int(prime),int(pkey))
print "Value Sent Is : ",
print val
break
elif choice=='2':
valu = raw_input("Enter Value You Got From The Other Party : ")
skey = findv(int(valu),int(prime),int(pkey))
print "********Shared Key Is******** : ",
print skey,
print " Keep It Secured !!! ****"
break
else:
print "Enter Valid Choice"
print "\n\n"
print "Want to something else :"
print "Press 'y'"
print "Else to exit press any key"
ch = raw_input("Choice : ")
print "\n\n"
if ch!='y':
print "Program Exit ....."
break
|
4ee114cbbacc138789cda08857a84f2a6c0ba8b4 | ryanSoftwareEngineer/algorithms | /math/1465_maximum_area_of_cake_after_cuts.py | 2,125 | 4.09375 | 4 | '''
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/
Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.
Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a huge number, return this modulo 10^9 + 7.
'''
# a better solution is simply to keep track of max height and max width of cuts
#
class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
maxheight = currentheight = 0
for i in horizontalCuts:
maxheight = max(maxheight, i-currentheight)
currentheight = i
maxheight = max(maxheight, h-horizontalCuts[-1])
maxwidth = currentwidth = 0
for i in verticalCuts:
maxwidth = max(maxwidth, i-currentwidth)
currentwidth = i
maxwidth = max(maxwidth, w-verticalCuts[-1])
return (maxheight *maxwidth) % ((10**9)+7)
# first attempt. I used a dynamic progamming algorithm to iterate through h*w and keep track of max width* height but
# this is not efficient enough
class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
row_cuts = set(horizontalCuts)
col_cuts = set(verticalCuts)
dp = [0]* w
max_so_far = 0
for row in range(h):
counter = 0
for col in range(w):
if col in col_cuts:
counter = 0
if row in row_cuts:
dp[col] =0
counter+=1
dp[col]+=1
max_so_far = max(max_so_far, (counter* dp[col]))
return max_so_far |
0f7446e0b925da206134a4a8448265f6bb567380 | ryanSoftwareEngineer/algorithms | /linked lists, queue, and stack/300_longest_increasing_subsequence.py | 1,462 | 3.59375 | 4 | '''
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without
hanging the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Could you come up with the O(n2) solution?
Could you improve it to O(n log(n)) time complexity?
'''
# create stack and counter
# iterate through array for each iteration iterate again
# if current number > stack[-1]
# add item to stack, increment counter
# else: pop until empty decrement for each pop until
# return max_so_far
# you could run this for each element... this would be o(n2)... how can I get the o(nlogn) solution ?
from collections import deque
# set dp = same length as nums initialize to 1
# for every i ... then for every j in 0 to i
# if nums[i] is greater than nums[j]... then you know that i must have +1 more than j
# take the highest of all j's to i... then add 1 for i
class Solution:
def lengthOfLIS(self, nums):
dp = [1]* len(nums)
dp[0]= 1
max_so_far = 1
for a in range(1, len(nums)):
for b in range(0, a):
if nums[a] > nums[b]:
dp[a] = max(dp[b]+1, dp[a])
max_so_far = max(max_so_far, dp[a])
print(dp)
return max_so_far
a= Solution()
input = [10,9,2,5,3,7,101,18]
b = a.lengthOfLIS(input);
print(b) |
ddbedd13893047ab7611fe8d1b381575368680a6 | ryanSoftwareEngineer/algorithms | /arrays and matrices/49_group_anagrams.py | 1,408 | 4.15625 | 4 | '''
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically
using all the original letters exactly once.
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
'''
def groupAnagrams( strs):
output = []
map = {}
map_i = 0
for i in strs:
b = i[:]
b= "".join(sorted(b))
if b in map:
output[map[b]].append(i)
else:
map[b] = map_i
output.append([i])
map_i += 1
return output
def attempttwo(strs):
# iterate through strs
# for every iteration of strs iterate through single string
# create array 0 to 26 to hold counts
# array of 26 from 0 to 26 represents count for each character
# convert to string of ints or tuple(array)
# use hash table to store string of counts
answer = {}
for word in strs:
alphabet = [0]*26
for char in word:
alphabet[ord(char.lower())-ord('a')] += 1
str_result = str(alphabet)
if str_result in answer:
answer[str_result].append(word)
else:
answer[str_result] = [word]
return list(answer.values())
strs = ["eat","tea","tan","ate","nat","bat"]
print(attempttwo(strs)) |
0dcee69f8a1fd140d89ae625308af2ae95917af5 | ryanSoftwareEngineer/algorithms | /linked lists, queue, and stack/143_reorder_list.py | 1,993 | 3.828125 | 4 | '''Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# my first thought was to loop through once, get the length and double link the list
# then iterate from end points to middle deleting the extra links along the way
# I thought looping through with two pointers to get mid, then adding pointers on a stack after mid
# a solution i looked up would have you reverse the 2nd half instead of using stack...
# thought about using recursion to pass in the start of the list and iterating next for 2nd parameter
# when you get to the end and your popping back up you return head.next to iterate from start while popping back from Ln -> ln-mid
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reorderList(self, head) -> None:
if not head:
return None
start = mid = end = head
end = end.next
while end and end.next:
mid, end = mid.next, end.next.next
end = mid.next
prev = mid
while end:
temp = end.next
end.next = prev
prev = end
end = temp
end = prev
while start != mid:
temp = start.next
temp2 = end.next
start.next = end
end.next = temp
start = temp
end = temp2
end.next = None
return head
def printll(root):
i = 1
while root and i <8 :
print(root.val)
root = root.next
i+=1
a = ListNode(1)
a.next = ListNode(2)
a.next.next = ListNode(3)
a.next.next.next = ListNode(4)
a.next.next.next.next = ListNode(5)
b= Solution()
printll(b.reorderList(a))
|
b3a10e7d1ff2eeaa7842ea556cbad3d4b3212f0c | ryanSoftwareEngineer/algorithms | /recursion and dynamic programming/91_decode_ways.py | 1,333 | 3.9375 | 4 | '''
https://leetcode.com/problems/decode-ways/
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Input: s = "226"
Output: 3
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Input: s = "06"
Output: 0
Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
'''
class Solution:
def numDecodings(self, s: str) -> int:
dp = [0 for _ in range(len(s)+1)]
dp[0] = 1
dp[1]=0 if s[0] == '0' else 1
for i in range(2, len(s)+1):
if s[i-1] != '0':
dp[i]+= dp[i-1]
val = int(s[i-2] + s[i-1])
if val >9 and val < 27:
dp[i]+= dp[i-2]
return dp[-1] |
695c0923e20fd9718ac60bc84d71d0f4279fe873 | ryanSoftwareEngineer/algorithms | /recursion and dynamic programming/45_jump_game_ii.py | 1,121 | 4.03125 | 4 | '''
Given an array of non-negative integers nums, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
You can assume that you can always reach the last index.
so why does jump game 2 come before jump game 1 on leetcode ... it's out of order I don't like that >_>
'''
# as you iterate through nums keep track of the farthest location you can jump at each phase
# farthest = the max of the current farthest or i+nums[i]
# Every time we reach a target, that starts at zero, we set our new jump target to the current farthest
# we calculate new farthest's from our current position to the new target
class Solution:
def jump(self, nums: List[int]) -> int:
if len(nums)<2:
return 0
jumps = target = far =0
for i in range(len(nums)-1):
far = max(far, i+nums[i])
if i == target:
jumps+=1
target = far
if target >= len(nums)-1:
return jumps
|
af6e84d7684517f18c24da101ebb998fe67ebcce | ryanSoftwareEngineer/algorithms | /arrays and matrices/57_insert_interval.py | 1,669 | 3.796875 | 4 | '''
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
'''
class Solution:
# The code could be a lot easier to read if this was done in two passes,
# you could iterate through first to insert the newinterval
# then iterate again to merge
# I wanted to try doing this in one pass though for fun
def insert(self, intervals, newInterval):
if len(intervals)< 1:
return [newInterval]
results = []
prev = intervals[0]
if prev[0] > newInterval[0]:
prev = newInterval
for i, cur in enumerate(intervals):
temp = prev
if prev[1]< cur[0]:
results.append(prev)
prev = cur
prev = self.merge(prev, cur)
prev = self.merge(prev, newInterval)
if temp[1]< newInterval[0] and newInterval[1] < cur[0]:
results.append(newInterval)
results.append(prev)
if newInterval[0]> prev[1]:
results.append(newInterval)
return results
def merge(self, prev, current):
if prev[1] < current[0] or prev[0]> current[1]:
return prev
prev[1] = max(prev[1], current[1])
prev[0] = min(prev[0], current[0])
return prev
intervals = [[1,3],[6,15]]
new = [4, 5]
a = Solution()
a.insert(intervals, new)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.