blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
2e7418533b0e96ccdbcc1be9958c0210639b4815 | gt6192/NeuralNetworks | /Perceptron_Model/Perceptron_Model.py | 1,173 | 3.53125 | 4 | class Perceptron:
def __init__ (self):
self.w = None
self.b = None
def model(self, x):
return 1 if (np.dot(self.w, x) >= self.b) else 0
def predict(self, X):
Y = []
for x in X:
result = self.model(x)
Y.append(result)
return np.array(Y)
def fit(self, X, Y, epoc, learning_rate = 1):
self.w = np.ones(X.shape[1])
self.b = 0
accuracy = []
max_accuracy = 0
max_accuracy_point = 0
for i in range(epoc):
for x, y in zip(X, Y):
y_pred = self.model(x)
if y == 1 and y_pred == 0:
self.w = self.w + learning_rate * x
self.b = self.b + learning_rate * 1
elif y == 0 and y_pred == 1:
self.w = self.w - learning_rate * x
self.b = self.b - learning_rate * 1
accuracy.append(accuracy_score(self.predict(X), Y))
if (accuracy[i] > max_accuracy):
max_accuracy = accuracy[i]
max_accuracy_point = i
checkw = self.w
checkb = self.b
self.w = checkw
self.b = checkb
plt.plot(accuracy)
plt.show()
print("Max accuracy = ",max_accuracy)
print("Max accuracy point = ",max_accuracy_point)
|
bd22633c3919249f080d56ea0a3c21b21d6f576f | sachin28/Python | /MustKnowPrograms/CaseSwap.py | 238 | 4.09375 | 4 | inpstr = raw_input("Enter string input: ")
revstr = []
for i in inpstr:
if i.isupper():
i = i.lower()
revstr.append(i)
else:
i = i.upper()
revstr.append(i)
revstr = "".join(revstr)
print revstr
|
989ecf8899186ac3ac3a9692834142b1edcea3b9 | Szubie/Misc | /6.00.1x Files/Week 3/Recursion/Recursive function recurPower(base, exp).py | 743 | 4.28125 | 4 | # want to multiply base by itself exp times.Cannot use ** or loops.
def recurPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
#First, what is the base case? if exp = 0, then the answer is 1. (If exp = 1, the answer is base)
#Now need to think of a recursive step. Simplify the problem, and in a way that it reduces the value of exp each time.
# recurPower = base * base * base (exp times)
# recurPower = base * recurPower(base, exp -1)
if exp == 0:
return 1
elif exp ==1:
return base
#actually the above line is unecessary, as the below returns the correct value for exp=1
else:
return base * recurPower (base, exp-1) |
ffab14e253440e8e3d1c0979dcefa03fec336060 | alaktionov-hub/python_study | /OOP_5_at_class/vacancy.py | 2,243 | 3.953125 | 4 | #!/usr/bin/env python3
import datetime # date and time
import random # For random choose
import sqlite3 # db Stotred on data
#
# Db was need create and have Vacansy . And some programmers
#
# Get data from consloe
vacancy_title = input('Enter title of vacancy! ')
salary = int(input('Salary is '))
vacancy_main_skill = input('Main skill is ')
vacancy_technologies = input('Enter technologies ')
vacancy_recruiter = input('Recruiter is ')
# Db connect
conn = sqlite3.connect("data/all_worker.db")
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM vacancies")
# count number of rows and make id bigger on 1
vacancy_id = cursor.fetchone()[0]+1
# new vacancy created
vacancy_params = (vacancy_id, vacancy_title, salary,
vacancy_main_skill, vacancy_technologies, vacancy_recruiter)
cursor.execute(
"INSERT INTO vacancies VALUES (?,?,?,?,?,?,'null',1)", vacancy_params)
conn.commit()
print(f'Vacancy {vacancy_title} is in db now!')
# select all candidates from db with same main skill as for vacancy
candidates_db = cursor.execute(
"SELECT * FROM candidates WHERE main_skill = '{vac_skill}'".format(vac_skill=vacancy_main_skill))
# create list of candites to make random choice from one of them
candidates_list = []
for candidate in candidates_db:
candidates_list.append(candidate)
# select all programmers from db with same main skill as for vacancy
programmers_db = cursor.execute(
"SELECT * FROM programmers WHERE main_skill = '{prog_skill}'".format(prog_skill=vacancy_main_skill))
programmers_list = []
for programmer in programmers_db:
programmers_list.append(programmer)
# prepare params for adding to db
cand = random.choice(candidates_list)[2]
prog = random.choice(programmers_list)[2]
now = datetime.date.today()
tommorrow = datetime.date(now.year, now.month, now.day + 1)
cursor.execute("SELECT COUNT(*) FROM Interviews")
# count number of rows and make id bigger on 1
interview_id = cursor.fetchone()[0]+1
interview_params = (interview_id, vacancy_main_skill, prog,
vacancy_recruiter, cand, tommorrow)
cursor.execute(
"INSERT INTO interviews VALUES(?,?,?,?,?,?,null,null)", interview_params)
conn.commit()
print("Interview was added to db!")
conn.close()
|
977ddc247a544dcf42ff63a6b98eccfc302b0d34 | zupph/CP3-Supachai-Khaokaew | /Lecture105_Supachai_K.py | 855 | 3.53125 | 4 | class Vehicle:
licenseCode = ""
serialCode = ""
def turnOnAirCondition(self):
print("turn on : Air")
class Car(Vehicle):
def turnOnAir(self):
print("Car ", end="")
car = Vehicle()
car.turnOnAirCondition()
class Van(Vehicle):
def vanTurnOnAir(self):
print("Van ", end="")
van = Vehicle()
van.turnOnAirCondition()
class Pickup(Vehicle):
def pickupTurnOnAir(self):
print("Pickup ", end="")
pickup = Vehicle()
pickup.turnOnAirCondition()
class Estatecar(Vehicle):
def turnOnAir(self):
print("Estatecar ", end="")
estatecar = Vehicle()
estatecar.turnOnAirCondition()
car1 = Car()
car1.turnOnAir()
van1 = Van()
van1.vanTurnOnAir()
pickup1 = Pickup()
pickup1.pickupTurnOnAir()
estatecar1 = Estatecar()
estatecar1.turnOnAir()
|
76ac9791d7460faa638d0935033df2e73c56cf51 | TanakitInt/Python-Year1-Archive | /In Class/Week 7/[Decision] easterPrediction.py | 1,507 | 4 | 4 | """[Decision] easterPrediction"""
def main():
"""start"""
import calendar as cl
year_in = int(input())
#exception for invalid year
if year_in > 2099 or year_in < 1900:
print("Invalid input.")
else:
#stop for exception
a_num = year_in % 19
b_num = year_in % 4
c_num = year_in % 7
d_num = ((19 * a_num) + 24) % 30
e_num = ((2 * b_num) + (4 * c_num) + (6 * d_num) + 5) % 7
march22_constant_notleap = 22
#so february in leap year will be plus 1 -> (22+1)
march22_constant_leap = 23
if year_in in [1954, 1981, 2049, 2076]:
if cl.isleap(year_in) == True:
#minus 7 for delay
day = march22_constant_leap + d_num + e_num - 31 - 7
else:
#minus 7 for delay
day = march22_constant_notleap + d_num + e_num - 31 - 7
else:
if cl.isleap(year_in) == True:
day = march22_constant_leap + d_num + e_num - 31
else:
day = march22_constant_notleap + d_num + e_num - 31
#when easter day is not in April
if day <= 0:
if cl.isleap(year_in) == True:
day = abs(day + 23 + 7)
print("March "+str(day)+", "+str(year_in))
else:
day = abs(day + 22 + 7 + 2)
print("March "+str(day)+", "+str(year_in))
else:
print("April "+str(day)+", "+str(year_in))
main()
|
732919f3c3cd2ab449e64e408bb60f90530b6e51 | Geek-Tekina/Coding | /Python/DSA/Sorting/BubbleSort.py | 593 | 4.125 | 4 | def bubble_sort(data):
swap=False
for i in range(len(data)-1): #For first element in an array
print("First data:", i)
for j in range(len(data)-1-i): # For second element in an array
print("Second data:", j)
if data[j] > data [j+1]:
data[j], data[j+1] = data[j+1], data[j]
swap=True
print("Swap done")
if not(swap):
return "Already sorted"
print("pass compleated")
print("every pass result:",data)
return data
print(bubble_sort([9,5,3,0,8])) |
dbd9e4e3aef6201a94419346fd482118cb01a01b | attiquetecnologia/python_librarys | /automato/modulo.py | 4,276 | 3.59375 | 4 | #-*- coding: utf-8 -*-
class Estado:
def __init__(self,name,id,final=False,initial=False,x=0.0,y=0.0):
try:
self.id = int(id)
self.name = str(name)
self.final = final
self.initial = initial
self.x = x
self.y = y
except ValueError as v:
print 'Erro ID nao pode ser uma string:\nMessage %s ' % v.message
# retorna uma representacao da classe como um dicionario
def to_dict(self):
return dict(name=dict(id=id,initial=initial,final=final,x=x,y=y))
def equals(self,estado):
print 'self.name(%s) == estado.name(%s) or self.id(%s) == estado.id(%s):' % (self.name,estado.name,self.id,estado.id)
if self.name == estado.name or self.id == estado.id:
return True
return False
## end def
def to_string(self):
return "Estado{ id:%2s, name:%s ,final:%s, initial:%s }" % (self.id,self.name,self.final,self.initial)
### FIM ESTADO ###
# -----------------------------------------------------------------------------------------------------------------
## Classe transição
class Transicao:
def __init__(self,de,para,ler):
## garante que ira receber uma instância de estado
if isinstance(de,Estado) and isinstance(para,Estado) and type(ler) is str:
self.de = de
self.para = para
self.ler = ler
else:
print 'Objeto nao construido'
def to_string(self):
return "Transicao{ de:name=%s(id=%2s), para:name=%s(id=%2s), ler:%s }" % (self.de.name,self.de.id,self.para.name,self.para.id,self.ler)
### FIM TRANSICAO ###
# -----------------------------------------------------------------------------------------------------------------
## OPERACOES ##
from automato import Automato
## Complemento
def complemento(old):
automato = Automato()
## percorre a lista e altera estados finais em normais
for e in old.estados:
if e.final:
e.final = False
automato.add_estado(e)
else:
e.final = True
automato.add_estado(e)
## coloca as transições no novo automato
automato.transicoes = old.transicoes
return automato
## fim complemento
## Multiplicacao
def multiplicar(a1,a2):
# novo automato
new = Automato()
# Alfabeto é a combinação dos simbolos dos dois
new.alfabeto = set(a1.alfabeto+a2.alfabeto)
## concatenando os nomes
for e1 in a1.estados:
for e2 in a2.estados:
## novo estados
new_id = str(e1.id) + str(e2.id)
new_name = e1.name + e2.name
## se for estado inicial
if e1.initial and e2.initial:
new.add_estado(Estado(name=new_name,id=new_id,initial=True))
## se forem estados finais
#elif e1.final or e2.final:
# new.add_estado(Estado(name=new_name,id=new_id,final=True))
## se não é normal
else: new.add_estado(Estado(name=new_name,id=new_id))
## fim for
## Outro for para fazer as transições, irá combinar leituras com os estados
for a in new.alfabeto:
for e1 in a1.estados:
for e2 in a2.estados:
estado_de = new.get_estado(name=str(e1.name)+str(e2.name))
estado_para = None
p1 = a1.mover_name(e1.name,a)
p2 = a2.mover_name(e2.name,a)
## se encontrar busca o estado
if p1 and p2:
estado_para = new.get_estado(name=p1+p2)
## cria tansicao
new.add_transicao( Transicao(de=estado_de,para=estado_para,ler=a) )
return new
##
### FIM OPERACOES ###
# -----------------------------------------------------------------------------------------------------------------
## ARQUIVOS ##
## Salvando automato
def salvar(file_name,automato):
f = open(file_name,"w") # abre com parametro de escrita
f.write(automato.print_xml())
f.close()
return True
|
beaa7a0ed07753483b0f09e429a557e873266aa9 | sapka12/adventofcode2017 | /day09/program.py | 996 | 3.578125 | 4 | garbage_start = "<"
garbage_end = ">"
group_start = "{"
group_end = "}"
ignore = "!"
def task1(text):
result = ""
in_garbage = False
need_ignore = False
group_level = 0
counter = 0
for i in range(len(text)):
actual_char = text[i]
if in_garbage and actual_char != garbage_end and not need_ignore and actual_char != ignore:
result = result + actual_char
if need_ignore:
need_ignore = False
elif actual_char == ignore:
need_ignore = True
elif in_garbage and actual_char == garbage_end:
in_garbage = False
elif not in_garbage and actual_char == group_end:
counter = counter + group_level
group_level = group_level - 1
elif not in_garbage and actual_char == group_start:
group_level = group_level + 1
elif not in_garbage and actual_char == garbage_start:
in_garbage = True
return (len(result), counter)
|
007a60180c464d2879be299a6aa65252a71866f2 | TaroBubble/advent-of-code | /day6/puzzle1.py | 391 | 3.5 | 4 | textFile = open('day6\input.txt', 'r')
def solution(textFile):
res = 0
solutionSet = set()
for line in textFile:
line = line.strip()
if line:
for char in line:
solutionSet.add(char)
if not line:
res += len(solutionSet)
solutionSet.clear()
return res + len(solutionSet)
print(solution(textFile)) |
c3bd44dad9e617279b263edf5cf8d1e19b34c29b | Chaenini/Programing-Python- | /example.py | 359 | 3.734375 | 4 | def min_max(*args):
min_value = args[0]
max_value = args[0]
for a in args:
if min_value > a :
min_value = a
if max_value < a :
max_value = a
return min_value,max_value
min,max= min_max(52.-3,23,89,-21)
print("최솟값 : ",min,"최댓값 : ",max) |
0d82a6a4f90b6464a02543093185e371fad3e22f | StoneRiverPRG/Python_Study | /配列.py | 645 | 4.34375 | 4 | # 配列 list の基礎
print("配列!")
# 配列の宣言(空の配列、宣言と同時に初期化)
list = []
list2 = [1, 1, 2, 3, 5]
# 要素の追加
print(list2)
list2 = list2 + [8, 13, 21]
print("要素追加後")
print(list2)
# 要素の追加(別の方法)
list2 = [10, 20, 30]
list2.append(40)
print(list2)
list2.insert(2, 21)
print(list2)
list2.insert(0, 0)
print(list2)
# 要素数の取得( len()関数)
print(len(list2))
# 要素の削除(del文, popメソッド)
list = [1, 2, 3, 4, 5]
print(list)
del list[3]
print(list)
list = [1, 2, 3, 4, 5]
print(list)
list.pop(3)
print(list)
|
3d9ac2a8d17859a2517bbf14a46d51b0da4b116b | TheRealJenius/TheForge | /TK.py | 5,009 | 4.28125 | 4 | # And so it begins
"""
Things to do:
- Define Functions required
- Enter input
- Display input as output
- Delete input
- Copy input
- Paste input
- Create a GUI
- TKinter seems to be the default a good place to start
- Create Menus
- File
- Edit
- About
- Time and date package
- Save as a file that can be accessed
- Save as a thumbnail
"""
# https://www.instructables.com/id/Create-a-Simple-Python-Text-Editor/
# https://www.tutorialspoint.com/develop-notepad-using-tkinter-in-python
# https://www.geeksforgeeks.org/make-notepad-using-tkinter/
'''
frame1 = tk.Frame()
frame2 = tk.Frame()
frame1.pack(side='top') # side='top' is default
frame2.pack(side='top')
# these widgets go into frame1
label = tk.Label(frame1, text="Enter your name:")
entry = tk.Entry(frame1)
label.pack(side='top')
entry.pack(side='top')
# these widgets go into frame2
btn1 = tk.Button(frame2, text='button1')
btn2 = tk.Button(frame2, text='button2')
btn3 = tk.Button(frame2, text='button3')
btn1.pack(side='left')
btn2.pack(side='left')
btn3.pack(side='left')
'''
'''
import tkinter from tkinter.constants import *
tk = tkinter.Tk()
frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
frame.pack(fill=BOTH,expand=1)
label = tkinter.Label(frame, text="Hello, World")
label.pack(fill=X, expand=1)
button = tkinter.Button(frame,text="Exit",command=tk.destroy)
button.pack(side=BOTTOM)
tk.mainloop()
'''
#Tcl = tool command language
#Tk = Tool Kit
#text.grid() #grid doesn't populate without ()
#############################################################################################################################
# Coding begins
# from Tkinter import *
# '*' Imports everything, everything is a widget in tkinter
# root = Tk() # Creates the origin 'window' widget or the root widget, this has to be the first thing. - This is the label widget.
'''
TextArea=Text(root) #TextArea displays text
MenuBar = Menu(root)
MenuFile = Menu(root, tearoff = 0) #tearoff allows the menu to open a seperate window within the main window to display the attributes defined
MenuEdit = Menu(root, tearoff = 0)
'''
import tkinter as tk #Need to import tkinter as tk - so it references the functions such as Frame, etc.
LargeFONT= ("Verdana", 12)
class Notes(tk.Tk): #Need to set it as a calss so the functions can all be called
'''
the items in the brackets allow you to inherit attributes from another class , a class can be created without it
'''
def __init__(self,*args, **kwargs): #sets the code that loads first, self is a parameter that is normally implied and can be changed if required, it's good practice to leave it as self
# *args = arguments = variables
# **kwargs = keyword argumemts = e.g. dictionaires
# you could essentially write the above as (self,*,**)
tk.Tk.__init__(self,*args,**kwargs)
container = tk.Frame(self) #frame defines the window
# pack esentially just places an element on the window without any direction or organisation
# grid is the opposite and allow you to decide where items go
container.pack(side="top", fill = "both", expand = True)
# side is a generic direction
# fill will fill in the space we have set for the pack
# expand will check if there is anymore whitespace on the window, to allow the container to expand within the space
container.grid_rowconfigure(0, weight=1) #0 sets the minimu size, weight defines the priority it increments by
container.grid_columnconfigure(0, weight=1)
self.frames = {} #empty dictionary
frame = StartPage(container, self)
self.frames[StartPage] = frame
frame.grid(row=0, column = 0, sticky = "nsew") #North South East West = nsew, it defines alignment - i.e. ew will strecth it in the centre
self.show_frame(StartPage)
def show_frame(self,cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self,text = "Start Page", font = LargeFONT)
label.pack(pady=10, padx=10)
#when you call upon a class it is going to return an object and we'll assign that object to a variable and call the variable to carry out functions
Application = Notes()
Application.mainloop()
# creating a quit button instance below - for testing
quitButton = Button(self, text = "Quit", command = self.client_exit) # Button is part of tkinter, client_exit hasn't been defined yet
quitButton.place(x=0, y=0) # adds the button to the window; It starts from the upper left hand side
# at this point it is a good idea to start noting down the size of the button, he geometry pointed out below
def client_exit(self): # defining the quit function doesn't neccesarily need to happen as it is just one line, but has been added here as the prgoram grows
exit() # built in function in python
|
65320b8bfb1f29f4c3c6d860193709317b83872d | tenten0113/python_practice | /8/super.py | 731 | 3.90625 | 4 | class Person:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def show(self):
print(f'私の名前は{self.lastname}{self.firstname}です! ')
# Personを継承したBusinessPersonクラスを定義
class BusinessPerson(Person):
def work(self):
print(f'{self.lastname}{self.firstname}は働いています。')
class HetareBusinessPerson(BusinessPerson):
def work(self):
super().work()
print('ただし、ボチボチと...')
if __name__ == '__main__':
hbp = HetareBusinessPerson('太郎', '山田')
hbp.work()
# 結果:山田太郎は働いています。
# ただし、ボチボチと...
|
52e37ca9e0a3f428fed1046a2fc4df3001d7b8af | jiin995/Ai | /plot | 142 | 3.59375 | 4 | #!/usr/bin/env python
import matplotlib.pyplot as plt
plt.plot([1,5,3,4],[0,2,4,6])
plt.ylabel('some numbers')
plt.show()
print 'hello'
ciao
|
719ddc3049716a8e761bfd4d433ea41d97c8f085 | AaronYang2333/CSCI_570 | /records/07-21/link.py | 1,064 | 3.71875 | 4 | __author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '7/22/2020 10:10 PM'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def initList(self, data):
# 创建头结点
self.head = ListNode(data[0])
p = self.head
# 逐个为 data 内的数据创建结点, 建立链表
for i in data[1:]:
node = ListNode(i)
p.next = node
p = p.next
return self.head
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None: return None
stack = []
while head.next is not None:
stack.append(head.val)
head = head.next
stack.append(head.val)
res = ListNode(stack.pop())
p = res
while len(stack) > 0:
temp = ListNode(stack.pop())
p.next = temp
p = p.next
return res
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5]
link = ListNode(-1).initList(arr)
Solution().reverseList(link)
|
f7e4932acafd4b432503fbe5c9e8ba913d44e316 | AbuSheikh/Python-Course | /Week 1/Practise1-C.py | 805 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
def CToF():
celsius = float (input ("Enter the temperatures degree in celsius "))
fahrenheit = (celsius * 1.8) + 32
print(f"{celsius} degree Celsius is equal to {fahrenheit} degree Fahrenheit")
def FToC():
fahrenheit = float (input ("Enter the temperatures degree in fahrenheit "))
celsius = (fahrenheit - 32) / 1.8
print(f"{fahrenheit} degree fahrenheit is equal to {celsius } degree celsius")
def enter():
x= int (input ("If you want to translate for celsius please enter 1 and If you want to translate for fahrenheit please enter 0 : "))
if x==0 :
CToF()
elif x==1 :
FToC()
else:
x= int (input(" please enter valid number "))
enter()
enter()
|
c8b82b199e34fb8a1247f1b078637f2991aee66c | Arina-prog/Python_homeworks | /homework 7/task_7_7.py | 597 | 4.4375 | 4 | # Create several functions store them inside variables for handling collection of
# movie names using lambdas
# Создайте несколько функций,
# сохраните их внутри переменных для обработки коллекции имен фильмов с
# использованием лямбда-выражений
movies = ["Farsazh 1", "Farsazh 2", "Farsazh 3", "Farsazh 4"]
movies1 = ["Dom 1", "Golodnye igri", "Apocalipsis", "Farsazh 4"]
is_the = lambda name: name.lower()[:3] == "Far"
movie_name = list(filter(is_the, movies))
print(movie_name)
|
de3fa8c1a77c36cfb511948cfc4438f26ec683e5 | self-study-squad/Python-examples | /Data Structure/Exercise-10.py | 356 | 3.703125 | 4 | # Write a Python program to group a sequence of key-value pairs into a dictionary of lists.
# Expected output:
# [('v', [1, 3]), ('vi', [2, 4]), ('vii', [1])]
from collections import defaultdict
class_roll = [('v',1),('vi',2),('v', 3), ('vi', 4), ('vii', 1)]
d = defaultdict(list)
for k, v in class_roll:
d[k].append(v)
print(sorted(d.items())) |
10dc434bae574e490d7821aa5f6680fb540aa4f3 | gracesin/hearmecode | /demos/lesson1_demo_test_ssn_basic.py | 1,607 | 4.1875 | 4 | # -*- coding: utf-8 -*-
#Test to see if SSN is issued by SSA
#Criteria at http://policy.ssa.gov/poms.nsf/lnx/0110201035
import re
#enter SSN to test
#test_ssn = raw_input("enter an SSN to test\n")
test_ssn = "123-45-6789"
#Remove dashes from SSN and get rid of spaces at beginning and end
test_ssn = test_ssn.replace("-","").strip()
print "Here it is with no dashes and spaces removed: {0}\n".format(test_ssn)
if len(test_ssn) == 9 and test_ssn.isdigit():#check for correct length and digits only
#Checking for impossible SSNs
#The first three digits (former area number) as "000," "666,” or in the 900 series
if test_ssn[:3] == "000" or test_ssn[:3] == "666" or test_ssn[0] == "9":
print "SSN starts with an impossible sequence: {0}".format(test_ssn[:3])
#The second group of two digits (former group number) as "00."
elif test_ssn[3:5] == "00":
print "SSN has '00' in the fourth and fifth digits."
#The third group of four digits (former serial number) as "0000."
elif test_ssn[5:] == "0000":
print "SSN ends with '0000.'"
else:
print "SSN is not impossible!"
else:#if ssn is not 9 digits, find out what's wrong
if re.search(r"[A-Za-z]", test_ssn):#look for alpha characters in SSN using regular expressions
print "Contains alpha characters: {0}".format(test_ssn)
elif len(test_ssn) != 9:#check length
print "Wrong length. Length of {1} is {0}".format(len(test_ssn), test_ssn)
else:#everything else that can go wrong!
print "Something else weird. I dunno. Here's the SSN: {0}".format(test_ssn)
#%%
|
32060aafa97c0649a3f6879935d31a7c4eb300b0 | jocelinoFG017/IntroducaoAoPython | /01-Cursos/GeekUniversity/Seção10-Expressões_Lambdas_e_Funções_Integradas/zip.py | 1,338 | 4.625 | 5 | """
Zip -> Cria um iteravel (Zip Object) que agrega elemento de cada um dos iteráveis
passados como entrada em pares
lista1 = [1, 2, 3]
lista2 = [4, 5, 6]
zip1 = zip(lista1, lista2)
print(zip1)
print(type(zip))
# SEMPRE podemos gerar uma lista, tupla ou dicionario
print(list(zip1))
zip1 = zip(lista1, lista2)
print(tuple(zip1))
zip1 = zip(lista1, lista2)
print(set(zip1))
zip1 = zip(lista1, lista2)
print(dict(zip1))
# o zip() utiliza como parametro o menor tamanho em iteravel. Isso significa que se estiver trabalhando
# com iteraveis de tamanhos diferentes, irá parar quando os elementos do menor iteravel acavar
lista3 = [7, 8, 9, 10, 11]
zip1 = zip(lista1, lista2, lista3)
print(list(zip1))
# Podemos utilizar diferentes iteraveis com zip
tupla = 1, 2, 3, 4, 5,
lista = [6, 7, 8, 9, 10]
dicionario = {'a': 11, 'b': 12, 'c': 13, 'd': 14, 'e': 15}
zt = zip(tupla, lista, dicionario.values())
print(list(zt))
# Lista de tuplas
dados = [(1, 2), (3, 4), (5, 6), (7, 8)]
print(list(zip(*dados)))
"""
# Exemplos mais complexos
prova1 = [80, 91, 78]
prova2 = [98, 89, 53]
alunos = ['maria', 'pedra', 'carla']
final = {dado[0]: max(dado[1], dado[2]) for dado in zip(alunos, prova1, prova2)}
print(final)
# podemos utilizar o map()
final = zip(alunos, map(lambda nota: max(nota), zip(prova1, prova2)))
print(dict(final))
|
f2ee24ba4eb6f05a04bae1af5456538da306e074 | uniqueimaginate/Coding | /Coding Test/bfs.py | 423 | 3.75 | 4 | graph = {
1: [2, 3, 4],
2: [5],
3: [5],
4: [],
5: [6, 7],
6: [],
7: [3]
}
def bfs(v):
discovered = [v]
queue = [v]
while queue:
curr = queue.pop(0)
for w in graph[curr]:
if w not in discovered:
queue.append(w)
discovered.append(w)
return discovered
print(bfs(1))
# [1, 2, 3, 4, 5, 6, 7] |
f2f8d54eea0c9af7cd4d3b67e4571d912a25bd5a | Gai-shijimi/investment-analysis | /analysis/CS/cs_analysis.py | 2,094 | 3.703125 | 4 | # キャッシュフローのパターンだけ
class CashFlow:
def __init__(self, cf_business_activities, cf_investing_activities, cf_financing_activities):
self.cf_business_activities = cf_business_activities # 営業活動によるキャッシュフロー
self.cf_investing_activities = cf_investing_activities # 投資活動によるキャッシュフロー
self.cf_financing_activities = cf_financing_activities # 財務活動によるキャッシュフロー
def pattern(self):
if self.cf_business_activities < 0 and self.cf_investing_activities < 0 and self.cf_financing_activities > 0:
print("新興企業です")
elif self.cf_business_activities > 0 and self.cf_investing_activities < 0 and self.cf_financing_activities > 0:
print("発展企業です")
elif self.cf_business_activities > 0 and self.cf_investing_activities < 0 and self.cf_financing_activities < 0:
print("発展企業です")
elif self.cf_business_activities > 0 and self.cf_investing_activities > 0 and self.cf_financing_activities < 0:
print("熟成期にある企業です")
elif self.cf_business_activities < 0 and self.cf_investing_activities > 0 and self.cf_financing_activities > 0:
print("衰退期にある企業です")
elif self.cf_business_activities < 0 and self.cf_investing_activities < 0 and self.cf_financing_activities < 0:
print("衰退期にある企業です")
else:
print("どこにも当てはまりません")
response1 = input("営業活動によるキャッシュフローの合計額を入れてください:")
response1 = int(response1)
response2 = input("投資活動によるキャッシュフローの合計額を入れてください:")
response2 = int(response2)
response3 = input("財務活動によるキャッシュフローの合計額を入れてください:")
response3 = int(response3)
cash_flow = CashFlow(response1, response2, response3)
print(cash_flow.pattern())c
|
07e891f9412e999a2c1be25e17257b2a6a173b35 | SW-418/EulerProject | /src/Python/SumOfEvenFibonacci.py | 384 | 3.5625 | 4 |
first = 1
second = 2
lessThan4Mil = True
sumOfEvenValues = 2
while lessThan4Mil:
new = first + second
print(f'First: {first} - Second: {second} - New: {new}')
if new > 4000000:
lessThan4Mil = False
elif new % 2 == 0:
sumOfEvenValues += new
print(f'Value is even: {new}')
first = second
second = new
print(f'Sum: {sumOfEvenValues}') |
0a76f8dea5a00623d6f1ae14ad73378c509eaf14 | zpfarmer/assignments | /Assignments/afs-210/Week 3/heapqueue.py | 529 | 4.4375 | 4 | #google heapq for more information and a list of what all commands you can use with it
import heapq as hq
#original list
list = [25, 35, 22, 85, 14, 65, 75, 22, 58]
print("Original list:")
print(list)
#using heapq as hq
#nlargest command will return with however many items from the list the user wants
#nsmallest is the opposite of this command, will return that smallest elements from a list
largest_3 = hq.nlargest(3, list)
#printing the 3 largest that I just created above
print("\nThe three largest numbers are", largest_3) |
51ce0092ea6ecfed449218507bcd27820b170657 | Kew4sK/CSC-132-Project | /button tester 3.py | 1,895 | 3.890625 | 4 | #####################################################
#Team 3: Pete Mace, Conan Howard, Justin Turnbull
# Date: 5/9/17
# Purpose: The system that the teams will come enter
# the code they get from the puzzle into
#####################################################
#imports libraries neccesary
import RPi.GPIO as GPIO
from time import sleep
import pygame
#Set switches and leds to pins from left to right
switches = [18, 23, 12, 21]
leds = [5, 6, 19, 26]
#set
GPIO.setmode(GPIO.BCM)
#set inpiuts and outputs
GPIO.setup(switches, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(leds, GPIO.OUT)
#These variables form the toggle mode of each switch
a = False
b = False
c = False
d = False
#Keep the lights off from the beginning
GPIO.output(leds,False)
try:
while (True):
#sets each button as an input state
input_state1 = GPIO.input(18)
input_state2 = GPIO.input(23)
input_state3 = GPIO.input(12)
input_state4 = GPIO.input(21)
#if the button is pressed the variable becomes true
#if the button is pressed or the variable is True, the next button becomes useful
#If a button is messed up in the sequence then should quit
if (input_state1 | a):
a = True
if (input_state2 | b):
b = True
if (input_state3 | c):
c = True
if (input_state4 | d):
d = True
if (d == True):
GPIO.output(leds, True)
else:
print "messed up at d"
else:
print"messed up at c"
else:
print "messed up at b"
else:
print "messed up at a"
except:
GPIO.cleanup()
|
78c009cef3b5f9d3f92baf45de82b47eabee3a59 | bohanxyz/amath584 | /temp.py | 1,301 | 3.5 | 4 | # L-14 MCS 507 Fri 27 Sep 2013 : power_method.py
"""
The script is a very simple illustration using numpy
of the power method to compute an approximation for
the largest eigenvalue of a complex matrix.
"""
import numpy as np
def power_method(mat, start, maxit):
"""
Does maxit iterations of the power method
on the matrix mat starting at start.
Returns an approximation of the largest
eigenvector of the matrix mat.
"""
result = start
for i in range(maxit):
result = mat @ result
result = result / np.linalg.norm(result)
return result
def check(mat, otp):
"""
Compares the output otp of the power
method with the largest eigenvalue
of the matrix mat.
"""
prd = mat @ otp
eigval = prd[0]/otp[0]
print('computed eigenvalue :' , eigval)
[eigs, vecs] = np.linalg.eig(mat)
print(' largest eigenvalue :', max(eigs))
def main():
"""
Prompts the user for a dimension
and the number of iterations.
"""
print('Running the power method...')
dim = 10
rnd = np.random.randn(dim, dim) \
+ np.random.randn(dim, dim)*1j
nbs = np.random.normal(0, 1, (dim, 1)) \
+ np.random.normal(0, 1, (dim, 1))*1j
eigmax = power_method(rnd, nbs, 1000)
check(rnd, eigmax)
main()
|
f389ca6d73c4a65b594702baabd17caabb33e132 | bravicsakos/Adatkezeles | /RSA.py | 3,541 | 3.765625 | 4 | import random
def gcd(a, b):
"""
Euklideszi algoritmus
"""
while b != 0:
a, b = b, a % b
return a
def kibov_euklidesz(phi, a):
"""
Kibővített Euklideszi alg.
"""
base_a, base_phi = a, phi
x0, x1, y0, y1, s = 1, 0, 0, 1, 1
while a != 0:
# print("Start of Cycle!\n")
r, q = phi % a, int(phi / a)
# print(f"r: {r}; q: {q}")
phi, a = a, r
# print(f"phi: {phi}; a: {a}")
x, y = x1, y1
# print(f"x: {x}; y: {y}")
x1, y1 = q * x1 + x0, q * y1 + y0
# print(f"x1: {x1}; y1: {y1}")
x0, y0 = x, y
# print(f"x0: {x0}; y0: {y0}")
s = -s
# print(f"s: {s}")
# print("\n End of Cycle!")
x, y = s * x0, -y0
x = x % base_a
y = y % base_phi
#print(f"\n final - x: {x}; y: {y}")
return x, y
def is_prime_mr(n):
"""
Miller-Rabin primality test.
A return value of False means n is certainly not prime. A return value of
True means n is very likely a prime.
"""
if n != int(n):
return False
n = int(n)
if n == 0 or n == 1 or n == 4 or n == 6 or n == 8 or n == 9:
return False
if n == 2 or n == 3 or n == 5 or n == 7:
return True
s = 0
d = n - 1
while d % 2 == 0:
d = int(d/2)
s += 1
assert (2 ** s * d == n - 1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
return True
for i in range(8): # number of trials
a = random.randrange(2, n)
if trial_composite(a):
return False
return True
def chinese_remainder(d, c):
m1, m2 = q, p
x1, y1 = kibov_euklidesz(q, p)
x2, y2 = kibov_euklidesz(p, q)
c1 = pow((c % p), (d % (p-1)), p)
c2 = pow((c % q), (d % (q-1)), q)
return (c1*x1*m1 + c2*x2*m2) % (p * q)
def generate_keypair(p, q):
if not (is_prime_mr(p) and is_prime_mr(q)):
raise ValueError('Both numbers must be prime.')
elif p == q:
raise ValueError('p and q cannot be equal')
n = p * q
phi = (p - 1) * (q - 1)
e = random.randrange(1, phi)
g = gcd(e, phi)
while g != 1:
e = random.randrange(1, phi)
g = gcd(e, phi)
x, y = kibov_euklidesz(e, phi)
d = x % phi
return (e, n), (d, n)
def encrypt(pk, plaintext):
key, n = pk
cipher = [pow(ord(char), key, n) for char in plaintext]
return cipher
def decrypt(pk, ciphertext):
global p, q
key, n = pk
plain = [chr(chinese_remainder(key, char)) for char in ciphertext]
return ''.join(plain)
if __name__ == '__main__':
print("RSA Encrypter/ Decrypter")
p = int(input("Enter a prime number (17, 19, 23, etc): "))
q = int(input("Enter another prime number (Not one you entered above): "))
print("Generating your public/private keypairs now . . .")
public, private = generate_keypair(p, q)
print("Your public key is ", public, " and your private key is ", private)
message = input("Enter a message to encrypt: ")
encrypted_msg = encrypt(private, message)
print("Your encrypted message is:")
print(''.join(map(lambda x: str(x), encrypted_msg)))
print("Decrypting message. . .")
print("Your message is:")
print(decrypt(public, encrypted_msg))
|
93fdfd151b369d0486e8626068d808fbdf056c13 | udaykkumar/PEular | /Python/problem-24.py | 1,106 | 4.03125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
'''
import time
import sys
import itertools
def permute(s, i, n):
if i == n:
print s
for j in range(i,n):
s[i],s[j] = s[j],s[i]
permute(s, i+1, n)
s[i],s[j] = s[j],s[i]
#This is really a cheat and not definately not how this is supposed to be
# I'll have to revisit this TODO
def getNthLexicographicPermutation(s,n):
permutations = list(itertools.permutations(s));
return ''.join(permutations[n-1])
def Solve(s,n):
return getNthLexicographicPermutation(s,n)
start_time = time.time()
print Solve(list("0123456789"),1000000)
print("--- %s seconds ---" % (time.time() - start_time))
|
35b49e0888953d07d3e1d5ff85568a36de4a6e4e | jezhang2014/2code | /leetcode/ExcelSheetColumnTitle/solution.py | 266 | 3.703125 | 4 | # -*- coding:utf-8 -*-
ass Solution:
# @return a string
def convertToTitle(self, num):
l = []
while num > 0:
c = chr((num-1) % 26 + ord('A'))
l.append(c)
num = (num-1) // 26
return ''.join(l[::-1])
|
6c93c264e6de4d08d5efeef33d023fc59ea4199d | minibrary/Python_Study | /Input_Output/2.py | 225 | 3.546875 | 4 | in_str = input("아이디를 입력해주세요.\n")
real_josh = "11"
real_k8805 = "ab"
if real_josh == in_str:
print("Welcome, josh!")
elif real_k8805 == in_str:
print("Welcome, k8805!")
else:
print("Get Out!")
|
7a0439d9e464f4ab4ce0195f7ba26dac6c75146c | NanLieu/COM404 | /Practice Assessment/AE1 Review - TCA 2/5-Nesting/bot.py | 961 | 4.03125 | 4 | # Setting value of variable for 'health' at 100
health = 100
# Print statement stating amount of 'health' and the code is starting
print("You health is",health,"%. Escape is in progress")
# For loop which loops 5 time stated in the range
for count in range(0, 5, 1):
print("...Oh dear, who is that?")
# Awaits user's input to put into 'who' variable
who = input()
# if function to determine which code is run based on the user's input
if (who == "Smiler's Bot"):
# negative adjustment to 'health' value
health = health - 20
print("Time to jam out of here!")
elif (who == "Hacker"):
# positive adjustment to 'health' value
health = health + 20
print("Yay! Better follow this one!")
else:
# Prints statement if user's input doesn't matches anything
print("Phew, just another emoji!")
# Prints final statement with remaining 'health' value
print("Escape! Health is",health,"%.") |
01bf0770314852f7fc807161d1af0bffc2e81a01 | RawToast/JapaneseStudy | /anki/plugins/morphman2/morph/matchingLib.py | 3,555 | 3.5 | 4 | class Edge():
def __init__( self, s, t, w=0 ):
self.s, self.t, self.w = s, t, w
def __repr__( self ): return '%s -> %s = %d' % ( self.s, self.t, self.w )
class Graph():
# Creation
def __init__( self ):
self.adj, self.flow = {}, {}
self.S, self.T = '#', '&' #XXX: must not be in V
def mkMatch( self, ps ):
A = list(set( [ a for (a,b) in ps ] ))
B = list(set( [ b for (a,b) in ps ] ))
map( self.addVertex, [self.S,self.T] )
map( self.addVertex, A )
map( self.addVertex, B )
for a in A:
self.addEdge( self.S, a, 1 )
for b in B:
self.addEdge( b, self.T, 1 )
for (a,b) in ps:
self.addEdge( a, b, 1 )
def addVertex( self, v ): self.adj[ v ] = []
def addEdge( self, s, t, w=0 ):
e = Edge( s, t, w )
re = Edge( t, s, 0 )
e.rev = re
re.rev = e
self.adj[ s ].append( e )
self.adj[ t ].append( re )
self.flow[ e ] = 0
self.flow[ re ] = 0
# Analysis
def complexity( self ):
return 'Complexity: |V|=%d, |E|=%d' % ( len(self.adj), len(self.flow)/2 )
# Comp
def getNeighborEdges( self, v ): return self.adj[ v ]
def getMatchPairing( self ): return [ (e.s,e.t) for (e,f) in self.flow.iteritems() if f == 1 and e.s != self.S and e.t != self.T ]
# Calculate shortest path
def bfsSP( self, s, t ):
self.bfsOuter, self.bfsInner = 0, 0
queue = [ s ] # :: [ Node ]
paths = { s:[] } # :: Map Node -> [ Edge ]
while queue:
self.bfsOuter += 1
u = queue.pop(0)
for e in self.getNeighborEdges( u ):
self.bfsInner += 1
if e.w - self.flow[ e ] > 0 and e.t not in paths:
paths[ e.t ] = paths[ u ] + [ e ]
if e.t == t: return paths[ e.t ]
queue.append( e.t )
return None
# Find max flow. molests self.flow
def edmondsKarp( self, s, t ):
while True:
path = self.bfsSP( s, t )
if not path: break
maxCap = min( e.w - self.flow[ e ] for e in path )
for e in path:
self.flow[ e ] += maxCap
self.flow[ e.rev ] -= maxCap
return sum( self.flow[ e ] for e in self.getNeighborEdges( s ) )
def doMatch( self, debugF=None ):
self.edmondsKarp( self.S, self.T )
return self.getMatchPairing()
def chunksOf( n, xs ):
def f( xs ):
a,b = xs[:n], xs[n:]
if not a: return []
else: return [a] + f( b )
return f( xs )
def test():
print '-- Trivial abcd x 123 problem --'
A = 'abcd'
B = '123'
pairsStr = 'a2a3b1b2b3c1c2'
pairs = [ (x[0], x[1]) for x in chunksOf( 2, pairsStr ) ]
g = Graph()
g.mkMatch( pairs )
print g.complexity()
ms = g.doMatch()
print 'Flow:', len(ms)
print 'Matching:', ms
def randTest():
print '-- Random test'
import string, random
A = range(26*2)
B = string.ascii_letters
N = lambda n=len(B): random.randint(0,n)
pairs = []
for a in A:
for i in range( N() ):
b = random.choice( B )
if (a,b) not in pairs: pairs.append( (a,b) )
g = Graph()
g.mkMatch( pairs )
print '|A|=%d, |B|=%d, |E|=%d' % ( len(A), len(B), len(pairs) )
print g.complexity()
ms = g.doMatch()
print 'Flow:', len(ms)
print 'Matching:', ms
if __name__ == '__main__':
test()
randTest()
|
ff5c76e0317588f017a5ca40d6443887369b3ff2 | ng3rdstmadgke/codekata_python | /20_1_tree/tree.py | 376 | 4.15625 | 4 | #!/usr/bin/env python
from turtle import Turtle
def tree(n, t):
if n == 1:
t.forward(10*n)
t.back(10*n)
return n
else:
t.forward(10*n)
t.left(15)
tree(n-1, t)
t.right(30)
tree(n-1, t)
t.left(15)
t.back(10*n)
return n
if __name__ == "__main__":
t = Turtle()
tree(3, t)
|
2da61b6dfdb6dd034f922a41ae826e86c0af9b3f | shyam96s/python1 | /largest3f.py | 348 | 4.28125 | 4 | def largest(n1,n2,n3):
if(n1>n2 and n1>n3):
print(str (n1)+" is the largest")
elif(n2>n1 and n2>n3 ):
print(str (n2)+" is the largest")
else:
print(str (n3)+" is the largest")
x=int(input("Enter 1st number"))
y=int(input("Enter 2nd number"))
z=int(input("Enter 3rd number"))
largest(x,y,z)
|
9e89d37de9e86db57cf153919849e14ce7462d22 | santoshdkolur/didactic-lamp | /antiMatrix.py | 2,123 | 3.984375 | 4 | #HARD
'''
Given a matix, sort the elements and rotatle the layers of the matrix in anti-clockwise manner by one unit.
Note: It works for all square matrices
Input:
n - size of the matrix
2*2 elements
Output:
Sorted matrix
AntiClock wise rotated matrix
Example:
Input:
Enter the size of the matrix: 4
Enter the elements: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Output:
After sorting and Before rotation:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
After rotation:
2 3 4 8
1 7 11 12
5 6 10 16
9 13 14 15
'''
#AUTHOR : SANTOSH D KOLUR
from math import floor
import time,os
def matrix(n,mat):
if len(mat) != n**2:
print("Invalid matrix")
exit()
mat.sort()
m=[]
for i in range(0,len(mat),n):
m.append(mat[i:i+n])
mat=m
print("After sorting and Before rotation: ")
for ele in mat:
for e in ele:
print(e,end='\t')
print()
del m
if(n%2!=0):
lim=floor((0+n-1)/2)
else:
lim=floor((0+n-1)/2)+1
#while(True): #Uncomment and indent the lines till the last line to see it move continously (uncommment the last two lines as well)
for i in range(lim): #Traverses layer by layer. Imagine an onion XD
temp=mat[i][i]
for j in range(i+1,n-i): #Top Layer
mat[i][j-1]=mat[i][j]
j=n-i-1
k=i
for k in range(i+1,n-i): #Right Layer
mat[k-1][j]=mat[k][j]
for k in range(j-1,i-1,-1): #Bottom Layer
mat[j][k+1]=mat[j][k]
for j in range(n-i-2,i-1,-1): #Left Layer
mat[j+1][i]=mat[j][i]
mat[i+1][i]=temp
print('\n\nAfter rotation :')
for ele in mat:
for e in ele:
print(e,end='\t')
print()
#time.sleep(0.5)
#os.system('cls')
if __name__ == "__main__":
n=int(input("Enter the size of the matrix:"))
mat=[int(ele) for ele in input("Enter the elements: ").split(' ')]
matrix(n,mat)
|
129792ac36679095406331e5c88f2d061c355ddc | monmarko/higher-lower-game-followers | /main.py | 1,771 | 3.75 | 4 | import random
from art import logo
from art import vs
from game_data import data
def get_random_account():
return random.choice(data)
def format_data(account):
name = account["name"]
description = account["description"]
country = account["country"]
# print(f'{name}: {account["follower_count"]}')
return f"{name}, a {description}, from {country}"
def get_followers_amount(account):
return account["follower_count"]
def follower_checking(followers_a_amount, followers_b_amount, user_guess):
"""
Checks followers against user's guess and returns
True if they got it right. Or False if they got it wrong.
"""
if followers_a_amount > followers_b_amount:
return user_guess == "a"
else:
return user_guess == "b"
def game():
should_continue = True
score = 0
first_person = get_random_account()
while should_continue:
print(logo)
second_person = get_random_account()
if first_person == second_person:
second_person = get_random_account()
followers_a = get_followers_amount(first_person)
followers_b = get_followers_amount(second_person)
print(format_data(first_person))
print(vs)
print(format_data(second_person))
user_guess = input("\nWho has more followers? Type A or B: ").lower()
if follower_checking(followers_a, followers_b, user_guess):
score += 1
print(f"That's right, your score is {score}")
if followers_b > followers_a:
first_person = second_person
should_continue = True
# clear()
else:
print(f"Game over, your score is: {score}")
should_continue = False
game()
|
2f04e6419dbdf36ec9075c2fbaa02b9e4ed85528 | mohitleo9/interviewPractice | /Stacks_And_Queues/Stack.py | 1,063 | 3.578125 | 4 | import os.path
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from Linked_Lists.LinkedLists import LinkedList, Node
class Stack:
def push(self, node):
if not node:
return
if not self.top:
self.top = node
return
node.next = self.top
self.top = node
return
def pop(self):
if not self.top:
return
tmp = self.top
self.top = self.top.next
return tmp
def peek(self):
return self.top.data
def __init__(self):
self.top = None
def __str__(self):
if not self.top:
return "None"
tmp = self.top
strin = ''
while tmp.next:
strin += str(tmp.data) + '->'
tmp = tmp.next
strin += str(tmp.data) + '->'
strin += 'None'
return strin
def main():
s = Stack()
s.push(Node(2))
s.push(Node(3))
s.pop()
s.pop()
print s
if __name__ == '__main__':
main()
|
bb7b80df9015b8ffcb1de6f284cfc8de93df0bf4 | keerthana0110/PythonBasics-xplore- | /classexample.py | 193 | 3.6875 | 4 | class Dog:
def __init__(self,name,age):
self.name=name
self.age=age
def bark(self):
print("Bow bow")
pet=Dog("Jade",2)
pet.bark()
print(pet.name)
print(pet.age)
|
a6b13ea92f0435b3fbc474f76f2dac3b44b3a78e | BFRamZ/IT505-Final-Project | /Database.py | 1,118 | 3.609375 | 4 | import sqlite3
from sqlite3 import Error
class Database:
def __init__(self, datfile):
self.connection = self.create_connection(datfile)
pass
def create_connection(self, path):
connection = None
try:
connection = sqlite3.connect(path)
except Error as e:
print(f"The error '{e}' occured")
return connection
def execute_query(self, query, params=()):
cursor = self.connection.cursor()
try:
cursor.execute(query, params)
self.connection.commit()
except Error as e:
print(f"The error '{e}' occured")
raise e
def execute_read_query(self, query, params=()):
cursor = self.connection.cursor()
result = None
try:
cursor.execute(query, params)
result = cursor.fetchall()
return result
except Error as e:
#print(f"The error '{e}' occurred")
raise e
|
85639044b697e997db8071116e03c7db4ab69edc | marcazgomes/exercicios | /e060.py | 196 | 3.984375 | 4 | num = int(input('Digite o valor que deseja fatorar:'))
result = 1
cont = 1
while cont <= num:
result *= cont
cont += 1
print(result)
#fiz simples e sem mostrar lado por lado, irei corrigir |
93b388785197f4d4bacf152afdfc821df10c31f6 | rubiyadav18/if-else_question | /malel_faemle_ques_.py | 313 | 4.125 | 4 | sex=input("enter a sex")
age=int(input("enter a age"))
if sex=="female":
print("she work only urban areas")
if sex=="male":
if age>=20 and age<=40:
print("he work anywhere")
if sex=="male":
if age>=40 and age<=60:
print("he work only urban areas")
else:
print("nothing") |
4f0fc693df4ba16b4d9f8d91d6a1e88fa736e000 | Polovnevya/python_algoritms | /Lesson_1/task_5.py | 918 | 4.0625 | 4 | """
Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв.
https://drive.google.com/file/d/1Ui2yipbPwl4C9ZbY4KEk6VSmB2YBMh-k/view?usp=sharing
"""
char_1 = input('Введите первую букву из диапазона a-z ')
char_2 = input('Введите вторую букву из диапазона a-z ')
char_1_place = ord(char_1) - ord('a') + 1
char_2_place = ord(char_2) - ord('a') + 1
char_num = abs(char_1_place - char_2_place)
print(f'Первая буква {char_1} является {char_1_place} буквой алфавита a-z')
print(f'Вторая буква {char_2} является {char_2_place} буквой алфавита a-z')
print(f'Между буквами {char_1} и {char_2} находится {char_num} букв')
|
060a6eb7ded769bd20da0509407fc62b2e152231 | gargisingh1993/tweety-fiesta | /mytweet.py | 3,517 | 3.890625 | 4 | # A Simple Function to
# Fetch relevant tweet for a single REST Api request provided a keyword as a param
# Imported relevant libs - json , requests, request_oauthlib
# imported json since twitter api returns the output as a json object ( when we hit the end point )
# important information which is needed for running this code is mentioned as comments below
# argparse used to pass a argument in command line.
# To run this file in command prompt (windows) or Command line other OS , type python <filename> <keyword>(you want to search for)
import json
import requests
from requests_oauthlib import OAuth1
import random
import time
import argparse
def main():
#if we dont need the arguments in command prompt use the input fucntion to take a word to search relevant tweet in cmd or cli
#if we want for a keyword with multiple words (remove the parser object and use the input method)
#keyword = input('Enter the keyword word:')
try:
parser = argparse.ArgumentParser(description='Keyword for search')
parser.add_argument('b')
args = parser.parse_args()
keyword = args.b
myfunction(keyword)
except (SystemExit,KeyError):
print("Correct Argument needed to process request, try again with an argument")
def myfunction(keyword):
CONSUMER_KEY = "" # enter your app's consumer key
CONSUMER_SECRET = "" # enter app's consumer secret
ACCESS_KEY ="" # enter access token
ACCESS_SECRET = "" #access token secret
auth = OAuth1(CONSUMER_KEY,CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
url='https://api.twitter.com/1.1/search/tweets.json?q='+keyword
res = requests.get(url,auth = auth)
data = res.json()
mylist = []
try:
for statuses in data['statuses']:
d = {
'screen_name':statuses['user']['screen_name'],
'text':statuses['text'],
'url':statuses['user']['url'],
}
mylist.append(d)
except KeyError:
print ("entered string is invalid: please type a proper text to match")
myfuncprint(mylist)
def myfuncprint(mylist):
#for x in mylist:
#print(x)
try:
x = random.choice(mylist)
try:
print ("@username:",x['screen_name']," ",x['text'])
except UnicodeEncodeError:
pass
#print("IDLE does not support encoding: json in ansible") #can throw this exception if required to show the encoding problem with IDLE
if x['url'] is None:
print("Media : is empty")
else:
print("Media : ",x['url'])
print("\n")
except IndexError:
print ("No tweet present")
time.sleep(1)
if __name__ == "__main__": main()
#def convert(data):
# if isinstance(data, basestring):
# return str(data)
# elif isinstance(data, collections.Mapping):
# return dict(map(convert, data.iteritems()))
#elif isinstance(data, collections.Iterable):
# return type(data)(map(convert, data))
#else:
#return data
# we can use this function to convert the IDLE UnicodeEncodeError , but will need to import the ansible library to use the basestring
# to use this function we need to import the collections library
#since it was mentioned not to use anyother libraries other than the one's listed , i have commented this part of the code required to deal with the UnicodeEncodeError
|
dbd584358ed7ba19067eaa069a95fd0195c9e9db | zazuPhil/prog-1-ovn | /Att välja.py | 442 | 3.78125 | 4 | svar = input('Hur tar du dig hem ')
if svar == 'gå':
print('Du få motion, sent')
elif svar == 'cykla':
print('Du få motion, I tid')
elif svar == 'buss':
print('få inte motion, kom tidigare')
buss = input('25 kr för bussbiljett? [ja/nej]')
if buss == 'ja':
print('förlorade 25 kr')
elif buss == 'nej':
print('spara 25 kr')
else:
print('gå hem')
else:
print('få motion, trött') |
2d5324e38e033789d3256af5593b65c3b2de273a | ccxxgao/Tour-Scheduler | /scheduling.py | 4,948 | 3.640625 | 4 | import csv
import pandas as pd
import numpy as np
def getAvailabilities(string):
s = string.split(', ')
avail = [0,0,0,0,0]
for day in s:
if day == 'Monday': avail[0] = 1
elif day == 'Tuesday': avail[1] = 1
elif day == 'Wednesday': avail[2] = 1
elif day == 'Thursday': avail[3] = 1
elif day == 'Friday': avail[4] = 1
return avail
if __name__ == "__main__":
fileName = input("Enter csv file name: ")
A = pd.read_csv(fileName)
# Preprocessing
A['days_available'] = A["When are you available for tours?"].apply(lambda x: getAvailabilities(x))
cols = list(A)
for i in range(len(cols)):
print("Column", i, " ", cols[i])
a = [int(x) for x in input("Columns indices to drop: ").split()]
A = A.drop(A.columns[a], axis=1)
if 'Days_off' not in list(A):
A['Days_off'] = 0
A['num_of_tours'] = 0
A['Name'] = A['Name'].str.split(" ", n = 1, expand = True)
A['gave_tour_this_week'] = 0
temp = A['days_available'].apply(pd.Series)
weekdays = ['M', 'T', 'W', 'Th', 'F']
temp.columns = weekdays
A = A.join(temp, how='outer')
A = A.join(pd.DataFrame(np.zeros((len(A), len(A)), dtype=int)), how='outer')
A = A.drop(columns=['days_available'])
# assign head guides four tours each
heads = input("Head Guides: ").split()
head_guides = []
for i in heads:
head_guides.append(A[A['Name'] == i].index.tolist()[0])
head_tours = input("Max number of tours to assign head guides: ")
if head_tours == "":
head_tours = 0
else:
head_tours = int(head_tours)
# dict stores semester assignments
# week : [(g1, g2), (g1, g2)...]
semester_assignments = {}
w = int(input("Number of weeks: "))
num_guides = int(input("Guides per tour: "))
for week in range(0, w):
A['gave_tour_this_week'] = 0
semester_assignments[week] = []
for day in weekdays:
# get list of all indices of available guides on a given day
available_guides = A[A[day]==1]
# Remove guides unavailable that day
date_val = '('+str(week)+','+str(weekdays.index(day))+')'
for index, row in available_guides.iterrows():
if date_val in str(row['Days_off']):
available_guides = available_guides.drop(index)
# Remove head guides if they have given 3 tours
for h in head_guides:
if h in list(available_guides.index):
if A.iloc[h, A.columns.get_loc('num_of_tours')] == head_tours:
available_guides = available_guides.drop(h)
assigned_guides = []
curr_guide = -1
# Select Guide 1
curr_guide = available_guides[available_guides.num_of_tours==available_guides.num_of_tours.min()]
curr_guide = curr_guide[curr_guide.gave_tour_this_week==curr_guide.gave_tour_this_week.min()].sample(n=1)
A.iloc[curr_guide.index[0], A.columns.get_loc('num_of_tours')] += 1
A.iloc[curr_guide.index[0], A.columns.get_loc('gave_tour_this_week')] = 1
assigned_guides.append(curr_guide.index[0])
available_guides = available_guides.drop(curr_guide.index[0])
# Select Guide 2
if num_guides == 2:
# get the remaining available guides in a list
available_guides = available_guides[available_guides.num_of_tours==available_guides.num_of_tours.min()]
available_guides = available_guides[available_guides.gave_tour_this_week==available_guides.gave_tour_this_week.min()]
past_pairings = {}
for option in list(available_guides.index):
past_pairings[option] = A.iloc[assigned_guides[0], A.columns.get_loc(option)]
attempt = min(past_pairings, key=past_pairings.get)
A.iloc[attempt, A.columns.get_loc('num_of_tours')] += 1
A.iloc[attempt, A.columns.get_loc('gave_tour_this_week')] = 1
assigned_guides.append(attempt)
# add 1 to both guides' paired w/
A.iloc[assigned_guides[0], A.columns.get_loc(assigned_guides[1])] += 1
A.iloc[assigned_guides[1], A.columns.get_loc(assigned_guides[0])] += 1
guides = []
for g in assigned_guides:
guides.append(A.iloc[g, A.columns.get_loc('Name')])
semester_assignments[week].append(guides)
# For new guides
else:
guides = []
for g in assigned_guides:
guides.append(A.iloc[g, A.columns.get_loc('Name')])
semester_assignments[week].append(guides)
for key, val in semester_assignments.items():
print("Week ", key, ": ", val)
print(A) |
c38fb1f774833ebd470402882ce2d2153e1cfdcf | FahimFBA/Toph-Problem-Solution-by-FBA | /Fibonacci_Numbers.py | 234 | 3.84375 | 4 | n=int(input())
a=1
b=1
for i in range(0, n-2): #I gave two numbers to a & b already. So for managing them all properly, I have deducted them from the range of the loop
t=a+b #t is a temporary variable here
b=a
a=t
print(t) |
8a3b5322d2b29787a24408db3d6c84ad93aeca92 | AnkithAbhayan/math-functions | /maths/factors finder.py | 750 | 3.828125 | 4 | from math import *
import time
number = int(input("enter a number:"))
print("\n" * 1)
item_list = []
multiplication_list = []
factor_list = []
for i in range(number + 1):
if i == 0:
pass
else:
item_list.append(i)
length = len(item_list) + 1
for i in range(len(item_list)):
length -= 1
for a in range(len(item_list)):
if item_list[a] * length == number:
multiplication_list.append(str(item_list[a])+" X "+str(length)+" = "+str(number))
factor_list.append(item_list[a])
else:
pass
for letter in multiplication_list:
print(letter)
print("\n" * 2)
print("the factors of "+str(number)+" are: "+str(factor_list))
|
b59e3b256cc72c7b49cfa1072312ba3652982244 | arnabs542/interview-notes | /notes/algo-ds-practice/problems/backtracking/combinatorial/generate_all_permutations.py | 912 | 3.84375 | 4 | def generate_all_permutations(lst, start, end, solutions):
if start >= end:
solutions.append(list(lst))
for i in range(start, end):
lst[start], lst[i] = lst[i], lst[start]
generate_all_permutations(lst, start + 1, end, solutions)
lst[start], lst[i] = lst[i], lst[start]
def generate_all_permutations_iterator(lst, start, end):
if start >= end:
yield list(lst)
return
for i in range(start, end):
lst[start], lst[i] = lst[i], lst[start]
yield from generate_all_permutations_iterator(lst, start + 1, end)
lst[start], lst[i] = lst[i], lst[start]
def main():
lst = [1, 2, 3, 4]
solutions = []
generate_all_permutations(lst, 0, len(lst), solutions)
print(sorted(solutions))
print(len(solutions))
print(list(generate_all_permutations_iterator(lst, 0, len(lst))))
if __name__ == "__main__":
main()
|
a49d529dc5b4978e0ab2c58c8868554d01227c34 | frankpiva/leetcode | /2020/12/26.py | 1,474 | 4 | 4 | """
Decode Ways
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Input: s = "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: s = "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Example 3:
Input: s = "0"
Output: 0
Explanation: There is no character that is mapped to a number starting with '0'. We cannot ignore a zero when we face it while decoding. So, each '0' should be part of "10" --> 'J' or "20" --> 'T'.
Example 4:
Input: s = "1"
Output: 1
Constraints:
1 <= s.length <= 100
s contains only digits and may contain leading zero(s).
"""
# approach: recursion
# memory: O(n)
# runtime: O(n)
import functools
class Solution:
@functools.lru_cache(maxsize=None)
def numDecodings(self, s: str) -> int:
# base case
if len(s) == 0:
return 1
# single check
if 0 < int(s[0]) < 10:
single = self.numDecodings(s[1:])
else:
single = 0
# double check
double = 0
if len(s) >= 2:
if 9 < int(s[0:2]) < 27:
double = self.numDecodings(s[2:])
return single + double
|
548e221b7b5383521b906325abb4e8544289503b | drenwickw/this | /testcoded/test2.py | 780 | 4 | 4 | '''
repeat = True
while repeat:
try:
my_input = input('Type an integer here -->')
print (int(my_input))
repeat = False
except ValueError:
print ("try again")
'''
from random import randint
def coin_flip(number):
heads = 0
tails = 0
for trial in range(0, number):
while randint(0, 1) == 0:
heads += 1
tails += 1
return heads / tails
print (coin_flip(100000))
print (randint(0, 6))
print ('\n\n\n')
def dice(rolls):
tot = 0
try:
for i in range (1, rolls + 1):
roll = randint(1, 6)
tot = tot + roll
return tot / rolls
except rolls > 1000000:
print ('Too many rolls, mate')
rolls = int(input("how many times?"))
print (dice(rolls)) |
acdb0ee0f25254591fac1875be103230231f2acd | starxfighter/Python | /pythonoop/animalOOP.py | 1,594 | 4.34375 | 4 | # Set definition of the parent animal class
class Animal():
def __init__(self, name, health):
self.name = name
self.health = health
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def display_health(self):
print("The health for ", self.name, " is now", self.health)
# Set definition for a child class of animal call Dog
class Dog(Animal):
def __init__(self, name, health):
super().__init__(name, health)
self.health = 150
def pet(self):
self.health += 5
return self
# set definition for a child class of animal called Dragon
class Dragon(Animal):
def __init__(self, name, health):
super().__init__(name, health)
self.health = 170
def fly(self):
self.health -= 10
return self
def display_health(self):
super().display_health()
print("I am a Dragon")
# Create animal, walk three times, run twice and then display health
anAnimal = Animal("Bear", 100)
anAnimal.walk().walk().walk()
anAnimal.run().run()
anAnimal.display_health()
# Create a dog, walk three times,run twice, pet and then display health
poodle = Dog("Fluffy", 100)
poodle.display_health()
poodle.walk().walk().walk()
poodle.run().run()
poodle.pet()
poodle.display_health()
# Create a dragon, walk three times, run twice, fly and then display health
oldDragon = Dragon("Drago", 100)
oldDragon.display_health()
oldDragon.walk().walk().walk()
oldDragon.run().run()
oldDragon.fly()
oldDragon.display_health() |
7aa8ae4c55c18c601d03725199f618eb7bb581df | lucasjct/python_curso_em_video | /Mundo_2/while/ex71.py | 544 | 3.625 | 4 | cinquenta = vinte = dez = um = 0
v1 = (int(input('Qual valor você quer sacar? ')))
while True:
while v1 >= 50:
v1 = v1 - 50
cinquenta +=1
while v1 >= 20:
v1 = v1 - 20
vinte += 1
while v1 >= 10:
v1 = v1 - 10
dez += 1
while v1 >= 1:
v1 = v1 - 1
um += 1
if v1 == 0:
break
print(f'Você levará o total:')
print(f'{cinquenta} cédula(s) de R$50')
print(f'{vinte} cédula(s) de R$20')
print(f'{dez} cédula(s) de R$10')
print(f'{um} cédula(s) de R$1') |
631dbfd0c22f964468cf194bf17d78c13cfa25e4 | amol10/practice | /sort/quick_sort.py | 846 | 3.53125 | 4 | from copy import copy
unsorted = list(map(int, input().split()))
bsorted = copy(unsorted)
def qsort(arr, start, end):
if start >= end:
return
pivot_idx = partition(arr, start, end)
qsort(arr, start, pivot_idx - 1)
qsort(arr, pivot_idx + 1, end)
def partition(arr, start, end):
pivot_idx = start + int((end - start + 1) / 2)
pivot = arr[pivot_idx]
lesser = []
greater = []
for i in range(start, end + 1):
if i == pivot_idx:
continue
if arr[i] <= pivot:
lesser.append(arr[i])
else:
greater.append(arr[i])
new_range = lesser + [pivot] + greater
for i, new in zip(range(start, end + 1), new_range):
arr[i] = new
return start + len(lesser)
qsort(bsorted, 0, len(unsorted) - 1)
print(bsorted)
if all(list(map(lambda t : t[0] == t[1], zip(bsorted, sorted(unsorted))))):
print("OK")
else:
print("ERROR")
|
8723d93dd70ddf9685a7354aaa346de17647c87d | ggarcz1/LeetCode | /58. Length of Last Word.py | 152 | 3.578125 | 4 | def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip()
val = s.split(' ')
return len(val[len(val)-1]) |
ed78dc82cc23f8dd15b2cc2bb127d421437df5f1 | claytonjr/ProgrammingCollectiveIntelligenceExercises | /Chapter9/Exercise4.py | 2,080 | 4 | 4 | """ Chapter 9 Exercise 4: Hierarchy of interests.
"Design a simple hierarchy of interests, along with a data structure to represent it.
Alter the matchcount function to use the hierarchy to give partial points for matches."
I implemented a scoring system based upon the activeness levels of the interests.
A higher score means that people share the same activity levels.
* see end for more methods of personality based scoring of interests
"""
def matchcount(interest1,interest2):
activeness_scale = {'fashion': 0.3,'art': 0.4, 'scrabble': 0.2, 'skiing': 1.0, 'shopping': 0.6,
'camping': 0.7, 'dancing': 0.8, 'tv': 0.0, 'travel': 0.7, 'cooking': 0.3,
'writing': 0.1, 'reading': 0.1, 'knitting': 0.1, 'photography': 0.4, 'football': 1.0,
'running': 1.0, 'soccer': 1.0, 'animals': 0.9, 'opera': 0.2, 'computers': 0.0,
'movies': 0.3, 'snowboarding': 1.0}
l1=interest1.split(':')
l2=interest2.split(':')
x, y = 0, 0
for v in l1:
if v in activeness_scale:
x+=activeness_scale[v]
else:
x+=0.5
for v in l2:
if v in activeness_scale:
y+=activeness_scale[v]
else:
y+=0.5
x1 = float(x)/len(l1)
y1 = float(y)/len(l2)
if x1>y1:
return 1-float(x1-y1)
elif y1>x1:
return 1-float(y1-x1)
else:
return 1
"""
Here are some ideas for personality-based scoring of interests influenced by the Hexaco personality inventory.
Unconventionality scale
Altruism (versus Antagonism) scale
Creativity scale
Inquisitiveness scale
Aesthetic Appreciation scale
Prudence scale
Perfectionism scale
Diligence scale
Organization scale
Patience scale
Flexibility scale
Gentleness scale
Forgivingness scale
Liveliness scale
Social Boldness scale
Social Self-Esteem scale
Sincerity scale
Fairness scale
Greed Avoidance scale
Modesty scale
Fearfulness scale
Anxiety scale
Dependence scale
Sentimentality scale
"""
|
c85be6ac2c97db0b2ebc9aa6334095e9cbcd6793 | wanghan79/2020_Python | /朱旻鸿2018012708/平时作业2 修饰器随机数生成筛选/朱旻鸿 第二次作业封装为修饰函数方法.py | 2,930 | 3.578125 | 4 | ##!/usr/bin/python3
"""
Author: MinHong.Zhu
Purpose: Generate random data set by decorator.
Created: 17/5/2020
"""
import random
import string
def DataSampling(func):
def wrapper(datatype, datarange, num, *conditions,strlen=15):
'''
:param datatype: basic data type including int float string
:param datarange: iterable data set
:param num: number of data
:param conditions: variable-length argument
:param strlen: string length
:return: a function
'''
try:
result = set()
if datatype is int:
while len(result) < num:
it = iter(datarange)
item = random.randint(next(it), next(it))
result.add(item)
elif datatype is float:
while len(result) < num:
it = iter(datarange)
item = random.uniform(next(it), next(it))
result.add(item)
elif datatype is str:
while len(result) < num:
item = ''.join(random.SystemRandom().choice(datarange) for _ in range(strlen))
result.add(item)
return func(result, *conditions)
except NameError:
print("Please check data type in DataSampling")
except TypeError:
print("Please check iterable data type in DataSampling")
except MemoryError:
print("Too much data out of memory in DataSampling")
except:
raise Exception
return wrapper
@DataSampling
def DataScreening(data, *conditions):
'''
:param data: iterable data set
:param conditions: variable-length argument
:return: a data set
'''
try:
result = set()
for item in data:
if type(item) is int or type(item) is float:
it = iter(conditions)
if next(it) <= item <= next(it):
result.add(item)
elif type(item) is str:
for substr in conditions:
if substr in item:
result.add(item)
print("The result of data screening")
print(result)
print("Welcome to continue generating random data by decorator")
except TypeError:
print("Please check the data type in DataScreening")
except:
raise Exception
print("********************************************")
DataScreening(int,[0,200],100,60,90)
print("********************************************")
DataScreening(float,[0,100],100,60,70)
print("*********************************************")
DataScreening(str,string.ascii_letters+string.digits,2000,'at','att','attt')
print("**********************************************")
DataScreening(int,200,100,20,50) #Exception occurred 200 is not iterable
print("**********************************************") |
855bf53b19ad5584f647b7cbbe402f5f5d39cf11 | Pritam-Rakshit/Connection-monitoring-tool | /portscanfp.py | 4,572 | 3.828125 | 4 | #!/usr/bin/env python
#!/usr/bin/env python
#import argparse
import socket
import sys
import os
def scan_ports():
""" Scan remote hosts """
#Create socket
try:
os.system('dialog --menu "Port Scanner" 20 40 2 "1" "FQDN based scanning" "2" "IP based scanning" 2> choice')
option = open("choice",'r')
opt = option.readline()
option.close()
if opt == '1':
os.system('dialog --inputbox "Enter a qualified host name:" 10 40 --and-widget 2> hostname.txt')
h= open("hostname.txt",'r')
host=h.readline()
h.close()
os.system('dialog --inputbox "Enter a starting port Number(Start point of port scan):" 10 40 --and-widget 2> hostname.txt')
h= open("hostname.txt",'r')
start_port=int(h.readline())
h.close()
os.system('dialog --inputbox "Enter a Ending port number(End point of port scan):" 10 40 --and-widget 2> hostname.txt')
h= open("hostname.txt",'r')
end_port=int(h.readline())
h.close()
try:
remote_ip = socket.gethostbyname(host)
# print remote_ip
except socket.error,error_msg:
print error_msg
sys.exit()
else:
os.system('dialog --inputbox "Enter an IP address:" 10 40 --and-widget 2> hostname.txt')
h = open("hostname.txt",'r')
ip =h.readline()
h.close()
os.system('dialog --inputbox "Enter a starting port Number(Start point of port scan):" 10 40 --and-widget 2> hostname.txt')
h = open("hostname.txt",'r')
start_port=int(h.readline())
h.close()
os.system('dialog --inputbox "Enter a Ending port number(End point of port scan):" 10 40 --and-widget 2> hostname.txt')
h= open("hostname.txt",'r')
end_port=int(h.readline())
h.close()
try:
remote_ip = ip
# print remote_ip
except socket.error,error_msg:
print error_msg
sys.exit()
except:
print "Wrong input data type!"
sys.exit()
try:
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.settimeout(8)
except socket.error,err_msg:
print 'Socket creation failed. Error code: '+ str(err_msg[0]) + ' Error message: ' + err_msg[1]
sys.exit()
#Get IP of remote host
#Scan ports
end_port += 1
h=open("hostname.txt","w")
for port in range(start_port,end_port):
try:
sock.connect((remote_ip,port))
sock.settimeout(8)
h.write("Port" + str(port) + " | Service Name:" + socket.getservbyport(port) + "\n")
#print 'Port ' + str(port) + ' is open'+', Service Name:'+socket.getservbyport(port)
sock.close()
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error:
pass # skip various socket errors
h.close()
os.system('dialog --title "port Scanner" --textbox hostname.txt 22 70')
os.system('dialog --backtitle "Message" --radiolist "Do you want to block any service or port?" 10 40 2 1 Yes yes 2 No no 2> choice')
option = open("choice",'r')
opt = option.read(1)
option.close()
if opt == '1':
os.system('dialog --inputbox "Enter the port number to stop:" 10 40 --and-widget 2> port.txt')
prt = open("port.txt",'r')
port = prt.readline()
prt.close()
os.system('iptables -t filter -A INPUT -p tcp --dport '+ port +' -j REJECT')
os.system('iptables -t filter -A INPUT -p udp --dport '+ port +' -j REJECT')
os.system('dialog --title "Message" --msgbox "Port "'+ port +'" is blocked!" 15 40')
elif opt == '2':
os.system('dialog --backtitle "Unblock a Port" --radiolist "Unblock any service or port?" 10 40 2 1 Yes yes 2 No no 2> choice')
option = open("choice",'r')
opt1 = option.read(1)
option.close()
if opt1 == '1':
os.system('dialog --inputbox "Enter the port number to stop:" 10 40 --and-widget 2> port.txt')
prt = open("port.txt",'r')
port = prt.readline()
prt.close()
os.system('iptables -t filter -D INPUT -p tcp --dport '+ str(port) +' -j REJECT')
os.system('iptables -t filter -D INPUT -p udp --dport '+ str(port) +' -j REJECT')
os.system('dialog --title "Message" --msgbox "Port "'+ str(port) +'" is unblocked!" 15 40')
else:
sys.exit()
if __name__ == '__main__':
scan_ports()
|
77d330d7e2f51df5120887cb17f65899797b55f4 | legendbabs/Automate-The-Boring-stuff | /Chapter07/project/phone_number_email_extrctor.py | 1,831 | 4.28125 | 4 | '''
Say you have the boring task of finding every phone number and email
address in a long web page or document. If you manually scroll through
the page, you might end up searching for a long time. But if you had a program
that could search the text in your clipboard for phone numbers and
email addresses, you could simply press ctrl-A to select all the text, press
ctrl-C to copy it to the clipboard, and then run your program. It could
replace the text on the clipboard with just the phone numbers and email
addresses it finds.
'''
# Step1: Create a regex for phone numbers
import pyperclip, re
phoneRegex = re.compile(r'''
(
(\d{3}|\(\d{3}\))? # area code
(\s|-|\.)? # separator
\d{3} # first 3 digits
(\s|-|\.)? # separator
\d{4} # last 4 digits
(\s*(ext|x|ext.)\s*\d{2,5})? # extension
)
''', re.VERBOSE
)
# Step2: Create a regex for email address
emailRegex = re.compile(r'''
(
[a-zA-Z0-9._%+-]+ # username
@ # @ symbol
[a-zA-Z0-9.-]+ # domain name
(\.[a-zA-Z]{2,4}) # dot something
)
''', re.VERBOSE)
# Step 3: Find all the matches in the clipboard text
text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
phoneNum = '-'.join([groups[1], groups[3], groups[5]])
if groups[8] != '':
phoneNum += ' x' + groups[8]
matches.append(phoneNum)
for groups in emailRegex.findall(text):
matches.append(groups[0])
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print('Copied to clipboard.')
print('\n'.join(matches))
else:
print('No phone numbers or email address found.')
# phoneRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
# mo = phoneRegex.search('My number is: 070-332-6997')
# print(mo.groups())
|
7d2c9b9f1331b9b3bc78191391da077fae28812e | iamshafran/Learning_Python | /Learn/No Scratch Python/10-5-programming_poll.py | 263 | 3.703125 | 4 | filename = "Learn/No Scratch Python/programming_poll.txt"
answer = " "
while answer:
answer = input("Why do you like programming? ")
if answer == "0":
break
with open(filename, "a") as file_object:
file_object.write(f"{answer}\n")
|
aaa7f5ddc3f2259d4289b613c1183e37a2113648 | mandjo2010/geog786course | /Assignments/Assignment-1/Assignment1.py | 999 | 3.96875 | 4 | #Python Assinment 1 by Shahid Nawaz Khan
import math as libmath
R=6371
#Location of salt lake City
lat1= 40.7607793
lng1= -111.8910474
#location of newyork
lat2= 40.7127837
lng2= -74.0059413
#changing latlng from degrees to radians
#first set of coordinates changing from degrees to radians
lat1= libmath.radians(lat1)
lng1= libmath.radians(lng1)
#second set of coordinates changing from degrees to radians
lat2= libmath.radians(lat2)
lng2= libmath.radians(lng2)
#finding differences in latlng and finding their absolute vaues
deltaLat= abs(lat1-lat2)
deltaLng= abs(lng1-lng2)
#This will be the part of equation inside the square root
#just to make things simple we will calcuate individual parts and then combine the equations
rootpart= libmath.sqrt((libmath.pow(libmath.sin((deltaLat)/2),2))+libmath.cos(lat1)*libmath.cos(lat2)*(libmath.pow(libmath.sin((deltaLng)/2),2)))
distance = 2*R*libmath.asin(rootpart)
print(distance)
#print("Absolute values of lat/lng are")
#print(deltaLat, deltaLng)
|
3918af515cbdd72515be0484a63df3f38a547d2e | LJLee37/HackerRankPractice | /Algorithms/Sorting/ClosestNumbers.py | 988 | 3.640625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the closestNumbers function below.
def closestNumbers(arr):
arr.sort()
smallList = []
smallest = -1
for i in range(len(arr) - 1):
if smallest == -1:
smallest = arr[i + 1] - arr[i]
smallList.append(arr[i])
smallList.append(arr[i + 1])
elif smallest > arr[i + 1] - arr[i]:
smallest = arr[i + 1] - arr[i]
smallList.clear()
smallList.append(arr[i])
smallList.append(arr[i + 1])
elif smallest == arr[i + 1] - arr[i]:
smallList.append(arr[i])
smallList.append(arr[i + 1])
return smallList
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = closestNumbers(arr)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
|
833c3d72596ac7fac21949b3070ccfcb6290dcce | bettingf/imagesofsatellite | /Exercise.py | 6,867 | 3.546875 | 4 |
# coding: utf-8
# In[245]:
import numpy as np
import pandas as pd
import sklearn
def generateDataset(size, ndim=4):
bias=1
x = np.linspace(-2*np.pi, +2*np.pi, size)
timeSeries=4*np.sin(x)+bias
features=np.zeros((size, ndim))
labels=np.zeros((size, 1))
for i in range(size):
for j in range(ndim):
features[i,j]=np.random.random_sample()*10
if np.linalg.norm(features[i])>8:
labels[i]=1
return timeSeries, features, labels
timeSeries, features, labels = generateDataset(1000)
################## Your Code Here ##########################
################## First question ##########################
#Visualize the data, either using pandas ploting capability
#or matplotlib.
import matplotlib.pyplot as plt
from pandas.plotting import scatter_matrix
timeSeriesPd = pd.Series(timeSeries)
featuresPd = pd.DataFrame(features)
labelsPd = pd.DataFrame(labels, columns=['label'])
# Raw time series
plt.figure()
plt.title('Time series')
timeSeriesPd.plot()
# Frequency of labels
plt.figure()
labelsPd.plot(kind='hist', title='Frequency of labels')
# distribution of features
plt.figure()
plt.title('Distribution of features')
featuresPd.boxplot()
# correlation of features
scatter_matrix(featuresPd, alpha=0.2, figsize=(6, 6), diagonal='kde', c = labels.transpose()[0])
plt.suptitle('Correlations of features')
plt.show()
################## Second question ########################
#Preprocess the data so it is suited for ML analysis.
#Specifically it is desired to have Train and Validation
#Datasets with 75/25 weight.
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.utils import shuffle
# we scale the features to be in the range [0-1]
#scaler = preprocessing.MinMaxScaler()
scaler = preprocessing.StandardScaler()
scaler.fit(features)
scaledFeatures = scaler.transform(features)
scaledFeaturesPd = pd.DataFrame(scaledFeatures)
# we create the dataset containing both preprocessed features and outputs
scaleddataset=pd.concat([scaledFeaturesPd,labelsPd], axis=1)
dsTrain, dsTest = train_test_split(scaleddataset, test_size=0.25)
# we oversample the get roughly the same amount of positive and negative samples
count0 = dsTrain.label.value_counts()[0.0]
count1 = dsTrain.label.value_counts()[1.0]
dsTrain0 = dsTrain[dsTrain['label'] == 0]
dsTrain1 = dsTrain[dsTrain['label'] == 1]
# we also take each sample 3 times to have enough training data
dsTrain1Small = pd.concat([dsTrain1,dsTrain1,dsTrain1])
print('Imbalance ratio : ' + str(int(count1/count0)))
for i in range(0, 3*int(count1/count0)):
dsTrain1Small = pd.concat([dsTrain0, dsTrain1Small], axis=0)
dsTrainSmall = dsTrain1Small
# we shuffle the trainig set
dsTrainFinal = shuffle(dsTrainSmall)
dsTestFinal = dsTest # This line is just there for consistency.
################## Third question ##########################
#Using Principal Analysis Decomposition, reduce the
#dimensionality of the features to ndim=2. Then apply an
#MLP classifier on the new features and the original labels
#MLP characteristics are 3 hidden layers of 25 cells and
#sigmoid activation. Evaluate the model
from sklearn import decomposition
from sklearn.metrics import classification_report,confusion_matrix
# PCA
dsTrainFeaturesFinal = dsTrainFinal[dsTrainFinal.columns[:-1]] # we only keep features
dsTestFeaturesFinal = dsTestFinal[dsTestFinal.columns[:-1]] # we only keep features
pca = decomposition.PCA(n_components=2)
pca.fit(dsTrainFeaturesFinal)
newTrainFeaturesFinal = pca.transform(dsTrainFeaturesFinal)
newTestFeaturesFinal = pca.transform(dsTestFeaturesFinal)
# MLP
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import roc_auc_score, roc_curve
dsTrainLabelsFinal = dsTrainFinal[dsTrainFinal.columns[-1]] # we only keep labels
dsTestLabelsFinal = dsTestFinal[dsTestFinal.columns[-1]] # we only keep labels
mlp = MLPClassifier(hidden_layer_sizes=(25,25,25),max_iter=500,activation='logistic') # we create the MLP
mlp.fit(newTrainFeaturesFinal,dsTrainLabelsFinal) # we train the MLP
#evaluation
predictions = mlp.predict(newTestFeaturesFinal) # we first predict the labels of the test dataset
#we print the confusion matrix
print(confusion_matrix(dsTestLabelsFinal,predictions))
fpr, tpr, threshold = roc_curve(dsTestLabelsFinal,predictions)
plt.title('ROC')
plt.plot(fpr, tpr)
plt.plot([0, 1], [0, 1])
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()
#we print the area under curve
print('AUC = ' + str(roc_auc_score(dsTestLabelsFinal,predictions)))
################## Fourth question #########################
#Create a model to predict future steps of the timeSeries
#Please only use scikitLearn methods even though sub-optimal
#Justify the model selection and accuracy
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
lr = LinearRegression()
windowSize = 2
tsTrainTestSplit = int(len(timeSeries)*0.75)
def sliding_window(a, window_size):
l = []
for i in range(0, len(a)-window_size):
l.append(a[i:(i+window_size)].reshape(-1,1))
return np.concatenate(l, axis=1).transpose(), a[window_size:]
def forecast(a, window_size, split_point):
x,y=sliding_window(a[0:split_point],window_size)
lr.fit(x,y)
last_window = np.concatenate([x[-1][1:],y[-1:]]).reshape(-1,1).transpose()
forecast = []
for i in range(split_point+1, len(a)):
# predict one step and update the sliding window with the new value
last_window=np.concatenate([last_window[-1][1:],lr.predict(last_window[-1:])]).reshape(-1,1).transpose()
# record the result
forecast.append(last_window[0][-1])
return forecast
def forecast_rmse(a, window_size, split_point):
result = forecast(a, window_size, split_point)
return result,mean_squared_error(result, a[(split_point+1):])
result,rmse = forecast_rmse(timeSeries, windowSize, tsTrainTestSplit)
# model selection
rmseList = []
for size in range(2,20):
result,rmse = forecast_rmse(timeSeries, size, tsTrainTestSplit)
rmseList.append(rmse)
# Display of the RMSE errors curve
plt.figure()
pd.Series(rmseList).plot()
# we select the window size with the lowest root mean square
bestWindowSize = np.argmin(rmseList)+2
print('The best model has a window size of : ' + str(bestWindowSize))
result,rmse = forecast_rmse(timeSeries, bestWindowSize, tsTrainTestSplit)
print('The best model has a root mean square error of : ' + str(rmse))
# Visual comparison of the predictino and the reel curve
plt.figure()
plt.title('Forecast vs Time series on test set')
forecastPd = pd.Series(result)
forecastPd.plot()
pd.Series(timeSeries[(tsTrainTestSplit+1):]).plot(style='r--')
|
18e43f61237162612f387f7a4e26e1e5e84634d8 | MaX-Lo/ProjectEuler | /104_pandigital_fibonacci_ends.py | 907 | 3.5 | 4 | """
idea:
"""
import time
import math
def main():
# n = 10000 t: 2.325
# n = 10000 t: 1.189
# n = 10000 t: 0.131
# n = 10000 t: 0.1
f1 = 1
f2 = 2
count = 3
t0 = time.time()
while True:
if count % 5000 == 0:
print('n =', count, 't:', round(time.time() - t0, 3))
f1, f2 = f2, f1+f2
count += 1
length = int(math.floor(math.log10(f2)))+1
if count == 541:
print(f2 % 1000000000, is_pandigital(str(f2 % 1000000000)))
if length >= 9 and is_pandigital(str(f2 % 1000000000)):
first_9 = f2 // 10 ** (length - 9)
if is_pandigital(str(first_9)):
print(count, f2)
break
def is_pandigital(num):
return set(num) == set('123456789')
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time) |
ee1f07189fc8cce67e4150d2d4c38c160654cc72 | AlirezaMojtabavi/Python_Practice | /Elementary/3- string - list - dictionary - tuple/Ex_11_counting_the_votes.py | 290 | 3.578125 | 4 | from collections import OrderedDict
number = int(input())
dictOfVotes = OrderedDict()
i=0
while i < number :
votes = str(input())
dictOfVotes[votes] = dictOfVotes.get(votes,0) + 1
i+=1
for thisOne in sorted(dictOfVotes.keys()):
print(thisOne," ",dictOfVotes[thisOne]) |
d78feaf63fb56d0494aa8124d4d7ea712c27d685 | lbranera/CMSC-110 | /Loop 1 to 10/one-to-ten.py | 158 | 3.890625 | 4 | # WHILE LOOP style
i = 1
while (i<=10):
print(i, end=" ")
i = i + 1 # or i+=1
'''
FOR LOOP style
for i in range(1, 11):
print(i, end=" ")
''' |
695ad348a32f48ee544513df078de86b16bddcdc | ianhom/Python-Noob | /Note_3/Example_24_2.py | 378 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
'''
a = 2.0;
b = 1.0;
s = 0.0;
for n in range(1,21):
s += a / b;
b,a = a , a + b;
print s;
s = 0.0;
for n in range(1,21):
s += a / b;
b,a = a , a + b;
print s;
# result
'''
32.6602607986
32.360679776
'''
|
cb2c7a2d111fc1b9f76d1fe4cacff9262adec4b2 | aadithya/exercise | /g_anagrams.py | 322 | 4 | 4 | def group_anagrams(words):
anagrams = {}
for word in words:
key = ''.join(sorted(word))
anagrams[key] = anagrams.get(key,[]) + [word]
return anagrams
if __name__ == "__main__":
words = [word.strip() for word in raw_input("Enter all the words:").split(',')]
print group_anagrams(words)
|
e25ba797e0d239bb741168d7f53a0f3eed874c82 | OpLaa/Document-Search-using-Inverted-Index- | /otherTestFiles/invertedindex.py | 1,257 | 3.734375 | 4 | arra1=["aaa","bbb","ccc","ddd","aaa","bbb","ccc","bbb","bbb","bbb","ccc"]
b = []
unique = []
k=0
for i in range(0,len(arra1)):
presense=False
for check in range(0,len(unique)):
presense=False
if(arra1[i]==unique[check]):
presense=True
break
if(presense==True):break
if(presense==False):
unique.append(arra1[i])
count=0
b.append(arra1[i])
for j in range(i,len(arra1)):
if(arra1[i]==arra1[j]):
count=count+1
b.append(count)
#continue with highest number of occurence of words
print(b)
occur = []
occurword = []
for i in range(1,len(b),2):
occur.append(b[i])
for i in range(0,len(b),2):
occurword.append(b[i])
print(occur)
print(occurword)
seq=occur.copy()
seqword=occurword.copy()
for i in range(1, len(seq)):
j = i
while j > 0 and seq[j - 1] > seq[j]:
seq[j - 1], seq[j] = seq[j], seq[j - 1]
seqword[j - 1], seqword[j] = seqword[j], seqword[j - 1]
j -= 1
seq.reverse()
seqword.reverse()
print(seq)
print(seqword)
#after merge
aftersort = []
for i in range(0,int((len(b))/2)):
aftersort.append(seqword[i])
aftersort.append(seq[i])
print(aftersort)
|
2ce5ad45a94dc921faf42633b64fc56ea0fde70d | ACTCollaboration/enlib | /autoclean.py | 1,251 | 3.765625 | 4 | """This module defines a class decorator that makes sure that the __exit__
function gets called when the program exits, if it hasn't been called before.
Its purpose is to allow interactive use of resource-using classes. In those
situations, the standard "with" approach does not work."""
import atexit
_toclean_ = set()
def call_exit_for_objects(objs):
"""Calls __exit__ for all objects in objs, leaving objs empty."""
# To allow the __exit__ function of the removed objects to
# clean up other objects that have been registered, we must
# take into account that __exit__ may modify the toclean list.
# We therefore use a while loop, and keep handling and removing
# the first item.
while len(objs) > 0:
obj = objs.pop()
obj.__exit__(None,None,None)
atexit.register(call_exit_for_objects, _toclean_)
def autoclean(cls):
global _toclean_
# Fail on purpose if __init__ and __exit__ don't exist.
oldinit = cls.__init__
oldexit = cls.__exit__
def newinit(self, *args, **kwargs):
oldinit(self, *args, **kwargs)
_toclean_.add(self)
def newexit(self, type, value, traceback):
try: _toclean_.remove(self)
except KeyError: pass
oldexit(self, type, value, traceback)
cls.__init__ = newinit
cls.__exit__ = newexit
return cls
|
93d65752521f574d580acbf853194fce0bd0706c | yoda-yoda/my-project-euler-solutions | /solutions/347.py | 2,111 | 3.65625 | 4 | #!/usr/bin/python
"""
Author: Denis Karanja,
Institution: The University of Nairobi, Kenya,
Department: School of Computing and Informatics,
Email: dee.caranja@gmail.com,
Euler project solution = 347(Largest integer divisible by two primes)
Status.. PENDING...
"""
from time import time
def is_prime(num):
"""Check if a number is prime"""
if num == 1: return False
for i in xrange(2, num):
if num % i == 0 : return False
else: return True
def get_primes(prime_limit, primes = []):
"""Generate all primes in limit"""
for j in xrange(1, prime_limit):
if is_prime(j):
primes.append(j)
return primes
def max_val(my_list, maximum = 0):
"""Returns a maximum value of a list"""
for idx, val in enumerate(my_list):
if my_list[idx] > maximum:
maximum = my_list[idx]
return maximum
def remove_primes(p_remv, q_remv, primes_list, new_primes = []):
"""remove p and q in, primes_in_limit"""
for k in primes_list:
if (k != p_remv) and (k != q_remv):
new_primes.append(k)
return new_primes
def largest_int(p, q, limit = 100, results = []):
"""Finds the largest int divisible by two primes where p and q are prime numbers"""
primes_in_limit = get_primes(limit)
new_primes = remove_primes(p, q, primes_in_limit)
"""Get all ints divisible by p and q and other primes"""
for l in xrange(1, limit):
if l % p == 0 and l % q == 0:
results.append(l)
"""Get ints divisible by p and q only"""
for val in new_primes:
if results:
if (max_val(results) % val) == 0:
results.remove(max_val(results))
return max_val(results)
def generate(gen_limit, sum_of_ints = 0, tuple_list = []):
"""Generate a list of prime tuples p and q"""
for p_gen in xrange(2, gen_limit):
for q_gen in xrange(p_gen+1, gen_limit):
if is_prime(p_gen) and is_prime(q_gen):
tuple_list.append((p_gen, q_gen))
"""Calculate the largest int"""
for m in tuple_list:
(x, y) = m
#print (x,y), largest_int(x, y, 100)
return tuple_list
#print generate(100)
print(largest_int(2, 61))
this_list = [(2, 3), (2, 5), (2, 7), (2, 11), (2, 13), (3, 5)]
# for i in this_list:
# (a, b) = i
# print (a, b), largest_int(a, b)
|
ba8522f06deeb3fe9a7a551d21a2d1722b490474 | TwoChill/Learning | /Learn Python 3 The Hard Way/ex36 - Game Designing and Debugging.py | 9,853 | 3.625 | 4 | import random
import time
def enter_command():
enter_command = str(input(":> "))
return enter_command
def start(usrName, location, usrGendr):
print('\n############################')
print('# Rise of the Dragon Rider #')
print('############################\n')
print(' - Play - ')
print(' - Help - ')
print(' - Quit - ')
print('\n Made by: ')
print(' M.L. de France ')
print('\n############################\n')
while True:
start_answer = enter_command().upper()
if start_answer == 'PLAY':
player_info(usrName, location, usrGendr)
break
elif start_answer == 'HELP':
help(true)
elif start_answer == 'QUIT':
quit()
else:
print('\nI didn\'t get that!\n')
return start_answer
def help(start_menu):
print('\n\n############################')
print('# - Help - #')
print('############################\n')
print('- Type your commands to do them.')
print('- Use "look" to inspect surrounding.')
print('- Use "dig" to investigate area.')
print('- Good luck and have fun!.')
print('\n############################')
if start_menu == True:
help_answer = str(input('\nPress ENTER to continue\n:>'))
while True:
if help_answer == "":
start(usrName, location, usrGendr)
else:
help_answer = str(input('\nPress ENTER to continue\n:>'))
def player_info(usrName, location, usrGendr):
print("\n# INTRO GAME HERE #")
# this is told from a 'god' perspective
print("\n\nBut first let's create a character!\n\n")
usrGendr = str(input("Are you a boy or a girl?\n:> ")).upper()
if usrGendr == 'BOY':
print('\nI just made a boy from clay.\n\n')
usrGendr = usrGendr_boy
elif usrGendr == 'GIRL':
print('\nI just made a girl from my rib.\n\n')
usrGendr = usrGendr_girl
else:
randomnr = random.randint(1,3)
if randomnr == 1:
usrGendr = 'BOY'
print("\nI think I'll make a boy from clay.\n\n")
usrGendr = usrGendr_boy
else:
usrGendr == 'GIRL'
print("\nI think I'll make a girl from my rib.\n\n")
usrGendr = usrGendr_girl
usrName = str(input("Now choose your characters name:\n:> ")).capitalize()
while True:
if " " in usrName:
print('\nI just need one strong name...\n')
usrName = str(input("\n1Choose your characters name:\n:> ")).capitalize()
continue
elif usrName == "":
print('\nI just need one strong name...\n')
usrName = str(input("\n2Choose your characters name:\n:> ")).capitalize()
continue
else:
answer = str(input((f'\nIs "{usrName}" correct? (Y/N):\n:> ')).upper())
if answer == "":
continue
elif (answer == 'Y') or (answer == 'YES'):
outside_home(usrName, 'Outside_home', usrGendr)
elif (answer == 'N') or (answer == 'NO'):
usrName = str(input("\n3Choose your characters name:\n:> ")).capitalize()
continue
else:
continue
break
return usrName, usrGendr
def look(usrName, location):
print(f'{usrName} looks around at {location}')
def intro_setting(usrName, location):
dic_intros = {
'Home':f'''\n{location} INTRO HERE\n'''.upper(),
'Outside_home':f'''\n{location} INTRO HERE\n'''.upper(),
'usrName_room': f'''\n{location} INTRO HERE\n'''.upper(),
'Wildland':f'''\n{location} INTRO HERE\n'''.upper(),
'North':f'''\n{location} INTRO HERE\n'''.upper(),
'North_West':f'''\n{location} INTRO HERE\n'''.upper(),
'West':f'''\n{location} INTRO HERE\n'''.upper(),
'South_West':f'''\n{location} INTRO HERE\n'''.upper(),
'South':f'''\n{location} INTRO HERE\n'''.upper(),
'South_East':f'''\n{location} INTRO HERE\n'''.upper(),
'East':f'''\n{location} INTRO HERE\n'''.upper(),
'DarkLands':f'''\n{location} INTRO HERE\n'''.upper(),
}
intro_setting = dic_intros.get(location)
return intro_setting
def outside_home(usrName, location, usrGendr):
location = 'Outside_home'
# This is not going to work becuase variable is local. maby dictonary
first_enterd = 0
if first_enterd == 0:
print(intro_setting(usrName, location))
first_enterd += 1
print(f'''
{usrName} slowly opens {usrGendr[3]} eyes from {usrGendr[3]} hammock.
The first thing {usrName} notice
is the warm sun on {usrGendr[2]} face
birds chirping faintly in the background
and a lukewarm breeze,
that carries a sweet scent of primrose roses.
'''); time.sleep(15); print(f'''
Afther a few seconds
you hear the sound of a door opening.
You look up and see your {mentorName} standing in a doorway.
'''); time.sleep(10)
# tutorial_menu(usrName, location)
#
# # wake by mentor to go inside,
# # options: look around, dig, go inside home
# # Serrounding like god of war
# # go to central
# # dig
#
# def tutorial_menu(usrName, location):
# time.sleep(10)
# while True:
# usr_command = str(input('''
# - Look
# - Help
# - Quit
# :> ''').upper())
#
# if usr_command == 'LOOK':
# look(usrName, location)
# elif usr_command == 'HELP':
# help(false)
# elif usr_command == 'QUIT':
# answer = str(input(f'\nSure to quit {gameName}? (Y/N):\t').upper())
# if (answer == 'Y') or (answer == 'YES'):
# quit()
# elif (answer == 'N') or (answer == 'NO'):
# continue
# else:
# print("I didn't get that..")
# def home(location):
# # location = 'Home'
# # Your home
# # Your mentor
# # Your room with Lore read functie
#
# def usrName_room(location):
# location = 'usrName_room'
# # here are some books with lore
# # rest (saves the game)
#
# def mentor(location, quest1, quest2, quest3,):
# location = Home
# # parameter tells were you are in game and what to print
# # go outside and inside get basic_quest to dig outside find map() for mentor.
# ##got_quest = True (and shows in menu)
# # asked about quest and gives a hint an what to do next?
#
# def save_game():
# # saves items, qeusts done, progression order
# # saves game manualy
# # ask to overwrite or create new save.
#
# def auto_save():
# # auto saves afther certain points and quests
# # auto saves every room entry.
#
# def progression():
# # keeps a record of the main story so far
# # order can change depending on how the game is played.
#
# def dig(location, quest1, quest2, quest3):
# # can dig anywhere to find something or certain lores
# # droprate of items depends on were you are in stroy
# # depending on location, items to find
# # there's a time delay for this action
# # some books are only found throudigging
# # dictonarie clasified by region cost as value
#
# def shoptrader(location):
# location = 'Wildland'
# # first static at calmlands()
# # later based on player location moves around inc 3 or 4.
# # when shoptraders moves, has found mysterious stone, gives it to you for some gil
# # combine items to get new items wich can be used to do maby secret things
#
# def menu(got_quest, got_spellbook, lorefound):
# # Inventory()
# # Map()
# # Quest()
# # Spellbook()
# # lore_books('all')
# # Progression
# # Save game
# # Exit Game
# # help
# # q to quit
#
# def lore_books(location, book_nr):
# # book_nr == 1:
# # print(''' Book 1 ''')
# # etc
# # some books are only found through digging
#
# def game_over():
# # depending on how, game over msg is displayd
# # can coninue from last save or auto_save (which is every room enter)
#
# def spellbook():
# # menu of:
# # How to lift grandcloaking spellbook
# # How to make a invisable grandcloaking
# # wand, claok, t-stone ...
# # How to make a t-stone
# # other way to - dark invisable cloak - use ???
# # etc
#
#
# def inventory():
# # usrname list of items with amout
# # this can be used to append to shoptrader and other quest dudes
# # so prorgram knows what to have and not?
#
#
# def spellbook_quest():
# # everything about this quest
# # if quest is done.. msg for some thing else
# # secondary action is for t stone
#
#
# def wand_quest():
# # everything about this quest
# # have to dig
#
# def invisableCloak_quest():
# # everything about this quest
# # can use w to obtain but this evil act will cause cloak to be dark
# # and gets banashed from dragon riders land for ever
#
# def princess_tower():
# # can hear princess
# # lock opens depends on items
# #
#
# def wildlands(location):
# location = 'Wildland'
#
#
# def north(location):
# location = 'North'
#
# def norht_west(location):
# location = 'North_West'
#
# def west(location):
# location = 'West'
#
# def south_west(location):
# location = 'South_West'
#
# def south(location):
# location = 'South'
#
# def south_east(location):
# location = 'South_East'
#
# def east(location):
# location = 'East'
#
# def dark_lands(location):
# location = 'DarkLands'
def quit():
print('\nThank you for playing Rise of the Dragon Rider!\n')
exit(0)
gameName = 'Rise of the Dragon Rider'
mentorName = 'mentor'
usrName = ''
location = ''
usrGendr = []
usrGendr_boy = ["he", "his", "him", "his"]
usrGendr_girl = ["she", "hers", "her", "her"]
true = True
false = False
start(usrName, location, usrGendr)
|
8a60d618f47ce9917bf2c8021b2863585af07672 | sreesindhu-sabbineni/python-hackerrank | /TextWrap.py | 511 | 4.21875 | 4 | #You are given a string s and width w.
#Your task is to wrap the string into a paragraph of width w.
import textwrap
def wrap(string, max_width):
splittedstring = [string[i:i+max_width] for i in range(0,len(string),max_width)]
returnstring = ""
for st in splittedstring:
returnstring += st
returnstring += '\n'
return returnstring
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result) |
485c98650c27b73af00318dbe6ad5d8c51670739 | gsteinb/ace | /final/user_assignments.py | 8,177 | 3.71875 | 4 | import tkinter as tk
from tkinter import ttk, font, Tk, Label, Button, Entry,\
StringVar, DISABLED, NORMAL, END, W, E
from tkinter.messagebox import showinfo
import database_api as db
import sqlite3
from user import *
from main import *
from random import sample
conn = sqlite3.connect('ace.db')
APP_HIGHLIGHT_FONT = ("Helvetica", 14, "bold")
REGULAR_FONT = ("Helvetica", 12, "normal")
TITLE_FONT = ("Helvetica", 16, "normal")
NICE_BLUE = "#3399FF"
HOME_FONT = ("Comic Sans", 26, "bold")
class ViewUserAssignments(GUISkeleton):
'''
Objects of this type are used to generate the GUI for the user to see all Assignments screen
'''
def __init__(self, parent, controller, uid=None):
GUISkeleton.__init__(self, parent)
self.labels = ["Name", "Deadline", "Grade"]
# label at top of the frame
'''initiate the buttons on the screen'''
new_frame = ttk.Frame(self)
#back button
self.create_label(new_frame, "Current Assignments",
TITLE_FONT, "Red").pack(side="left", padx=40)
back_button = self.create_button(new_frame, "Back")
back_button["command"] = lambda: controller.show_frame('UserHome', self.real_uid)
back_button.pack(side="right", padx=10)
new_frame.grid(row=0, column=3, pady=20, sticky="E", columnspan=3)
# dictionaries to contain the widgets and associate widget to
# correspondin assignment id
self.names = {}
self.deadlines = {}
self.grades = {}
# the buttons
self.past_attempts = {}
self.new_attempts = {}
self.cont = controller
i = 2
for label in self.labels:
new_label = self.create_label(self, label, APP_HIGHLIGHT_FONT,
NICE_BLUE).grid(row=2, column=i)
i+=1
def set_uid(self, uid, aid=None, atid=None):
self.real_uid = uid
self.uid = uid[0]
self.atid = atid
self.gen_rows()
def gen_rows(self):
ids = db.get_assignments_ids(conn)
# set iterator for grid rows
i = 1
# for each id create a row
for aid in ids:
# get the attempts for the user
attempts = db.get_user_attempts(str(aid), self.uid, conn)
# get the assignment details
dets = db.get_assignment_details(aid, conn)
# create new entries
name_label = self.create_label(self, text=dets[1], font=REGULAR_FONT)
deadline_label = self.create_label(self, text=dets[4], font=REGULAR_FONT)
try :
grade_label = self.create_label(self, text=attempts[-2][4], font=REGULAR_FONT)
except IndexError:
grade_label = self.create_label(self, text=attempts[-1][4], font=REGULAR_FONT)
# add to corresponding dictonaries with user ids as keys
self.names[aid] = name_label
self.deadlines[aid] = deadline_label
self.grades[aid] = grade_label
# create new buttons
past_attempt_button = self.create_button(self, "Past Attempts")
new_attempt_button = self.create_button(self, "Current Attempt")
new_attempt_button.config(command=lambda j=[aid, self.atid]: self.cont.show_frame("Attempt" ,self.real_uid, j[0], j[1]))
past_attempt_button.config(command=lambda j=[aid, self.atid]: self.cont.show_frame("ViewPastAttempt", self.real_uid, j[0], j[1]))
# add to corresponding dictonaries with user ids as keys
self.past_attempts[aid] = past_attempt_button
self.new_attempts[aid] = new_attempt_button
# set everything nicely on the grid using an iterator i
name_label.grid(row=i+3, column=0)
deadline_label.grid(row=i+3, column=1)
grade_label.grid(row=i+3, column=2)
new_attempt_button.grid(row=i+3, column=3)
past_attempt_button.grid(row=i+3, column=4)
i += 1
class ViewPastAttempt(GUISkeleton):
def __init__(self, parent, controller, uid=None, aid=None):
GUISkeleton.__init__(self, parent)
self.labels = ["Date of Submission ", "Grade", "View Attempt"]
# label at top of the frame
title = self.create_label(self, "Your Attempts",
TITLE_FONT,
"Red").grid(row=0, column=1, pady=10, columnspan=2)
# dictionaries to contain the widgets and associate widget to
# correspondin assignment id
back_button = self.create_button(self, "Back")
back_button["command"] = lambda: self.refresh()
back_button.grid(row=0, column=3)
self.submissions = []
self.grades = []
self.buttons = []
# the buttons
self.view_attempts = {}
self.cont = controller
i = 1
for label in self.labels:
new_label = self.create_label(self, label, APP_HIGHLIGHT_FONT).grid(row=2, column=i)
i+=1
# generate all the dynamically generated widget rows
# enable clicking functionality for all the buttons
#self.enable_buttons()
def set_uid(self, uid, aid=None, atid=None):
self.real_uid = uid
self.uid = uid[0]
self.atid = atid
self.gen_rows(self.uid, aid)
def gen_rows(self, uid, aid):
all_attempts = db.get_user_attempts(str(aid), uid, conn)
# set iterator for grid rows
i = 1
atid = 1
# for each id create a row
for attempts in all_attempts:
# create new entries
submission_label = self.create_label(self, text=attempts[5], font=REGULAR_FONT)
grade_label = self.create_label(self, text=attempts[4], font=REGULAR_FONT)
# add to corresponding dictonaries with user ids as keys
self.submissions.append(submission_label)
self.grades.append(grade_label)
# create new buttons
view_attempt_button = self.create_button(self, "View")
view_attempt_button.config(
command = lambda j=atid: self.cont.show_frame("ViewAttempt" , self.real_uid, aid, j))
self.buttons.append(view_attempt_button)
# add to corresponding dictonaries with user ids as keys
# set everything nicely on the grid using an iterator i
submission_label.grid(row=i+3, column=1)
grade_label.grid(row=i+3, column=2)
view_attempt_button.grid(row=i+3, column=3)
atid += 1
i += 1
def refresh(self):
for i in self.submissions:
i.destroy()
for j in self.grades:
j.destroy()
for k in self.buttons:
k.destroy()
self.cont.show_frame('ViewUserAssignments', self.real_uid)
class Assignment():
'''
A problem object which is used to interact with assignment's data,
and perform actions that affect assignment's data
'''
def __init__(self,aid):
'''
aid is the assignment id of the assignment we want to create
'''
# get user details from database
assignment = db.get_assignment_details(conn, aid)[0]
# assign corresponding values to variables
self.aid = assignment[0]
self.topic = assignment[1]
self.deadline = assignment[2]
self.visible = assignment[3]
self.questions = assignment[4]
self.length = assignment[5]
# getters and setters
def get_aid(self):
return self.aid
def get_deadline(self):
return self.deadline
def get_length(self):
return self.length
def get_topic(self):
return self.topic
def get_questions(self):
return self.questions
def get_visible(self):
return self.visible
|
1c8c6b421234239d6e254cd918c35d6795ad5676 | defibull/leetcode | /matrix_median.py | 739 | 3.546875 | 4 | def count_small_or_eq(B,x):
low = 0
high = len(B)-1
curr = -1
while low <= high:
mid = (low+high)/2
if B[mid] <= x:
curr = mid
low = mid+1
else:
high = mid-1
return curr +1
def findMedian( A):
for row in A:
for i, num in enumerate(row):
s = i
for nc_row in A:
print s
if nc_row == row:
continue
s+=count_small_or_eq(nc_row,num)
if s == int(len(A)*len(A[0]))/2:
return num
print findMedian([
[2],
[1],
[4],
[1],
[2],
[2],
[5]
])
|
e861d7f8aeb8c4c030e2da315df9d23da91b143b | SMerchant1678/frc-hw-submissions | /lesson5/lesson5number2.py | 261 | 3.8125 | 4 | name = raw_input("What is your name? ")
color = raw_input("What is your favorite color? ")
pet = raw_input("How many pets do you have? ")
array = [name, color, pet]
print array[0] + "'s favorite color is " + array[1] + ". They have " + array[2] + " pets."
|
7b47e55fc2aeb225e041a347b88ee73f612a722c | chrisjackson4256/nlpIMDB | /review_to_words.py | 598 | 3.578125 | 4 | from bs4 import BeautifulSoup
import re
def review_to_words( raw_review ):
''' function to convert raw IMDB review
to list of words'''
# remove markup and tags
bs_review = BeautifulSoup( raw_review )
# remove numbers and punctuation
letters_only = re.sub(r'[^a-zA-Z]', ' ', bs_review.get_text())
# convert to lower case
lower_case = letters_only.lower()
# split string into list
words_only = lower_case.split()
# define the stop words
stops = set(stopwords.words("english"))
# remove stop words from review
words = [w for w in words_only if w not in stops]
return " ".join(words) |
ce4be701d31baffd748aaa7c1cc79486b2399dce | GoncaloPascoal/feup-fpro | /Recitations/RE10/flatten.py | 312 | 4.15625 | 4 | # -*- coding: utf-8 -*-
def flatten(alist):
"""
Given a nested list, returns a single list with each of the non-list elements.
"""
l = []
for i in range(len(alist)):
if type(alist[i]) is list:
l += flatten(alist[i])
else:
l += [alist[i]]
return l
|
51338b2b6b0b070f8ca7da04374386bb86f3439c | murphy-codes/challenges | /Python_edabit_VeryHard_Unique-Character-Mapping.py | 644 | 4.15625 | 4 | '''
Author: Tom Murphy
Last Modified: 2019-10-23 15:54
'''
# https://edabit.com/challenge/yPsS82tug9a8CoLaP
# Unique Character Mapping
# Write a function that returns a character mapping from a word.
def character_mapping(phrase):
char_map = []
mapping = dict()
i = 0
for l in phrase:
if l not in mapping:
mapping[l] = i
i+=1
char_map.append(mapping[l])
return char_map
print(character_mapping("abcd")) # ? [0, 1, 2, 3]
print(character_mapping("abb")) # ? [0, 1, 1]
print(character_mapping("babbcb")) # ? [0, 1, 0, 0, 2, 0]
print(character_mapping("hmmmmm")) # ? [0, 1, 1, 1, 1, 1]
|
77bb8d91891c66914a97c6f21721b3e195edf36f | mrparkonline/py_basics | /solutions/basics1/squareTiles.py | 417 | 4.4375 | 4 | # Write a program that inputs the number of tiles and then prints out the maximum side length. You may assume that the number of tiles is less than ten thousand.
from math import sqrt as squareRoot
# input
tiles = int(input('Enter the number of tiles: '))
# processing
max_side_length = squareRoot(tiles)
max_side_length = int(max_side_length)
# output
print('The largest square has side length', max_side_length) |
13e834539990883adf53817e52291264f51abdd5 | ddaypunk/tw-backup | /Python/CodeAcademy/Python Class/notes_Mar3_2013.py | 1,094 | 4.46875 | 4 | """
CODE ACADEMY NOTES - MAR 3
"""
""" Lists """
#the following will add a value to the end of a list
list_name.append(value)
#the follwing will add a list to the end of a list
list_name.extend(value)
#alternately using append
for each in list_name2:
list_name1.append(each)
#the following will search for a value in list, returns position
list_name.index(value)
#the following will insert a value into the list at a position
list_name.insert(pos,value)
#moves all items from pos and back, forward one space or pos+1
#remove the value from the list
list_name.remove(value)
#the following will sort a list in increasing alpha/num order
list_name.sort()
#does not return a list, replaces list_name
#get the total items in a list
len(list_name)
""" Dictionaries """
dict_name = {'key1': value1, 'key2': value2, ...}
#adds new key/value pair to dictionary
dict_name[new_key] = new_value
#deletes key and value at supplied key
del dict_name[key]
#dictionaries do not seem to have += opperators
""" Arbitrary number of args example """
m = 5
n = 13
def myFun(*args):
return sum(args) |
65d8fc5db3e8b6dd52d8874633f0eb168e44f638 | Arslan186/GeekBrains-Python | /lesson4_3.py | 201 | 3.796875 | 4 | my_list_1 = [2, 2, 5, 12, 8, 2, 12]
my_list = []
for a in my_list_1:
if my_list_1.count(a) == 1:
my_list.append(a)
print("Уникальные числа списка: ", my_list)
|
7c73420a99e9c29278a9111de1a841db46b3c5c7 | umunusb1/PythonMaterial | /python2/13_OOP/07_Class_Variables.py | 1,070 | 4.09375 | 4 |
class Employee:
"common base class for employee"
empcount = 0 # class variable
def __init__(self, name, salary):
self.name = name # instance variable
self.salary = salary
Employee.empcount += 1
def displaycount(self):
print "total employee%s" % Employee.empcount
def displayemployee(self):
print("name:", self.name, ",salary:", self.salary)
def __del__(self):
"""
destructor
:return:
"""
Employee.empcount -= 1
print 'Destructor is called'
print Employee, type(Employee)
print vars(Employee)
# "this would create first object of employee class"
print
Emp1 = Employee("Udhay", 2000) # "this would create second object of employee class"
print vars(Emp1)
print 'After Emp1 creation, Total employee count:', Employee.empcount
Emp2 = Employee("Prakash", 60000)
print 'Emp2.salary', Emp2.salary
print 'After Emp2 creation, Total employee count:', Employee.empcount
# Emp2 was terminated
del Emp2
print 'Total employee count:', Employee.empcount
|
da245462977164dfad5eb86059c10f83222580ed | leigon-za/Learning_Python | /10_15_failing_silently.py | 626 | 4.25 | 4 | def count_words(filenames):
"""Count the approximate number of words in a file"""
try:
with open(filename, encoding = 'utf-8') as f:
contents = f.read()
except FileNotFoundError:
pass
else:
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.")
filenames = ['lazarus.txt','niesczhe.txt','plato_the_republic.txt','pride_prejudic.txt']
for filename in filenames:
count_words(filenames)
# Here the file name for nietsczhe was changed - you can see that it produced
# no error, nor a print message |
621e6a47378c02fac8b89a7244a095bb2f3e629e | christianns/Curso-Python | /03_Control_de_flujo/14_Ejercicio_9.py | 1,248 | 3.828125 | 4 | # Problema 09: Un restaurante ofrece un descuento del 10% para consumos de hasta $ 100.00
# y un descuento de 20% para consumos mayores, para ambos caso se aplica un impuesto de 19%.
# Determinar el monto del descuento, el impuesto y el importe a pagar.
# Análisis: Para la solución de este problema, se requiere que
# usuario ingrese el consumo y es sistema verifica y calcula el
# monto del descuento, el impuesto y el monto a pagar.
valor_cuenta = None
IVA = 0.19
desc_10 = 0.10
desc_20 = 0.20
print ("Ingrese el valor de la cuenta:")
valor_cuenta = float(input())
if valor_cuenta <= 100000:
print ("Consumo:", float(int(valor_cuenta)))
valor_IVA = valor_cuenta * IVA
print ("IVA:", float(int(valor_IVA)))
desc_10 = valor_cuenta * 0.10
print ("Descuento 10%:", float(int(desc_10)))
valor_final = valor_cuenta + valor_IVA - desc_10
print ("Total:" , float(int(valor_final)))
if valor_cuenta > 100000:
print ("Consumo:", float(int(valor_cuenta)))
valor_IVA = valor_cuenta * IVA
print ("IVA:", float(int(valor_IVA)))
desc_20 = valor_cuenta * 0.20
print ("Descuento 20%:", float(int(desc_20)))
valor_final = valor_cuenta + valor_IVA - desc_20
print ("Total:" , flaot(int(valor_final)))
|
c08f13449767a15c8e3bc2704f649ec1094fc4d0 | ALENJOSE5544/Python-lab | /pythoncycle1/P04.py | 154 | 4.125 | 4 | #Program to find sum of two integers
a=int(input("Enter the frist number:"))
b=int(input("Enter the second number:"))
s=a+b
print("The sum is:")
print(s)
|
75196503764d71f7a6e5ff73df06a20e421de35e | imjoseangel/100-days-of-code | /python/howsum/howsum.py | 1,104 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
def howSum(targetSum: int, numbers: list, memo: dict = None) -> list:
if memo is None:
memo = {}
if targetSum in memo:
return memo[targetSum]
if targetSum == 0:
return []
if targetSum < 0:
return None
for num in numbers:
remainder = targetSum - num
remainderResult = howSum(remainder, numbers, memo)
if remainderResult is not None:
memo[targetSum] = [*remainderResult, num]
return memo[targetSum]
memo[targetSum] = None
return None
# m = target num
# n = numbers.length
#
# Brute Force
# time: O(n^m * m)
# space: O(m)
#
# Memoized
# time: O(n*m^2)
# space: O(m^2)
def main():
print(howSum(7, [2, 3])) # [3, 2, 2]
print(howSum(7, [5, 3, 4, 7])) # [4, 3]
print(howSum(7, [2, 4])) # None
print(howSum(8, [2, 3, 5])) # [2, 2, 2, 2]
print(howSum(300, [7, 14])) # None
if __name__ == '__main__':
main()
|
963c154eb4b383271452048826d1d4e1788fde54 | frclasso/turma1_Python_Modulo2_2019 | /Cap05_Tkinter/18_PainedWondw.py | 312 | 3.8125 | 4 |
from tkinter import *
root = Tk()
root.title("PainedWindow")
m1 = PanedWindow()
m1.pack(fill=BOTH, expand=1)
left = Entry(m1, bd=2)
m1.add(left)
m2 = PanedWindow(m1, orient=VERTICAL)
m1.add(m2)
top = Scale(m2, orient=HORIZONTAL)
m2.add(top)
button = Button(m2, text="ok")
m2.add(button)
root.mainloop()
|
16bb0a81bcda4d1c63d5c6483c54c0383a43a7d6 | ClearlightY/Python_learn | /top/clearlight/base/liaoxuefeng/functional_programming/higher_function/Map_Reduce_HigherOrder_Function.py | 3,474 | 3.96875 | 4 | from functools import reduce
# 高阶函数: map/reduce
# 变量可以指向函数
print(abs(-10))
print(abs)
x = abs(-10)
print(x)
# 变量指向函数
x = abs
print(x)
# 变量指向abs函数本身. 直接调用abs()函数和调用变量x()完全相似
print(x(-19))
# 函数参数传入函数
def add(x, y, f):
return f(x) + f(y)
# 一个函数能够把其它函数作为参数使用,这个函数就是高阶函数。
print(add(-5, 6, abs))
# map/reduce
# map()函数: 接受两个参数, 一个是函数, 一个是Iterable(可作用于for循环的对象)
# 作用: map将传入的函数一次作用到序列的每个元素, 并把结果作为新的Iterator返回
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(r)
# 由于结果r是一个Iterator
# Iterator是惰性序列, 因此通过list()函数让它把整个序列都计算出来并返回一个list
print(list(r))
print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
# reduce:把一个函数作用在一个序列, 接受两个参数, reduce把结果继续和序列的下一个元素做累积计算
# 序列求和, 用reduce实现
def add(x, y):
return x + y
print(reduce(add, [1, 3, 5, 7, 9]))
# 把序列[1,3,5,7,9]变成13579
def fn(x, y):
return x * 10 + y
print(reduce(fn, [1, 3, 5, 7, 9]))
# 把str转换为int的函数
def char2num(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits[s]
print(reduce(fn, map(char2num, '13579')))
# 上面两个函数整理成一个函数
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return DIGITS[s]
return reduce(fn, map(char2num, s))
print(str2int('13579'))
# lambda函数进一步简化
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(s):
return DIGITS[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
print(str2int('13579'))
# 1. 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
# 输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
def normalize(name):
return str.lower(name).capitalize()
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
# 2.Python提供的sum()函数可以接受一个list并求和
# 请编写一个prod()函数,可以接受一个list并利用reduce()求积:
def prod(L):
return reduce(lambda x, y: x * y, L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
# 3.利用map和reduce编写一个str2float函数
# 把字符串'123.456'转换成浮点数123.456
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': '.'}
def str2float(s):
flag = len(s) - s.index('.') - 1
def charTonum(s):
return DIGITS[s]
for i in range(len(s)):
if s[i] == '.':
s1 = s[:i]
s2 = s[i + 1:]
def f(x, y):
return x * 10 + y
return reduce(lambda x, y: x * 10 + y, map(charTonum, s)) / 10 ** flag
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
|
02036b74755314bfa61c61221a4a9e968d0145cb | realy-qiang/project | /finally/swiper/qdz/Swiper/libs/test.py | 1,002 | 3.65625 | 4 | # class myIteration(object):
# def __iter__(self):
# self.x = 0
# return self
# def __init__(self, n):
# self.n = n
# def __next__(self):
# if self.x < self.n:
# self.x += 1
# return self.x
# else:
# raise StopIteration
# my_iteration = myIteration(5)
# for i in my_iteration:
# print(i)
import sys
# def fib(n):
# a,b, counter = 0, 1, 0
# while True:
# if counter > n:
# return
# yield a
# a,b = b, a+b
# counter += 1
# f = fib(10)
# while True:
# try:
# print(next(f), end='')
# except StopIteration:
# sys.exit()
# def fun(val,list=[]):
# list.append(val)
# # print(id(list))
# return list
# data1 = fun(10)
# data2 = fun(123,[])
# data3 = fun('a')
# print(data1)
# print(data2)
# print(data3)
import random
list = [1, 2, 3, 4, 6, 6, 7, 8, 2, 10]
for i in range(3):
slice = random.sample(list, 5) # 从list中随机获取5个元素,作为一个片断返回
print(slice)
print(list, '\n') # 原有序列并没有改变 |
d1c1dcb8a83b08f94dce18df6c6e18cf35a9dea4 | maxpt95/6.00.1xPython | /Midterm/keyWithValues.py | 427 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 27 10:47:39 2021
@author: maxpe
"""
def keysWithValue(aDict, target):
'''
aDict: a dictionary
target: an integer
'''
targetKeys = []
for key, value in aDict.items():
if value == target:
targetKeys.append(key)
targetKeys.sort()
return targetKeys
print(keysWithValue({8: 1, 1: 2, 9: 0, 0: 1, 7: 0}, 0)) |
083809c950da1736f06c72977afd37a7a929a6f9 | haochen208/Python | /pyyyy/12 break、continue/02continue.py | 245 | 3.984375 | 4 | # continue:控制程序结束本次循环,直接进入下一轮循环!
# i = 1
# while i < 8:
# i += 1
# if i == 5:
# continue
# print(i)
for i in range(5):
if i == 3:
continue
print(i)
|
e957732614a518d8d608b4157d9d80f7d8102dd0 | dOtOlb/mmls | /lib/ItemRecord.py | 1,151 | 3.5 | 4 | import sys
import datetime
import operator
class ItemRecord:
"""A data structure holding all the information about an item"""
def __init__(self, type, id, score, data):
self.type = type
self.id = id
self.score = score
self.boosted_score = score
self.data = data
self.time = datetime.datetime.now()
self.active = True
# get_id getter method
def get_id(self):
return self.id
# get_time getter method
def get_time(self):
return self.time
# get_score getter method
def get_score(self):
return self.score
# get_type getter method
def get_type(self):
return self.type
# get_data method
def get_data(self):
return self.data
# is_deleted method to check if it is deleted
def is_deleted(self):
return not self.active
# delete method
def delete(self):
self.active = False
# need to compute the boost score
def boost_score(self, boost, start_over):
self.boosted_score = (self.score if start_over
else self.boosted_score) * boost
|
653cc9d592c85bc0aac44018b28d194fdc04ce76 | dhany007/ark | /4.py | 540 | 4.125 | 4 | def thirdHighest(arrNumber):
lst = []
if(type(arrNumber)==list):
if(len(arrNumber)<3):
print("Minimal array length is 3!")
else:
for i in arrNumber:
if type(i)== int:
lst.append(i)
lst.sort(reverse=True)
print(lst[2])
else:
print("Parameter should be an array!")
thirdHighest([1,2,3,4,5])
thirdHighest([1,4,5])
thirdHighest(1)
thirdHighest('a')
thirdHighest([107,1,-4,'a','true',0, -77])
|
cd851c231fa5659416432bea5a7f57f0b0b50eb3 | NineOnez/Python_Language | /28_String.py | 729 | 4.09375 | 4 | '''
text = "Hello"
print(text[0]+"Hello")
print(text[1]*3)
print(text[0:4])
print("********************************")
address = "18/215 Donmeuang Bangkok"
print("Bangkok" in address)
print("BKK" not in address)
print("********************************")
name = "FirstOnez"
birthPlace = "Chaing Mai"
print("Hello" + name , "and was born in" , birthPlace)
print("********************************")
print("Hello %s ! and was born in %s"%(name,birthPlace))
name = input("Enter your name : ")
lastname = input("Enter your lastname : ")
print("Welcome %s %s To Maepaneekayhoom.inc"%(name.capitalize(),lastname.capitalize()))
text = "First"
textFormated = "Welcome %s"%(text)
print(textFormated.center(21,"-"))
print(len(text))
'''
|
34b58383fa28ad045e39f78890f8d8c7eeb2883f | chuzhinoves/DevOps_python_HW4 | /2.py | 816 | 3.921875 | 4 | """
2. Представлен список чисел. Необходимо вывести элементы исходного списка,
значения которых больше предыдущего элемента.
Подсказка: элементы, удовлетворяющие условию, оформить в виде списка.
Для формирования списка использовать генератор.
Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55].
Результат: [12, 44, 4, 10, 78, 123].
"""
input_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
lenght = len(input_list) - 1
G = (input_list[i]
for i in range(1, lenght)
if input_list[i] > input_list[i-1])
# проверка
[print(i) for i in G] |
6f94ae61da9dbc5b01d1641193586c5cdb68fa9f | sandeepbaldawa/Programming-Concepts-Python | /recursion/power.py | 305 | 3.796875 | 4 | def power(base, exp):
if exp == 0:
return 1
half = power(base, exp/2)
if exp & 1: # odd number or not exp % 2
return base * half * half
else:
return half * half
print power(5,3)
print power(5,0)
print power(5,2)
print power(2,2)
|
c3a879af8b4301e67363f705175764b9ef5c169d | PacktPublishing/Mastering-Object-Oriented-Python-Second-Edition | /Chapter_7/ch07_ex4.py | 1,031 | 3.859375 | 4 | #!/usr/bin/env python3.7
"""
Mastering Object-Oriented Python 2e
Code Examples for Mastering Object-Oriented Python 2nd Edition
Chapter 7. Example 4.
"""
# Comparisons
# ======================================
# Using a list vs. a set
import timeit
def performance() -> None:
list_time = timeit.timeit("l.remove(10); l.append(10)", "l = list(range(20))")
set_time = timeit.timeit("l.remove(10); l.add(10)", "l = set(range(20))")
print(f"append; remove: list {list_time:.3f}, set {set_time:.3f}")
# Using two parallel lists vs. a mapping
list_2_time = timeit.timeit(
"i= k.index(10); v[i]= 0", "k=list(range(20)); v=list(range(20))"
)
dict_time = timeit.timeit("m[10]= 0", "m=dict(zip(list(range(20)),list(range(20))))")
print(f"setitem: two lists {list_2_time:.3f}, one dict {dict_time:.3f}")
__test__ = {name: value for name, value in locals().items() if name.startswith("test_")}
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=False)
performance()
|
ffd25919a225ecaaeb5ba85e8f24e50ced54ae44 | jeffanberg/Coding_Problems | /leetcode_problems/problem11.py | 480 | 3.875 | 4 | '''
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
'''
def maxArea(self, height: List[int]) -> int:
return -1 |
ae5c05558de8bfd1cff176448a0e298a14310e49 | Eduarda8/ExercicioProva2bim | /questao24.py | 280 | 4.25 | 4 | '''
Questão 24 :
Faça um programa que calcule o mostre a média aritmética de N notas.
Resposta :
'''
quantidade = int(input("Digite a quantidade de notas"))
soma = 0
for i in range(quantidade):
soma += int(input("Digite uma nota:"))
print("A media e: ", soma/quantidade)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.