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 |
|---|---|---|---|---|---|---|
0c69af55072f8d45e4f70de71c6f92562b63c791 | ewerthonjust/TG-Trabalho1-2020 | /Q3/arvore.py | 2,876 | 3.515625 | 4 | import csv
#@authors Diego Arndt & Ewerthon Ricardo Just
def isEmpty(collection):
return collection == None or collection.__len__() == 0
def converterDistancia(string):
if string is '':
return None
return int(string)
def getFilhos(distanciasLista):
filhos = []
index = 0
for nodeDistance in distanciasLista:
if nodeDistance != None and nodeDistance != 0:
filhos.append(index)
index += 1
return filhos
def inserirFronteira(novoNo, filho, fronteira):
novoNo.filho = filho
novoNo.custo = novoNo.custoParente(filho)
print()
print("- Pai:", novoNo.filho.nome)
print("- Custo atual:", novoNo.custo)
print("- Custo por estimativa:", novoNo.calculaCustoEstimativa())
for no in fronteira:
# Mantem as fronteiras com a melhor opção no final
if(no.calculaCustoEstimativa() <= novoNo.calculaCustoEstimativa()):
fronteira.insert(fronteira.index(no), novoNo)
return
fronteira.append(novoNo)
class No:
custo = None
filhos = []
filho = None
def __init__(self, id, nome, distanciasLista, distanciaReta=None):
self.id = id
self.nome = nome
self.distanciasLista = list(map(converterDistancia, distanciasLista))
self.filhos = getFilhos(self.distanciasLista)
self.distanciaReta = distanciaReta
def distancia(self, no):
return self.distanciasLista[no.id]
def calculaCustoEstimativa(self):
return self.custo + self.distanciaReta
def getNome(self):
return self.nome
def custoParente(self, filho):
return filho.custo + filho.distancia(self)
def printCaminho(no):
if(no.filho is None):
return no.nome
return f'{printCaminho(no.filho)} -> {no.nome}'
def lerArvore():
nosLista = []
nNos = 0
with open('arvore.csv') as arvore:
csvReader = csv.reader(arvore, delimiter=',')
nLinhas = 0
for linha in csvReader:
if nLinhas == 0:
tipoBusca = linha[0]
linha.remove(linha[0])
print(f'{tipoBusca}: {", ".join(linha)}')
else:
nomeNo = linha[0]
linha.remove(linha[0])
nosLista.append(No(nLinhas - 1, nomeNo, linha))
nLinhas += 1
nNos = nLinhas - 1
print(f'Numero total de {tipoBusca}: {nNos}')
print()
arvore.close
with open('distanciaReta.csv') as distanciaReta:
csvReader = csv.reader(distanciaReta, delimiter=',')
nLinhas = 0
for linha in csvReader:
if(nLinhas > nNos):
raise "Quantidade de distâncias em linha reta diferente do número de {tipoBusca}!"
nosLista[nLinhas].distanciaReta = int(linha[1])
nLinhas += 1
distanciaReta.close
return nosLista
|
523eaf51a45727fb5e64f4b8b44b199906e8e24c | zekiahmetbayar/python-learning | /Bolum1_Problemler/dik_ucgen.py | 407 | 3.765625 | 4 | #Kullanıcıdan bir dik üçgenin dik olan iki kenarını(a,b) alın ve hipotenüs uzunluğunu bulmaya çalışın.
#Hipotenüs Formülü: a^2 + b^2 = c^2
kisa_kenar = int(input("Üçgenin kısa kenarını giriniz : "))
uzun_kenar = int(input("Üçgenin uzun kenarını giriniz : "))
hipo_kenar = 0
(hipo_kenar) = (kisa_kenar ** 2) + (uzun_kenar ** 2)
print("Hipotenus : {} ".format(hipo_kenar ** 0.5))
|
91c28b237c6d9bea65310e20ae92ad3e83d3133d | wilkuukliw/introduction_to_python | /week13/code_from_today/monday/decorators.py | 1,084 | 4.1875 | 4 | # decorators.py
# Functions are first class functions.
# functions can take other functions as parameters
# fnctions can return functions as return values
def my_first_class_function(x):
print(x())
return x
#def greet():
# return 'Hello'
# inner
def foo():
# declare
def inner():
return 'Hello from inner'
return inner
# simple decorator
def my_decorator(func):
def wrapper(*args):
print('This is before functions execution')
func(*args) # print('Hello')
print('This is done after execution')
return wrapper
"""
@my_decorator
def greet():
print('Hello')
# greet = my_decorator(greet)
"""
"""
@my_decorator
def greet(name):
print(f'Hello {name}')
"""
@my_decorator
def greet2(name, age):
print(f'Hello {name}, {age}')
def me_2_decorator(func):
def wrapper(*args):
x = 'Before execution of func'
x += func(*args)
x += 'After execution'
return x
return wrapper
@me_2_decorator
def greet(name):
return f'Hello {name}'
x = greet('Anna')
#print(x)
|
186dbd64c2e1bf02d58c4fdb18a1b7b07ed8c277 | AntoniyaV/SoftUni-Exercises | /Fundamentals/Mid-Exam-Preparation/Feb-2020-2-03-heart-delivery.py | 791 | 3.828125 | 4 | neighbourhood = input().split("@")
command = input()
neighbourhood = [int(i) for i in neighbourhood]
index = 0
while not command == "Love!":
length = int(command.split()[1])
index += length
if index >= len(neighbourhood):
index = 0
if neighbourhood[index] == 0:
print(f"Place {index} already had Valentine's day.")
else:
neighbourhood[index] -= 2
if neighbourhood[index] <= 0:
neighbourhood[index] = 0
print(f"Place {index} has Valentine's day.")
command = input()
print(f"Cupid's last position was {index}.")
if sum(neighbourhood) == 0:
print("Mission was successful.")
else:
failed_houses = [n for n in neighbourhood if not n == 0]
print(f"Cupid has failed {len(failed_houses)} places.")
|
242857e65fd56b46e91127c8f6f82405a2c1eaac | Beck-Haywood/Checklist | /checklist.py | 2,859 | 4.1875 | 4 | #Checklist
checklist = list()
# CREATE
def create(item):
checklist.append(item)
# READ
def read(index):
if (index >= len(checklist)):
print("Index number is larger than list! Cant read")
else:
return checklist[index]
# UPDATE
def update(index, item):
if (index >= len(checklist)):
print("Index number is larger than list!")
else:
checklist[index] = item
# DESTROY
def destroy(index):
if (index >= len(checklist)):
print("Index number is larger than list! cant destroy")
else:
checklist.pop(index)
# LIST all items in array
def list_all_items():
index = 0
for list_item in checklist:
print("{} {}".format(index, list_item))
index += 1
#COMPLETE
def mark_completed(index):
update(index, "{} {}".format("√", read(index)))
def user_input(prompt):
# the input function will display a message in the terminal
# and wait for user input.
user_input = input(prompt)
return user_input
#SELECT
def select(function_code):
# Create item
function_code = function_code.upper()
if function_code == "C":
input_item = user_input("Input item:")
create(input_item)
# Read item
elif function_code == "R":
item_index = int(user_input("Index Number?"))
# Remember that item_index must actually exist or our program will crash.
read(item_index)
# Print all items
elif function_code == "P":
list_all_items()
elif function_code == "U":
input_item = user_input("Add the item you want to update")
input_index = int(user_input("Add the index to add"))
update(input_index, input_item)
elif function_code == "X":
input_index = int(user_input("Add the index of the item you want to check off!"))
mark_completed(input_index)
elif function_code == "D":
input_index = int(user_input("Add the index of the item you want to destroy!"))
destroy(input_index)
elif function_code == "Q":
# This is where we want to stop our loop
return False
# Catch all
else:
print("Unknown Option")
return True
# TEST function
def test():
create("purple sox")
create("red cloak")
print(read(0))
print(read(1))
update(0, "purple socks")
destroy(1)
print(read(0))
list_all_items()
#mark_completed(0)
select("C")
# View the results
list_all_items()
# Call function with new value
select("R")
# View results
list_all_items()
# Continue until all code is run
#Run the Tests
#test()
running = True
while running:
selection = user_input(
"Press C to add to list, R to Read from list, P to display list,Q to quit, U to update, D to destroy, and X to check something off the list.")
running = select(selection)
|
4ae8e5beed7c6ec75ea15f3ec84d864c743064f0 | rsmbyk/computer-network | /socket-programming/udp/code/udp_server.py | 1,289 | 3.65625 | 4 | import operator
import socket
op = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.__truediv__,
"%": operator.mod,
"**": operator.pow
}
def number (n):
try:
float (n)
except ValueError:
return False
return True
def parse (msg):
msg = msg.split (" ")
if len (msg) != 3:
return "Invalid format!"
elif (msg[1] not in op or not number (msg[0]) or not number (msg[2])):
return "Invalid format!"
return str (round (op[msg[1]] (float (msg[0]), float (msg[2])), 2))
def main ():
buffer = 32
host = ""
port = 3000
sock = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
sock.bind ((host, port))
print ("Listening on port", str (port) + "...\n")
while True:
msg, client = sock.recvfrom (buffer)
msg = msg.decode ()
if msg.lower () == "exit":
break
print ("Receives message from", client[0])
print ("Received message:", msg)
result = parse (msg)
print ("Returning :", result, "\n")
sock.sendto (result.encode (), client)
print ("Waiting for another connection...")
sock.close ()
print ("Program terminated.")
if __name__ == "__main__":
main ()
|
eabc1d9164ae77082ab4c60f703bdf6d3f64ca65 | rodcgon/nr_converge | /nr_converge.py | 975 | 3.75 | 4 | # most of this code I found on the internet
# sorry, but it was some time ago, i don't remember the sources
def derivative(f, x, h, *args):
return (f(x+h,args) - f(x-h,args)) / (2.0*h) # might want to return a small non-zero if ==0
def solve(f, x0, h, *args):
lastX = x0
nextX = lastX + 10* h # "different than lastX so loop starts OK
while (abs(lastX - nextX) > h): # this is how you terminate the loop - note use of abs()
newY = f(nextX,args) # just for debug... see what happens
print "f(", nextX, ") = ", newY # print out progress... again just debug
lastX = nextX
nextX = lastX - newY / derivative(f, lastX, h, args) # update estimate using N-R
return nextX
def func1(x,*args): # change this function to whatever you want to get the zero
return x**2+5*x+2
if __name__ == "__main__":
x0=2 #initial guess
h = .0001 #desired precision
res = solve(func1, x0, h)
print res
|
bbace7b025b77da4bb871c8ac64c85f3f97ea333 | YaroslavHavrylovych/goiteens | /git/2016/group4/yaroslav_havrylovych/git_test/yaroslav.py | 231 | 3.796875 | 4 | """
Example for your home function
"""
def multiply(value):
"""
custom progression function
"""
mul = 1
for i in range(1, value):
mul = mul * i
return mul
print('mul 1..20 = ' + str(multiply(20)))
|
bc7c74b46a0347e4f9c3893375403b1fea34428e | 799142139zhufei/Data_Structure | /Object_oriented/常用设计模式/简单工程模式.py | 868 | 4.09375 | 4 |
'''不直接向客户暴露对象创建的实现细节,
而是通过一个工厂来负责创建产品类的实例'''
class Payment(object):
'''抽象产品角色'''
def pay1(self):
print('我是基类')
class PayTest1(Payment):
'''具体产品角色'''
def pay(self):
print('我是测试1')
super(PayTest1,self).pay1() # 子类继承了父类方法
class PayTest2(Payment):
'''具体产品角色'''
def pay(self):
print('我是测试2')
class PayFactory(object):
'''工厂角色'''
def create(self,pay):
if pay == 'PayTest1':
return PayTest1()
if pay == 'PayTest2':
return PayTest2()
else:
None
# 所有的类和方法统一在一个入口调用,代码复用性好
pf = PayFactory()
obj = pf.create('PayTest2')
obj.pay()
obj.pay1() |
730b5c93c7127486a09a07c60b940139ac54d260 | Rach1612/Python | /Python Short Pro/p4-5p2.py | 2,560 | 4.5625 | 5 | #Program A
#for this program the user will input length
print("To calculate area of a square we need to find lenght of one side of the square")
sideofsquare=(float(input("Enter length of side of the square"))) #ask user to enter lengh
print(float(sideofsquare)) #check lengh is correct
if sideofsquare <0:#check lengh is not negative number
print("Length must be >= 0. Please try again")
else:
areaofsquare=sideofsquare ** 2 #calculation to find area of square
print("thank you")
print("area of square is" ":"+ str(float(areaofsquare)))
#program B
lengthofside=(float(input("Please input length of side")))
print(float(lengthofside))
if lengthofside <0:
print("Length must be >= 0. Please try again") #check lengh is not negative number
else:
areaofcube=lengthofside**3
print(float(areaofcube))
print("area of cube is :" + str(float(areaofcube)))
#Program C
#area of circle with diameter : 202067.39
#if diameter= 202067.39 radius = half of this
#formula for calculating area of circle is A= pi x radius squared
#import math
import math
math.pi
print(math.pi) #to check math is working correctly
diameterofcircle=(float(input("Enter the diameter of the cirle please")))
print(float(diameterofcircle))
if diameterofcircle <0:
print("Length must be >= 0. Please try again.")
else:
radius=diameterofcircle/2
print(float(radius))
areaofcircle=float(math.pi)*radius**2
print("area of circle is :" + str(float(areaofcircle)))
#Program D
#volume of a sphere with diameter length :202067.39
#formula : v = 3/4 x pi x radius to the power of 3
#radius= diameter/2
diameterofsphere=int(float(input("Enter the length of diameter of the sphere please")))
print (float(diameterofsphere))
if diameterofsphere <0:
print("Length must be >= 0. Please try again.")
else:
radiusofsphere=(float(diameterofsphere / 2))
print(float(radiusofsphere))
volumeofsphere=3/4 * (math.pi *(float(radiusofsphere **3)))
print(float(volumeofsphere))
#Program E
#volume of cylinder with diameter:202067.39 and side length :202067.39
#formula v=pi x r** x height
height=(float(input("Enter height of cylinder please")))
print(float(height))
if height <0:
print("Length must be >= 0. Please try again")
else:
radiusofcylinder=(float(height/2))
print(float(radiusofcylinder))
volumeofcylinder=(float(math.pi * float(radiusofcylinder * (float(height)))))
print(float(volumeofcylinder))
|
eeaced2d9b58f0cfb8a8c4d673381f855226cc88 | carvalhopedro22/Programas-em-python-cursos-e-geral- | /Programas do Curso/Desafio 16.py | 146 | 3.953125 | 4 | import math
n = float(input('Digite um numero: '))
arredondado = math.trunc(n)
print('O numero arredondado é {}'.format(arredondado, math.trunc)) |
230f6eada0eff31f4e01636704d31d40a6c12603 | giabao2807/python-study-challenge | /basic-python/args.py | 268 | 3.703125 | 4 | #tham số biến động trong python
#loại tham số với số lượng k xác định
def sum(start, *numbers):
for n in numbers:
start += n
return start
print(sum(0, 1, 2)) # = 3
print(sum(1, 2, 3)) # = 6
print(sum(0, 1, 2, 3, 4, 5, 6)) # = 21 |
cffc7b4005d641c4b74d1bab3aa46896c0d4648e | mcctor/TweetMurmurs | /Twitter/murmur.py | 2,424 | 3.53125 | 4 | from collections import namedtuple
from datetime import date
import twitter
DATE_TODAY = date.today().strftime("%Y-%m-%d")
City = namedtuple('City', ['name','geocode'])
class TweetMurmurs:
_city_murmurs = list()
_major_cities = [
City(name='Nairobi', geocode='-1.27468,36.81170,50km'),
City(name='Thika', geocode='-1.0420115,37.0234126,50km'),
City(name='Mombasa', geocode='-4.0517497,39.6620736,50km'),
City(name='Kisumu', geocode='-0.0749726,34.5980818,50km'),
City(name='Nakuru', geocode='-0.45982,36.10068,50km'),
City(name='Eldoret', geocode='0.4836246,35.2622765,50km')
]
def __init__(self, consumer_key, consumer_secret, access_token_key, access_token_secret):
self.twitter_api = twitter.Api(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token_key=access_token_key,
access_token_secret=access_token_secret,
sleep_on_rate_limit=True
)
def get_all_tweets(self, limit=15):
"""
This method any tweet posted from one of the major cities listed. Have to be careful not to
surpass Twitter's Rate Limit of 15 requests per 15 minute TimeFrame Windows.
:param:
limit -> Maximum number of tweets to be returned for a given city.
:return:
A list containing tweets.
"""
posted_tweets = list()
# reset the class variable first
self._city_murmurs = list()
for city in self._major_cities:
city_murmurs = self.twitter_api.GetSearch(geocode=city.geocode, since=DATE_TODAY, count=limit)
data = dict(city=city.name, tweets=[])
if len(city_murmurs) > 0:
for city_murmur in city_murmurs:
data['tweets'].append(city_murmur.text)
posted_tweets.append(data)
self._city_murmurs = posted_tweets
return self._city_murmurs
def save(self):
"""
This method saves all the information stored in the instance variables to a
database.
"""
pass
if __name__ == '__main__':
murmur = TweetMurmurs(
consumer_key='VFbtuufO4wBzpfeDS6xEXd0Td',
consumer_secret='k2Ui7lDpX8iHAgQiAOSxm3FyRvUl9CMQzKYa5ZHSNd1VUk73kj',
access_token_key='1029806395376394240-CjX9utgkBv2IuScfqVJz7ag1govYpg',
access_token_secret='Rikyg9UQMRYG2sDG6Ak8UGLldL52rQoJCHWqkXfnKfUep'
)
print(murmur.get_all_tweets()) |
ca2106938a690722bef977aa603519835db2ce0a | Rukeith/leetcode | /108. Convert Sorted Array to Binary Search Tree/solution.py | 559 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def helper(self, num, first, last):
if last < first:
return None
mid = first + (last - first) // 2
root = TreeNode(num[mid])
root.left = self.helper(num, first, mid - 1)
root.right = self.helper(num, mid + 1, last)
return root
def sortedArrayToBST(self, num):
return self.helper(num, 0, len(num) - 1)
|
4c45123fe0275761df24b0efafaad0b2b803c69c | AlanVieyra333/machine-learning | /material/ACP/Preprocesamiento/preprocesa2.py | 297 | 3.515625 | 4 | import numpy as np
import sklearn.preprocessing as preprocessing
X = np.array( [[ 1.0, -2.0, 2.0 ],
[ 3.0, 0.0, 0.0 ],
[ 0.0, 1.0, -1.0 ]] )
# Normalizamos los datos
print( X, "\n" )
X_normalizada = preprocessing.normalize( X, axis=0 )
print( X_normalizada )
|
1e889868cf1df0feb933968b3c457ab46bfced35 | cyct123/LeetCode_Solutions | /25.reverse-nodes-in-k-group.py | 2,179 | 3.796875 | 4 | #
# @lc app=leetcode id=25 lang=python3
#
# [25] Reverse Nodes in k-Group
#
# https://leetcode.com/problems/reverse-nodes-in-k-group/description/
#
# algorithms
# Hard (54.26%)
# Likes: 10346
# Dislikes: 560
# Total Accepted: 654.7K
# Total Submissions: 1.2M
# Testcase Example: '[1,2,3,4,5]\n2'
#
# Given the head of a linked list, reverse the nodes of the list k at a time,
# and return the modified list.
#
# k is a positive integer and is less than or equal to the length of the linked
# list. If the number of nodes is not a multiple of k then left-out nodes, in
# the end, should remain as it is.
#
# You may not alter the values in the list's nodes, only nodes themselves may
# be changed.
#
#
# Example 1:
#
#
# Input: head = [1,2,3,4,5], k = 2
# Output: [2,1,4,3,5]
#
#
# Example 2:
#
#
# Input: head = [1,2,3,4,5], k = 3
# Output: [3,2,1,4,5]
#
#
#
# Constraints:
#
#
# The number of nodes in the list is n.
# 1 <= k <= n <= 5000
# 0 <= Node.val <= 1000
#
#
#
# Follow-up: Can you solve the problem in O(1) extra memory space?
#
#
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
count = 0
countNode = head
while (countNode):
count += 1
countNode = countNode.next
if not count:
return head
swapRound = count // k
dummyNode = ListNode()
prevNode = dummyNode
curNode = head
lastNode = None
for i in range(swapRound):
for j in range(k):
if not j:
lastNode = curNode
nextNode = prevNode.next
prevNode.next = curNode
curNode = curNode.next
prevNode.next.next = nextNode
prevNode = lastNode
prevNode.next = curNode
return dummyNode.next
# @lc code=end
|
156401931535e799aa60cd45224db94ca0ed784f | davidcgill/hs-game-library | /homepage.py | 1,874 | 3.65625 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: gilld
#
# Created: 19-12-2016
# Copyright: (c) gilld 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
from graphics import *
from random import *
from Button import *
import hangman
import Tictactoe
def exitbutton(win):
#creates the button which closes the program (to be placed on every page)
centre=Point(387,393)
exitbut=Button(win,centre,15,25,"x")
exitbut.activate("red")
#places the button in top right and returns the button to user
return exitbut
def homepage():
win=GraphWin("Chess",400,400)
win.setCoords(0,0,400,400)
win.setBackground("systemhighlight")
ext=exitbutton(win)
game=Button(win,Point(325,75),100,50,"TBD")
game1=Button(win,Point(325,135),100,50,"Checkers")
game2=Button(win,Point(325,195),100,50,"Chess")
game3=Button(win,Point(325,255),100,50,"Tictactoe")
game4=Button(win,Point(325,315),100,50,"Hangman")
game4.activate("red")
game3.activate("orange")
game2.deactivate()
game1.deactivate()
game.deactivate()
buttonlist=[game,game1,game2,game3,game4,ext]
while 1==1:
p=win.getMouse()
if buttonlist[5].clicked(p)==True:
win.close()
quit()
elif buttonlist[4].clicked(p)==True:
win.close()
hangman.main()
elif buttonlist[3].clicked(p)==True:
win.close()
Tictactoe.ticmain()
elif buttonlist[2].clicked(p)==True:
win.close()
elif buttonlist[1].clicked(p)==True:
win.close()
elif buttonlist[0].clicked(p)==True:
win.close()
#else move title movement word games bouncing back and forth
|
4551a0fb596d527e6ca3edf341673f4df6dc15d5 | prachi735/CodeWars | /replace_with_alphabet_position.py | 671 | 4 | 4 | from string import ascii_uppercase
from string import ascii_lowercase
from collections import OrderedDict
def alphabet_position(text):
upper_alpha = dict((k, i+1) for i,k in enumerate(ascii_uppercase))
lower_alpha = dict((k, i+1) for i,k in enumerate(ascii_lowercase))
for a in text:
if a in ascii_uppercase:
text = text.replace(str(a),str(upper_alpha[a])+" ")
elif a in ascii_lowercase:
text = text.replace(str(a),str(lower_alpha[a])+" ")
elif a == " ":
pass
else:
text = text.replace(str(a),"")
text = text.replace(" "," ")
text = text.strip()
return text
|
a016a1461185de97fc6f048d7696af458d5ade5b | MathMaster1296/MyFirstProject- | /main.py | 2,611 | 4.15625 | 4 | done = "\nDone with Program. Proceeding to Next Program.\n\n\n"
#Class #4
number = int(input("Enter a number: "))
prime = "The number is prime."
for x in range(2, number):
if number % x == 0:
prime = "The number is composite."
break
print(prime)
print(done)
number = int(input("Enter a number: "))
number1 = 0
number2 = 1
if number <= 0:
print("Invalid Input.")
elif number == 1:
print(number1)
else:
print(number1)
print(number2)
for x in range(number - 2):
print(number1 + number2)
number2 += number1
number1 = number2 - number1
print(done)
number = int(input("Enter a number: "))
for x in range(1, number + 1):
if x % 2 != 0 and x % 3 != 0:
print(x)
print(done)
while True:
number = int(input("Enter a number for Fizz Buzz! (Or type 0 for quit): "))
if number == 0:
break
if number % 15 == 0:
print("Fizz Buzz!")
elif number % 5 == 0:
print("Buzz!")
elif number % 3 == 0:
print("Fizz!")
else:
print("Oops!")
print(done)
factorial_number = int(input("Enter a number: "))
factorial = 1
for d in range(2, factorial_number + 1):
factorial *= d
print(f"The factorial of {factorial_number} is {factorial}")
print(done)
#Class #3
b = "nothing"
c = "nothing"
while not(b == "quit"):
b = input("Do you want to turn the fan on, off, or quit?: ")
if b == "on" or b == "off":
if (b == c):
print(f"Fan is already {b}")
else:
print(f"Fan turned {b}")
elif not(b == "quit"):
print("Invalid Input. Please Try Again.")
c = b
print(done)
num = int(input("Enter a Number: "))
if num % 2 == 1:
print("The number is odd.")
else:
print("The number is even.")
print(done)
z = int(input("Enter a number: "))
for a in range(z + 1):
print(a)
print(done)
text = input("What text do you want? ")
number = 1
for number1 in text:
print(f"{number} -> {number1}")
number += 1
print(done)
weightunit = input("Weight Unit: ")
weight = int(input("Weight: "))
if weightunit.lower() == "kg":
print(f"about {weight*2.2//1} pounds")
elif weightunit.lower() == "lb":
print(f"about {weight//2.2} kilograms")
else:
print("Invalid")
print(done)
age = int(input("What is your child's age? "))
if age <= 0:
print("not born")
elif 0 < age <= 3:
print("toddler")
elif 3 < age <= 12:
print("child")
elif 12 < age <= 18:
print("teenager")
else:
print("adult")
print(done)
x = int(input("First number: "))
y = int(input("Second number: "))
if x > y:
print(f"{x} - {y} = {x - y}")
elif x < y:
print(f"{y} - {x} = {y - x}")
else:
print("They are both equal")
print("Done with all Programs") |
e0e4369276b3fa7254b2fcfd4b3d4f44fb403791 | zhanganxia/other_code | /笔记/selfstudy/07-面向对象/09-单例模式.py | 735 | 3.84375 | 4 | # 单例模式
# 确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为
# 单例类,单例模式是一种对象创建型模式
class Singleton(object):
__instance = None
def __new__(cls,name,age):
if not cls.__instance:
cls.__instance = object.__new__(cls)
print('******',cls.__instance)
print('name',name)
print('age',age)
return cls.__instance
a = Singleton(18,"zax")
b = Singleton(20,"ljq")
print(id(a))
print(id(b))
a.age = 22
print(b.age)
#单例模式的目的:令单个进程中只有一个类的实例,从而可以实现数据的共享,节省系统开销,防止io阻塞等等 |
d7d092067ae1e98ad179419804899e04a929eb2f | jazyrcp/Python | /assign_1/assign_7.py | 212 | 3.859375 | 4 | print('Enter the Limits__________________')
low = int(input("Lower Limit:"))
up = int(input("Upper Limit:"))
for i in range(low,up+1):
c=0
for j in range(1,i+1):
if(i%j==0):
c=c+1
if c==2:
print(i)
|
ecf63936e9e1c667422d44866a373f3124f902ab | suryam35/Software-Lab-CS29006 | /Assignment-3/Part-2/torch_package/data/transforms/crop.py | 1,487 | 3.546875 | 4 | #Imports
from PIL import Image
import numpy as np
class CropImage(object):
'''
Performs either random cropping or center cropping.
'''
def __init__(self, shape, crop_type='center'):
'''
Arguments:
shape: output shape of the crop (h, w)
crop_type: center crop or random crop. Default: center
'''
# Write your code here
self.shape = shape
self.crop_type = crop_type
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
height, width = image.shape[0] , image.shape[1]
new_width = self.shape[1]
new_height = self.shape[0]
if self.crop_type == 'center':
left = round((width - new_width)/2)
top = round((height - new_height)/2)
x_right = round(width - new_width) - left
x_bottom = round(height - new_height) - top
right = width - x_right
bottom = height - x_bottom
im_crop = image[top:bottom , left:right]
return im_crop
else:
im_crop = image[0: new_height , 0:new_width]
return im_crop
# Write your code here
# crop = CropImage([478,640] , 'random')
# img = np.array(Image.open('./data/imgs/0.jpg'))
# im = crop(img)
# image = Image.fromarray(im)
# image.save('crop.jpg')
|
d50b0ec02eb892d9827d381c8cf7d1c29fbbdbfe | simeon49/python-practices | /inner_models/learn_detetime.py | 2,110 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 日期与时间处理
###################################################
# datetime 获取当前日期和时间
###################################################
print('============= datetime.datetime =============')
from datetime import datetime
now = datetime.now()
print(now) # 2019-02-18 17:16:38.635506
print(type(now)) # <class 'datetime.datetime'>
# 创建日期
dt = datetime(2019, 2, 17, 12, 30)
print(dt) # 2019-02-17 12:30:00
# timestamp
print(dt.timestamp()) # 1550377800.0
# timestamp 转datetime
# 2019-02-17 12:30:00 (东8区时间 UTC+8:00)
print(datetime.fromtimestamp(1550377800.0))
# UTC 标准市区的时间
print(datetime.utcfromtimestamp(1550377800.0)) # 2019-02-17 04:30:00
# str转换为datetime
print(datetime.strptime('2019-02-17 12:30:00',
'%Y-%m-%d %H:%M:%S')) # 2019-02-17 12:30:00
# datetime转换为str
print(now.strftime('%a, %b %d %H:%M')) # Mon, Feb 18 17:25
# datetime加减
from datetime import timedelta
print(dt + timedelta(hours=10)) # 2019-02-17 22:30:00
print(dt + timedelta(days=2, hours=12)) # 2019-02-20 00:30:00
# 设置时区
from datetime import timezone
tz_utc_8 = timezone(timedelta(hours=8)) # 创建时区UTC+8:00
print('now: ', now) # 2019-02-18 17:30:32.241769
# 2019-02-18 17:30:32.241769+08:00
print('utc8: ', now.replace(tzinfo=tz_utc_8))
# 练习: 假设你获取了用户输入的日期和时间如2015-1-21 9:01:30,以及一个时区信息如UTC+5:00,
# 均是str,请编写一个函数将其转换为timestamp:
import re
def to_timestamp(dt_str, tz_str):
tz_number = int(re.match(r'UTC([-\+]\d{1,2}):00', tz_str).groups()[0])
# print(tz_number)
tz = timezone(timedelta(hours=tz_number))
d = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
d = d.replace(tzinfo=tz)
return d.timestamp()
# 测试:
t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
assert t1 == 1433121030.0, t1
t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
assert t2 == 1433121030.0, t2
print('ok')
|
0022302a9c9c44c73b7ae40b95299470afb8995e | thomasearnest/MDeepLearn | /Pytorch/materials/decorator_high.py | 2,692 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name:decorator_high
Description : 使用类的高级装饰器
Email : autuanliu@163.com
Date:2018/3/23
"""
from abc import abstractmethod, abstractproperty, abstractclassmethod, abstractstaticmethod
# 抽象类定义
class Person():
def __init__(self, age, gender):
self.age = age
self.gender = gender
@abstractclassmethod
def run(cls, distance):
pass
@abstractstaticmethod
def do(string):
pass
@abstractproperty
def what(self):
pass
@abstractmethod
def get_name(self):
pass
class Student(Person):
def __init__(self, score, *args):
self.score = score
super().__init__(*args)
@classmethod
def run(cls, distance):
print(f'Run {distance} m')
@staticmethod
def do(string):
print('Do ', string)
@property
def what(self):
print('Yes')
def get_age(self):
return self.age
@property
def score(self):
return self.score
# @score.setter, 这个需要单层
def score(self, value):
assert isinstance(value, float), 'The value should be float!'
self.score = value
@property
def gender(self):
return self.gender
# @gender.setter
def gender(self, string):
assert isinstance(value, str), 'The value should be string!'
self.gender = string
# Test example
s1 = Student(95.3, 21, 'm')
s2 = Student(89.3, 18, 'f')
# 属性
s1.what
s2.score
s1.gender
# 普通方法
print('age', s2.get_age())
# 类方法
Student.run(23)
s1.run(34)
# 静态方法
s2.do('ase')
Student.do('wefr')
class Price:
def __init__(self, lowprice=0, highprice=0):
if not Price.isvalid(lowprice, highprice):
raise ValueError("Low price should not be higher than high price")
self._low = lowprice
self._high = highprice
@staticmethod
def isvalid(lowprice, highprice):
return True if lowprice <= highprice else False
# 定义访问接口
@property
def price(self):
return self._low, self._high
@price.setter
def price(self, twoprices):
"""
似乎Python的setter只能接受一个参数(除了self外)
所以这里传入了数组
"""
if Price.isvalid(twoprices[0], twoprices[1]):
self._low = twoprices[0]
self._high = twoprices[1]
else:
raise ValueError("Low price should not be higher than high price")
p2 = Price(100.0, 120.0)
print(p2.price)
p2.price = (110, 140)
print(p2.price)
|
9c90ee3369350ee03d06d47ef5041b4b6e816c19 | lguilh3rme/cursoPython | /D27.py | 185 | 3.734375 | 4 | #encoding: utf-8
nm = str(raw_input('Nome completo: ')).strip()#strip tira os espaços
n = nm.split() #.split() fatia
print('Seu primeiro nome é {}. O ultimo é {}'.format(n[0],n[-1])) |
15ed7e12868dac6e9d4c5df5f7fcbff756ab9263 | DobriyD/educational-programm | /week3/3rd symbol del.py | 106 | 3.9375 | 4 | string = input()
string = ''.join([string[i] for i in range(len(string)) if i % 3 != 0])
print(string)
|
ed94979889ff0d8575f8b9d19ea9970341c71989 | AmreshTripathy/Python | /StringModification.py | 304 | 3.703125 | 4 | n = int(input())
for i in range(0, n):
string = input()
for j in range(0, len(string)):
if (j % 2 == 0):
print (string[j],end='')
print(" ",end='')
for j in range(0, len(string)):
if(j % 2 != 0):
print (string[j],end='')
print("")
|
b2c2a67319f73602de956b68050a7bb7be604b5f | Camille-Arsac/python | /car/car.py | 744 | 3.734375 | 4 | class Car:
def __init__(self,
max_speed,
fuel_consumption,
seats):
self.max_speed = max_speed
self.current_speed = 0
self.distance = 0
self.fuel_consumption = fuel_consumption
self.current_fuel = 0
self.seats = seats
self.person_in_car = []
def add_in_car(self, person):
if len(self.person_in_car) < self.seats:
self.person_in_car.append(person)
def remove_in_car(self, person):
if person in self.person_in_car:
self.person_in_car.remove(person)
def advance(self, speed, time):
self.current_fuel -= self.fuel_consumption
self.distance += speed
time -= 1
|
17a674640e3ff6aac77eebddf40be09b279bff65 | RajitPaul11/PythonBasix | /salary.py | 326 | 3.796875 | 4 | class Employee:
salary = 1000
increment = 1.5
@property
def salaryAfterIncrement(self):
return self.salary*self.increment
@salaryAfterIncrement.setter
def salaryAfterIncrement(self, val):
self.increment = val/self.salary
E = Employee()
print(E.salaryAfterIncrement)
E.salaryAfterIncrement=2000
print(E.increment)
|
8897ad019e2072c174e5ef5c98f2dbfd12bb0e0b | Srivathsan97/HackerRank | /Python/5 - Loops/Answer - Loops.py | 603 | 4.1875 | 4 | if __name__ == '__main__':
n = int(input())
if (n<=20 and n>=1):
for i in range (0,n):
print(i*i)
"""
Loops are statements that help us execute statement(s) continously, multiple times, until the condition becomes False.
Different looping statements are : for ; While and nested loops.
Example 1:
for i in range(10):
print(i)
Example 2:
i = 3
while i < 3:
print(i)
i += 1
Resources:
1. http://tutorialspoint.com/python/python_loops.htm
2. http://learnpython.org/en/Loops
3. For Loop : https://www.w3schools.com/python/python_for_loops.asp
""" |
cc3705ee47ae0d195abfd193edfe745de29f2670 | kill4n/SistemasEmbebidos_17_1 | /PyWeather/PyWeather/Unidades.py | 838 | 3.578125 | 4 | # -*- coding: utf-8 -*-
class Unidades:
def __init__(self, distancia, presion, velocidad, temperatura):
"""Representa la entidad de descripción de las unidades de medida."""
self._distancia = distancia
self._presion = presion
self._velocidad = velocidad
self._temperatura = temperatura
@property
def distancia(self):
"""Obtiene las unidades de distancia."""
return self._distancia
@property
def presion(self):
"""Obtiene las unidades de presión."""
return self._presion
@property
def velocidad(self):
"""Obtiene las unidades de velocidad."""
return self._velocidad
@property
def temperatura(self):
"""Obtiene las unidades de temperatura."""
return self._temperatura |
e6ddfd56176f0874a316e2d99bb5a3a4a74d8223 | Emmanuel1399/Projects | /juego.py | 1,732 | 3.5625 | 4 | from random import randint
carton=[[],[],[],[],[]]
def cartonBingo(carton):
randint(0,75)
i=0
while len(carton[4])<5:
while len(carton[i])<5:
num=randint(1,76)
e=0
while e<len(carton):
if num in carton[e]:
num=randint(1,76)
e=0
e+=1
num=num
carton[i].append(num)
i+=1
print(carton)
menu()
def validarNum(carton):
num=int(input("ingrese un numero: "))
i=0
while i<len(carton):
e=0
while e<len(carton[i]):
if num==carton[i][e]:
carton[i][e]="x"
e+=1
i+=1
win=False
j=0
while j<len(carton):
d=0
while d<len(carton[j]):
r=0
while carton[j][r]=="x":
r+=1
if r==5:
win=True
break
d+=1
j+=1
n=0
while n<len(carton):
g=0
while carton[g][n]=="x":
g+=1
if g==5:
win=True
break
n+=1
if win==True:
print("gano")
menu()
else:
validarNum(carton)
def menu():
print("opcion 1) crear carton\n"
"opcion 2) jugar\n"
"opcion 3) salir")
opcion=int(input("ingrese la opcion escogida: "))
if opcion==1:
cartonBingo(carton)
if opcion==2:
if carton[0]!=0:
validarNum(carton)
else:
print("no se ha creado el carton")
menu()
if opcion==3:
print("gracias")
menu() |
112150770059ece12d86d81cba75acb337a238d3 | pezy/AutomateTheBoringStuffWithPython | /practice_projects/regex_search.py | 700 | 4.21875 | 4 | #! python3
'''
regex_search.py - opens all .txt files in a folder and searches for any line
that matches a user-supplied regular expression. The results
should be printed to the screen.
'''
import os
import re
target_folder = input("Enter the target foulder:\n")
os.chdir(target_folder)
target_files = os.listdir(target_folder)
target_files = [target for target in target_files if target.endswith('.txt')]
regex = re.compile(input('Enter the regular expression:\n'))
for file_name in target_files:
file = open(file_name)
for line in file.readlines():
words = regex.findall(line)
if words:
print(file_name + ": " + str(words))
|
233b3bc8b22a97d17af152225951249c10a7c853 | Patrick-Ali/PythonLearning | /Tea_Heat.py | 729 | 3.9375 | 4 | # Tea_Heat.py - Version 1 - Patrick Ali - 11/10/15
# This is how hot the tea is at the beginning
heat = 100
# This ocunts the number of blows it takes for the tea to cool down
count = 0
# This begins the loop that will determine how many blows it takes for the tea to cool
while heat >= 70:
# This performs the calculation on each blow
heat = heat - (heat*10/100)
# This tells the user how hot the tea is now
print ("The current heat of the tea is %" + str(heat))
# This adds one to count for every blow taken so as to get the final count
# on the number of blows it takes
count = count + 1
print ("This is blow number: " + str(count))
if heat == 70:
break
|
e38b5caab3d4a850e41c096f637e099300e9f8d0 | XLPeng57/CSCI416-Intro-to-Machine-Learning | /HW1/gd.py | 1,639 | 4.25 | 4 | import numpy as np
def cost_function( x, y, theta0, theta1 ):
"""Compute the squared error cost function
Inputs:
x vector of length m containing x values
y vector of length m containing y values
theta_0 (scalar) intercept parameter
theta_1 (scalar) slope parameter
Returns:
cost (scalar) the cost
"""
##################################################
# TODO: write code here to compute cost correctly
##################################################
h_theta = np.add(theta0,np.multiply(theta1,x))
cost = 1/2 * np.sum(np.power(np.subtract(h_theta,y),2))
return cost
def gradient(x, y, theta_0, theta_1):
"""Compute the partial derivative of the squared error cost function
Inputs:
x vector of length m containing x values
y vector of length m containing y values
theta_0 (scalar) intercept parameter
theta_1 (scalar) slope parameter
Returns:
d_theta_0 (scalar) Partial derivative of cost function wrt theta_0
d_theta_1 (scalar) Partial derivative of cost function wrt theta_1
"""
# d_theta_0 = 0.0
# d_theta_1 = 0.0
##################################################
# TODO: write code here to compute partial derivatives correctly
##################################################
#
prediction = np.add(np.dot(x,theta_1),theta_0)
d_theta_0 = np.sum(np.subtract(prediction,y))
d_theta_1 = np.sum(x.dot(np.subtract(prediction,y)))
return d_theta_0, d_theta_1 # return is a tuple
if __name__ == "__main__":
|
a544c404fcd4cd6724a5b473d6cec36ad9bd07fa | danikuehler/COVIDtimeseries | /HW4_Q3_Kuehler_Danielle.py | 3,705 | 3.625 | 4 | # Danielle Kuehler
# ITP 449 Summer 2020
# HW4
# Question 3
import pandas as pd
import matplotlib.pyplot as plt
#Read in CSV Files
covidData = pd.read_csv("06-18-2020.csv")
covidConfirmed = pd.read_csv("time_series_covid19_confirmed_US.csv")
covidDeaths = pd.read_csv("time_series_covid19_deaths_US.csv")
pd.set_option("display.max_columns", None)
'''
1. What state in the US currently has the highest number of active cases?
'''
#Drop NaN Values
covidData.dropna(axis=0, inplace=True)
#Match active column with maximum value of active, check if value has max value of active
print("Question 1:\nHighest number of active cases: ", covidData.loc[covidData.Active == covidData.Active.max(), 'Province_State']) #loc fetches province state
'''
2. What state in the US has the highest fatality rate (deaths as a ratio of infection)?
'''
#Highest mortality rate, display:
print("\nQuestion 2:\nHighest fatility rate: ", covidData.loc[covidData.Mortality_Rate == covidData.Mortality_Rate.max(), 'Province_State'])
'''
3. What is the difference in the testing rate between the state that tests the most and the state that tests the least?
'''
#State that tests most
print("\nQuestion 3:\nState that tests the most: ", covidData.loc[covidData.Testing_Rate == covidData.Testing_Rate.max(), 'Province_State'])
#State that tests the least
print("State that tests the least: ", covidData.loc[covidData.Testing_Rate == covidData.Testing_Rate.min(), 'Province_State'])
#Display difference in testing
print("Difference in testing rate:", round(covidData.Testing_Rate.max() - covidData.Testing_Rate.min()), "cases")
'''
4. Plot the number of daily new cases in the US for the top 5 states with the highest confirmed cases (as of today). From March 1 – today. Use Subplot 1.
'''
#Group data by state
sumCases = covidConfirmed.groupby(["Province_State"]).sum().loc[:,"3/1/20":"6/18/20"].reset_index()
#Sort to most cases
high5 = sumCases.sort_values(by=["6/18/20"], ascending=False).head(5)
#Get index of states with highest cases
high5Indexes = high5.set_index("Province_State")
#Count of cases from march 1 through now
x = high5.transpose() #Swap rows and columns
x = x.iloc[1:,:] #All row's except 0th row
x.columns = ['New York','New Jersey','California','Illinois','Massachusetts']
#Plotting
fig = plt.figure()
fig.suptitle('Kuehler_Danielle_HW4\nCOVID19 Data')
ax1 = fig.add_subplot(1,2,1, title="COVID19 Cases") #number of rows, number of columns, first subplot
ax1.plot(x)
#Formatting
ax1.set_xticks(['3/1/20','3/18/20','4/1/20', '4/18/20', '5/1/20', '5/18/20', '6/1/20', '6/18/20'])
ax1.set_xlabel("Date")
ax1.set_ylabel("Number of Cases (Daily)")
ax1.legend(x, loc="upper left")
'''
5. Plot the number of daily deaths in the US for the top 5 states with the highest confirmed cases (as of today). From March 1 – today. Use Subplot 2.
'''
#Group data by state
sumDeaths = covidDeaths.groupby(["Province_State"]).sum().loc[:,"3/1/20":"6/18/20"].reset_index()
#Sort to most cases
top5 = sumDeaths.sort_values(by=["6/18/20"], ascending=False).head(5)
#Get index of states with highest cases
top5Indexes = top5.set_index("Province_State")
#Count of deaths from march 1 through now
a = top5.transpose() #Swap rows and columns
a = a.iloc[1:,:] #All row's except 0th row
a.columns = ['New York','New Jersey','Massachusetts','Illinois','Pennsylvania']
#Plotting
ax2 = fig.add_subplot(1,2,2, title="COVID19 Deaths") #number of rows, number of columns, first subplot
ax2.plot(a)
#Formatting
ax2.set_xticks(['3/1/20','3/18/20','4/1/20', '4/18/20', '5/1/20', '5/18/20', '6/1/20', '6/18/20'])
ax2.set_xlabel("Date")
ax2.set_ylabel("Number of Deaths (Daily)")
ax2.legend(a, loc="upper left")
#Display
plt.show()
|
cc248605baeb95fdfe7b0d4decd57e26e9648990 | BradKentAllen/Red_Letter_Search | /Bible_utilities/WordListUtilities.py | 1,112 | 3.921875 | 4 | '''utilities for working with wordlist files and
dictionaries saved as wordlist
'''
def checkWords(wordListFileName):
'''runs loop to check user entered words if in
the dictionary list file
'exit' to quite
'''
with open(wordListFileName) as file:
wordList = file.read().split()
run = True
while run is True:
checkWord = input('word: ')
if checkWord in wordList:
print(checkWord, ' is in list')
else:
print('NOT in list')
if checkWord == 'exit':
run = False
def HitchcockToList(fileName):
'''converts .txt version of Hitchcock Names in Bible
to python list
Returns a list of names
'''
with open(fileName) as file:
text = file.readlines()
nameList = []
for count, line in enumerate(text):
if count > 10:
if line.isspace() is False:
words = line.split()
if 20 > len(words[0]) > 1:
if words[0].isdigit() is False:
nameList.append(words[0][:-1])
return nameList
|
001584034d2785d6c5426a999956d79e3850260f | stlachman/Sprint-Challenge--Data-Structures-Python | /names/names.py | 7,886 | 4.3125 | 4 | import time
import sys
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
"""Wrap the given value in a ListNode and insert it
after this node. Note that this node could already
have a next node it is point to."""
def insert_after(self, value):
current_next = self.next
#New Next is current value, so previous is current, and next is current next
self.next = ListNode(value, self, current_next)
#If next exists, current Next's prev needs to links to value we're inserting
if current_next:
current_next.prev = self.next
"""Wrap the given value in a ListNode and insert it
before this node. Note that this node could already
have a previous node it is point to."""
def insert_before(self, value):
current_prev = self.prev
self.prev = ListNode(value, current_prev, self)
if current_prev:
current_prev.next = self.prev
"""Rearranges this ListNode's previous and next pointers
accordingly, effectively deleting this ListNode."""
def delete(self):
#If Previous, previous's next now points to this' next, skipping current
if self.prev:
self.prev.next = self.next
#If Next, next's previous now points to this previous, skipping current
if self.next:
self.next.prev = self.prev
"""Our doubly-linked list class. It holds references to
the list's head and tail nodes."""
class DoublyLinkedList:
def __init__(self, node=None):
self.head = node
self.tail = node
self.length = 1 if node is not None else 0
def __len__(self):
return self.length
"""Wraps the given value in a ListNode and inserts it
as the new head of the list. Don't forget to handle
the old head node's previous pointer accordingly."""
def add_to_head(self, value):
if self.head:
current_head = self.head
#insert value before current head, so currentHead is connected to new head
current_head.insert_before(value)
#make head equal to head's previous value
self.head = current_head.prev
else:
self.head = ListNode(value)
self.tail = self.head
self.length += 1
"""Removes the List's current head node, making the
current head's next node the new head of the List.
Returns the value of the removed Node."""
def remove_from_head(self):
current_head = self.head
if current_head is None:
return None
#Reassigning new head
if current_head.next is not None:
self.head = current_head.next
else:
#Only 1 item, so both are None
self.head = None
self.tail = None
self.length -= 1
return current_head.value
"""Wraps the given value in a ListNode and inserts it
as the new tail of the list. Don't forget to handle
the old tail node's next pointer accordingly."""
def add_to_tail(self, value):
#insert after tail
if self.tail:
current_tail = self.tail
current_tail.insert_after(value)
self.tail = current_tail.next
else:
self.tail = ListNode(value)
self.head = self.tail
self.length += 1
"""Removes the List's current tail node, making the
current tail's previous node the new tail of the List.
Returns the value of the removed Node."""
def remove_from_tail(self):
if self.tail:
current_tail = self.tail
current_tail.delete()
self.length -= 1
if current_tail == self.head:
self.head = None
self.tail = None
else:
self.tail = current_tail.prev
return current_tail.value
else:
return None
def contains(self, node):
#Check if node exists in linked list
current_node = self.head
while current_node:
if current_node == node:
return True
current_node = current_node.next
return False
def contains_value(self, value):
current_node = self.head
while current_node:
if current_node.value == value:
return True
current_node = current_node.next
return False
"""Removes the input node from its current spot in the
List and inserts it as the new head node of the List."""
def move_to_front(self, node):
if self.contains(node):
print(self.length)
#Add node to front of list
self.add_to_head(node.value)
print(self.length)
#Delete node
self.delete(node)
print(self.length)
"""Removes the input node from its current spot in the
List and inserts it as the new tail node of the List."""
def move_to_end(self, node):
if self.contains(node):
#add to tail
self.add_to_tail(node.value)
#delete
self.delete(node)
"""Removes a node from the list and handles cases where
the node was the head or the tail"""
def delete(self, node):
if self.contains(node):
if node == self.head:
self.remove_from_head()
elif node == self.tail:
self.remove_from_tail()
else:
#Node.delete does not change the length, but the other two do
node.delete()
self.length -= 1
"""Returns the highest value currently in the list"""
def get_max(self):
max_val = self.head.value
current = self.head
while current is not None:
max_val = max(current.value, max_val)
current = current.next
return max_val
class Queue:
def __init__(self):
# self.size = 0
# Why is our DLL a good choice to store our elements?
self.storage = DoublyLinkedList()
def enqueue(self, value):
self.storage.add_to_tail(value)
def dequeue(self):
return self.storage.remove_from_head()
def len(self):
return len(self.storage)
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
queue = Queue()
queue.enqueue(self)
while queue.len() > 0:
current_node = queue.dequeue()
if value > current_node.value:
if current_node.right is None:
current_node.right = BinarySearchTree(value)
else:
queue.enqueue(current_node.right)
elif value < current_node.value:
if current_node.left is None:
current_node.left = BinarySearchTree(value)
else:
queue.enqueue(current_node.left)
def contains(self, target):
current_node = self
while current_node is not None:
if target == current_node.value:
return True
elif target > current_node.value:
current_node = current_node.right
elif target < current_node.value:
current_node = current_node.left
return False
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
# duplicates = []
# runtime O(n^2)
# for name_1 in names_1:
# for name_2 in names_2:
# if name_1 == name_2:
# duplicates.append(name_1)
duplicates = []
# initialize binary search tree with first value
bst = BinarySearchTree(names_1[0])
# time complexity: O(n log n)
for name_1 in names_1[1:]:
bst.insert(name_1)
for name_2 in names_2:
if bst.contains(name_2):
duplicates.append(name_2)
end_time = time.time()
print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print (f"runtime: {end_time - start_time} seconds")
# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
# What's the best time you can accomplish with no restrictions on techniques or data
# structures? |
2da1c798f4f4076512eb25010afaab134e53df37 | stylesuxx/japybot | /plugin.py | 1,681 | 3.515625 | 4 | import abc
class Plugin(object):
""" This abstact Baseclass has to be implemented by each Plugin. """
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def name(self):
""" The Plugins name. """
pass
@abc.abstractproperty
def description(self):
""" The Plugins description. """
pass
@abc.abstractproperty
def version(self):
""" The Plugins version String. """
pass
@abc.abstractmethod
def help(self, isAdmin):
"""
Return the Helptext.
:param isAdmin: Indicates if the requesting user is an admin
"""
pass
class Command(Plugin):
""" This abstact Baseclass has to be implemented by each Command Plugin. """
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def command(self):
""" The command string. Alphanumeric, lowercase only. """
pass
@abc.abstractproperty
def public(self):
""" Indicates if the reply should be posted to the muc or in private. """
pass
@abc.abstractmethod
def process(self, arguments, isAdmin):
"""
Processes the user input and returns a reply.
:param arguments: Arguments from the request. This is the remaining string after the command
:param isAdmin: True if requesting user is an admin
"""
return
class Parser(Command):
""" This abstract Baseclass has to be implemented by each Parser Plugin. """
@abc.abstractmethod
def parse(self, message):
"""
Parse the message and do whatever you need to do.
:param message: The message to parse
"""
return |
e4f07f441fafc31fb9aba6f5c0741736042e1d3b | zyberguy/learnstreet | /Income Tax Calculator/income_tax-python.py | 881 | 3.96875 | 4 | # This def calculates the tax according to the given tax-structure and returns the tax
def calculate_tax(inc):
inc = int(inc)
tax = 0.0
if inc > 40000:
print inc
tax += (float(30)/float(100)) * (inc-40000)
inc = 40000
if inc > 20000:
tax += (float(20)/float(100)) * (inc-20000)
inc = 20000
if inc > 10000:
tax += (float(10)/float(100)) * (inc-10000)
inc = 10000
return tax
# This def reads a series of incomes from comma separated values in the string text and then formats the income and tax in a table and returns the string
def income_list(text):
result =[]
incomes = text.split(",")
taxes = []
for i in range(0, len(incomes)):
taxes.append(calculate_tax(incomes[i]))
result.append(incomes[i] +"-"+ str(taxes[i]))
return result |
dd9f3bfc118ee6e987b7dee071a7317052b022d8 | user6666666666666/PythonDataScience | /chapter2/Unit10_Regular.py | 933 | 3.9375 | 4 | import re
# 一个非字母数字字符进行划分
result = re.split(r"\W", "Hello, world!")
print(result)
# 合并所有相邻的非字母字符
result = re.split(r"\W+", "Hello, world!")
print(result)
mo = re.match(r"\d+", "067 Starts with a number")
print(mo.group())
mo2 = re.match(r"\d+", "Does not start with a number")
print(mo2)
# 不区分大小写
s = re.search(r"[a-z]+", "0010010 Has at least one 010 letter 0010010", re.I)
print(s.group())
# 区分大小写
s = re.search(r"[a-z]+", "0010010 Has at least one 010 letter 0010010")
print(s.group())
s = re.findall(r"[a-z]+", "0010010 Has at least one 010 letter 0010010", re.I)
print(s)
# print
# 0010010[...]010[...]0010010
s = re.sub(r"[a-z ]+", "[...]", "0010010 has at least one 010 letter 0010010")
print(s)
# print
# 0010010 repl repl repl repl 010 repl repl 0010010
s = re.sub(r"[a-z]+", "repl", "0010010 has at least one 010 letter and 0010010")
print(s) |
5eea12122a9ff7e636d3e6e6d7c81eff21adaa5a | RachelKolk/Intro-Python-I | /src/lists.py | 808 | 4.3125 | 4 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
# YOUR CODE HERE
x.append(4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
# YOUR CODE HERE
x.extend(y)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
# YOUR CODE HERE
x.remove(8)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
# YOUR CODE HERE
x.insert(5, 99)
print(x)
# Print the length of list x
# YOUR CODE HERE
print(len(x))
# Print all the values in x multiplied by 1000
# YOUR CODE HERE
def mult_by_thousand(num):
return num * 1000
multiplied = map(mult_by_thousand, x)
multiplied_list = list(multiplied)
print(multiplied_list) |
27012e2dfa804154558003306f4ffc7ceda40798 | m1xxos/Codestuffff | /Coffee Machine/Problems/What day is it/task.py | 147 | 3.90625 | 4 | time = input()
if 10.30 + float(time) <= 0:
print("Monday")
elif 10.30 + float(time) >= 24:
print("Wednesday")
else:
print("Tuesday")
|
2cb52636dd6b5083a0de4c1e65a981ff037aa5ab | rg98/aoc2020 | /9/code_one.py | 636 | 3.640625 | 4 | #!/usr/bin/env python3.9
import copy
def check_sum(num, numbers):
nums = copy.deepcopy(numbers)
nums.sort()
left = 0
right = len(nums) - 1
while left != right and nums[left] + nums[right] != num:
if nums[left] + nums[right] > num:
right -= 1
else:
left += 1
return left != right
# Read program
numbers = []
with open('in.txt', 'r') as fd:
for line in fd:
num = int(line[:-1])
if len(numbers) == 25:
if not check_sum(num, numbers):
print(num)
break
numbers.pop(0)
numbers.append(num)
|
9524a8d05d2231453104bae6a9bbe92eb6c798e3 | shootsoft/practice | /LeetCode/python/091-120/110-balanced-binary-tree/solution.py | 965 | 3.765625 | 4 | __author__ = 'yinjun'
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
if root == None:
return True
left = self.getHeight(root.left)
right = self.getHeight(root.right)
if left>-1 and right >-1:
return abs(left-right) <= 1
else:
return False
def getHeight(self, root):
if root == None:
return 0
left = self.getHeight(root.left)
right = self.getHeight(root.right)
if left == -1 or right == -1:
return -1
elif abs(left-right) <= 1:
return max(left, right) + 1
else:
return -1 |
d8ec95e09ed2ca7a7916fd181ef0d65fce7dea15 | Prabin-silwal/python-project | /encryption-app-using-python-master/file.py | 2,005 | 3.671875 | 4 | class file():
# print the decode text in the file(message.txt)
@staticmethod
def outputinfile(message):
f=open("D:\Python project\encryption-app-using-python-master/message.txt",'w')
f.write(message)
f.close()
# take input from the file for preview
@staticmethod
def datafromfile(choice=1):
if choice==2:
address="D:\Python project\encryption-app-using-python-master/message.txt"
elif choice==1:
address="D:\Python project\encryption-app-using-python-master/cipher.txt"
f=open(address,"r")
chiper_text=f.readline().replace("\n","")
f.close()
return chiper_text
#take input from file to decrypt
@staticmethod
def datafromfile2(address):
f=open(address,"r")
chiper_text=f.readline().replace("\n","")
f.close()
return chiper_text
# display the encode text in file(chiper.txt)
@staticmethod
def displayfile(chiper):
f=open("D:\Python project\encryption-app-using-python-master/cipher.txt",'w')
f.write(chiper)
f.close()
class raps_file(file):
# display the encode text in file(chiper.txt)
@staticmethod
def displayfile(chiper,key_list,key_list2):
f=open("D:\Python project\encryption-app-using-python-master/cipher.txt",'w')
f.write(chiper+"\n")
for i in range(len(key_list)):
f.write(str(key_list[i])+"\t"+str(key_list2[i])+"\t")
f.close()
# take input from the file
@staticmethod
def datafromfile(address):
key_list,key_list2=[],[]
f=open(address,'r')
chiper=f.readline().replace("\n","")
keys=f.readline().split()
for i in range(len(keys)):
if i%2==0:
key_list.append(int(keys[i]))
else:
key_list2.append(int(keys[i]))
return chiper,key_list,key_list2
class playfair_file(file):
pass
class caesar_file(file):
pass |
12368e6daf5fb7604e616836e8d76d7bb7fd226f | brunofonsousa/python | /pythonbrasil/exercicios/repeticao/ER resp 08.py | 531 | 4.375 | 4 | '''
Faça um programa que leia 5 números e informe a soma e a média dos números.
'''
# Utilizando variável soma
numeros = 5
soma = 0
for i in range(1,numeros + 1):
num = int(input("Digite o %iº número: "%(i)))
soma += num
print("")
print("SOMA: ", soma)
print("MÉDIA: ", soma / numeros)
print("")
# Somando já na variável num
numeros = 5
num = 0
for i in range(1,numeros + 1):
num += int(input("Digite o %iº número: "%(i)))
print("")
print("SOMA: ", num)
print("MÉDIA: ", num / numeros)
print("")
|
43e08c44cd074f6dc14cbf18a94dbb9be35640f0 | anilgursahani/bitesofpy | /68/clean.py | 490 | 3.890625 | 4 | import re
def remove_punctuation(input_string):
"""Return a str with punctuation chars stripped out"""
pattern = ('\W')
nonWordCharPat = re.compile(pattern)
pattern = ('\s')
wsPat = re.compile(pattern)
nonWordChars = re.findall(nonWordCharPat,input_string);
wsChars = re.findall(wsPat, input_string);
charList = [aChar for aChar in input_string if aChar in wsChars or aChar not in nonWordChars]
newString = "".join(charList)
return newString
pass |
c2cec33138ff92062d9d4481f2acdb3660b5fab0 | JasonPBurke/Intro-to-Python-class | /Lab_2/Jason_Burke_Lab2_Part_B.py | 1,110 | 4.28125 | 4 | miles = float(input('OK Nathan, how many miles do you want converted to kilometers? '))
miles_to_kilometers = miles * 1.6
print('Nathan, there are', format(miles_to_kilometers, '.2f'), 'kilometers for every',\
miles, 'miles. Pretty Cool!' )
F = float(input("Give me a temperature in farenheit and I'll convert it to celsius! "))
C = (F - 32) * 5 / 9
print('Got it. When you convert', F, 'degrees farenheit, you get',\
format(C, '.1f'), "degrees celsius. You're welcome!")
gallons = float(input('How many gallons do you have? '))
liters = gallons * 3.9
print('You get', format(liters, '.2f'), 'liters for every', gallons, 'gallons.')
pounds = float(input("Give me a number of pounds and I'll convert them to kilograms: "))
kilograms = pounds * 0.45
print(pounds, 'pounds is equal to', format(kilograms, '.2f'), 'kilograms. Now you know!')
inches = float(input('Give me a number of inches and I will tell you how many centimeters you have! '))
centimeters = inches * 2.54
print ('You have', format(centimeters, '.2f'), 'centimeters in', inches, 'inches. Good bye for now!')
|
f4b8177132f5ed4c011026ae7990cba3befe598b | 1337-L3V1ATH0N/L3V1X | /Createfile.py | 1,752 | 3.546875 | 4 | #! /usr/bin/python3
import os
import time
import subprocess
try:
def help():
print('Usage:-\n\t1 - Creates Files on given path.')
print('\t2 - Creates Folders on given path.')
print('\thelp - Prints this message.')
print('\texit - Exits this program.')
print('\tclear - Clears the screen.')
os.system('clear')
while True:
print('\n\t\t\t===== [ Creator ] =====\n')
create = ['1. Create File','2. Create Folder']
for i in create:
print(i)
choice = input('\n[*] Enter creation : ')
if choice == '1':
print('\n[*] Current Path',os.getcwd())
time.sleep(2)
path = input('\n[*] Where to create file ? Enter Path : ')
os.chdir(path)
print('\n[*] Changed to ',os.getcwd())
file = input('\n[*] Enter your filename with extension :')
subprocess.call(['touch',file])
time.sleep(1)
print('\nFile Created')
elif choice == '2':
print('\n[*] Current Path',os.getcwd())
time.sleep(2)
path = input('\n[*] Where to create folder ? Enter Path : ')
os.chdir(path)
print('\n[*] Changed to',os.getcwd())
folder = input('\n[*] Enter your folder name : ')
subprocess.call(['mkdir',folder])
time.sleep(1)
print('\nFolder Created')
elif choice == 'help':
help()
break
elif choice == 'clear':
os.system('clear')
continue
elif choice == 'exit':
exit(0)
else:
print('\n[!] Unable to understand input...\nExiting')
break
except:
print('\n[!] Encountered Errors... Exiting... ')
pass
|
c404b5233be9173a861919113ad73cae909c5cda | wsgan001/PyFPattern | /Data Set/bug-fixing-2/431042da8ecd7de347b4336d3a2e1f0d1652e8e7-<merge>-bug.py | 1,581 | 3.578125 | 4 |
def merge(self, source, destination, changed):
for (key, value) in source.items():
if isinstance(value, dict):
try:
node = destination.setdefault(key, {
})
except AttributeError:
node = {
}
finally:
(_, changed) = self.merge(value, node, changed)
elif (isinstance(value, list) and (key in destination.keys())):
try:
if (set(destination[key]) != set((destination[key] + source[key]))):
destination[key] = list(set((destination[key] + source[key])))
changed = True
except TypeError:
for new_dict in source[key]:
found = False
for old_dict in destination[key]:
if (('name' in old_dict.keys()) and ('name' in new_dict.keys())):
if (old_dict['name'] == new_dict['name']):
destination[key].remove(old_dict)
break
if (old_dict == new_dict):
found = True
break
if (not found):
destination[key].append(new_dict)
changed = True
elif ((key not in destination.keys()) or (destination[key] != source[key])):
destination[key] = value
changed = True
return (destination, changed)
|
3640940d9126c66bd1c21407bb06908d862b87d5 | neilgupte75/SSW_810_Python-_Stevens | /HW07/HW07_Test_Neil_Gupte.py | 4,454 | 3.71875 | 4 | import unittest
from HW07_Neil_Gupte import HW07
from typing import *
class AnagramListTest(unittest.TestCase):
""" test anagram list function"""
def test_anagram_list(self)->None:
a:str="hello"
b:str="loleh"
self.assertEqual(HW07.anagrams_lst(a,b),True)
self.assertEqual(HW07.anagrams_lst("", ""), True)
self.assertEqual(HW07.anagrams_lst("yup", "yu"), False)
self.assertEqual(HW07.anagrams_lst("12345", "123"), False)
self.assertEqual(HW07.anagrams_lst("12345", "12345"), True)
class AnagramDictTest(unittest.TestCase):
""" test anagram dictionary function"""
def test_anagram_dict(self)->None:
a:str="hello"
b:str="loleh"
self.assertEqual(HW07.anagrams_dd(a,b),True)
self.assertEqual(HW07.anagrams_dd("", ""), True)
self.assertEqual(HW07.anagrams_dd("yup", "yu"), False)
self.assertEqual(HW07.anagrams_dd("12345", "123"), False)
self.assertEqual(HW07.anagrams_dd("12345", "12345"), True)
class AnagramCounterTest(unittest.TestCase):
""" test anagram counter function"""
def test_anagram_counter(self)->None:
a:str="hello"
b:str="loleh"
self.assertEqual(HW07.anagrams_cntr(a,b),True)
self.assertEqual(HW07.anagrams_cntr("", ""), True)
self.assertEqual(HW07.anagrams_cntr("yup", "yu"), False)
self.assertEqual(HW07.anagrams_cntr("12345", "123"), False)
self.assertEqual(HW07.anagrams_cntr("12345", "12345"), True)
class CoversAlphabetTest(unittest.TestCase):
""" test covers_alphabet function """
def test_covers_alph(self)->None:
a:str="AbCdefghiJklomnopqrStuvwxyz"
self.assertEqual(HW07.covers_alphabet(a),True)
self.assertEqual(HW07.covers_alphabet("AbCdefghiJklomnopqrStuvwxyz12344"), True)
self.assertEqual(HW07.covers_alphabet("1bCdefghiJklomnopqrStuvwxz"), False)
self.assertEqual(HW07.covers_alphabet(""), False)
self.assertEqual(HW07.covers_alphabet("The quick brown fox jumps over the lazy dog"), True)
class WebAnalyzerTest(unittest.TestCase):
""" test web_analyzer function """
def test_web_analyzer(self)->None:
weblogs: List[Tuple[str, str]] = [
('Nanda', 'google.com'), ('Maha', 'google.com'),
('Fei', 'python.org'), ('Maha', 'google.com'),
('Fei', 'python.org'), ('Nanda', 'python.org'),
('Fei', 'dzone.com'), ('Nanda', 'google.com'),
('Maha', 'google.com'), ]
weblogs2: List[Tuple[str, str]] = [
('Nanda', 'google.com'), ('Maha', 'google.com'),
('Fei', 'python.org'), ('Maha', 'google.com'),
('Fei', 'python.org'), ('Nanda', 'python.org'),
('Fei', 'dzone.com'), ('Nanda', 'google.com'),
('Maha', 'google.com'),('Anil', 'apple.com'),('zoro', 'zoom.com')]
weblogs3: List[Tuple[str, str]] = [
('Nanda', 'google.com'), ('Maha', 'google.com'),
('Fei', 'python.org'), ('Maha', 'google.com'),
('Fei', 'python.org'), ('Nanda', 'python.org'),
('Fei', 'dzone.com'), ('Nanda', 'google.com'),
('Maha', 'google.com'), ('Anil', 'apple.com'), ('Zoro', 'apple.com')]
weblogs4: List[Tuple[str, str]] = [
('Nanda', 'zcash.com'),('Manda', 'zcash.com'),('Onda', 'zcash.com')]
summary: List[Tuple[str, List[str]]] = [
('dzone.com', ['Fei']),
('google.com', ['Maha', 'Nanda']),
('python.org', ['Fei', 'Nanda']), ]
summary2: List[Tuple[str, List[str]]] = [
('apple.com', ['Anil']),
('dzone.com', ['Fei']),
('google.com', ['Maha', 'Nanda']),
('python.org', ['Fei', 'Nanda']),
('zoom.com', ['zoro'])]
summary3: List[Tuple[str, List[str]]] = [
('apple.com', ['Anil','Zoro']),
('dzone.com', ['Fei']),
('google.com', ['Maha', 'Nanda']),
('python.org', ['Fei', 'Nanda'])]
summary4: List[Tuple[str, List[str]]] = [
('zcash.com', ['Manda','Nanda','Onda']) ]
self.assertEqual(HW07.web_analyzer(weblogs), summary)
self.assertEqual(HW07.web_analyzer(weblogs2), summary2)
self.assertEqual(HW07.web_analyzer(weblogs3), summary3)
self.assertEqual(HW07.web_analyzer(weblogs4), summary4)
if __name__=='__main__':
unittest.main(exit=False,verbosity=2)
|
569c0d050a17494bac05195164cbfa5cbe7cc222 | angOneServe/MyPython100days | /day09/property与setter和getter.py | 965 | 4.0625 | 4 | #@property实际上就是定义了一个属性,如shuxing这个属性外界可以读值,写值
#这个属性可以自定义读写值得一些操作,即使用@shuxing.setter和@shuxing.getter创建同名方法进行设置
class Person:
def __init__(self):
self._name=""
self._age=-1
@property
def name(self):
return self._name
@name.setter
def name(self,name):
self._name="设置器"
@property #定义一个属性
def age(self):
return "年龄为:"+str(self._age)
@age.getter
def age(self): #定义属性的读值
return "你的年龄为:"+str(self._age)
@age.setter #定义属性的写值
def age(self,age):
self._age=age+1
p=Person()
p.name=""
p.age=4 #age属性写值函数被执行,self._age=age+1
print(p.name)
print(p.age)
p._age=55 #直接给_age写值,并不影响属性age的值
print(p.name)
print(p.age) |
a5813e992e21935fd44a7ee70ebfce3bee5f02c4 | adityagandhi007/Python | /Soal no 3.py | 1,419 | 3.859375 | 4 | class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.e1 = None
# Fungsi nemembahkan node baru di tengah"
def Inbetween(self,middle_node,newdata):
if middle_node is None:
print("The mentioned node is absent")
return
NewNode = Node(newdata)
NewNode.nextval = middle_node.nextval
middle_node.nextval = NewNode
# Print linked list
def listprint(self):
printval = self.e1
while printval is not None:
print (printval.dataval)
printval = printval.nextval
list = SLinkedList()
list.e1 = Node("50")
e2 = Node("100")
e3 = Node("200")
e4 = Node("300")
e5 = Node("400")
e6 = Node("500")
list.e1.nextval= e2
e2.nextval = e3
e3.nextval = e4
e4.nextval = e5
e5.nextval = e6
list.Inbetween(e2.nextval,"250") # insert node di antara 200 & 300
list.listprint()
#Memasukkan di antara dua Data Nodes
#Ini melibatkan pengejaran pointer dari simpul tertentu untuk menunjuk ke simpul baru.
#Itu dimungkinkan dengan melewati kedua simpul baru dan simpul yang ada setelah mana simpul baru akan dimasukkan.
#Jadi kita mendefinisikan kelas tambahan yang akan mengubah pointer selanjutnya dari node baru ke pointer berikutnya dari node tengah.
# Kemudian tetapkan node baru ke pointer berikutnya dari node tengah. |
092c9d6e8fe407937a58754901bf433092870b81 | anderportela/Learning--Python3--Curso_em_Video | /Valores únicos em uma Lista.py | 575 | 4.0625 | 4 | valores = []
while True:
n = int(input('\nDigite um valor inédito: '))
if n not in valores:
valores.append(n)
print('Valor adicionado com sucesso...')
else:
n = int(input('\nValor repetido! Digite um valor inédito: '))
r = str(input('Quer continuar? [S/N]: ')).upper()
if r == 'N':
break
elif r == 'S':
continue
else:
r = str(input('Opção Inválida! Digite N ou S: ')).upper()
if r == 'N':
break
valores.sort()
print(f'\nOs valores digitados foram: \033[31m{valores}\033[m')
|
707e565fd96c1d2955dccf533fd96ca11adba925 | nityamall/Python_Projects | /workspace/HelloWorld/New/pattern_3.py | 289 | 3.65625 | 4 | n=input("ENTER THE NO. OF LINES")
n=int(n)
for i in range (1,n+1):
for j in range(i,n):
print(end=" ")
z=0
for k in range (0,i):
z=z+1
print(z,end=" ")
y=i
for o in range (1,i):
y=y-1
print(y,end=" ")
print()
|
775c508072e0c48c3cdf73d83ad89297f796763a | MagdaGruszka/mg_pbd | /CA1/CA1_bigdata.py | 976 | 3.8125 | 4 |
class Calculator(object): #calculator functions in python
def add(self, x, y):
number_type = (int, float, complex)
if isinstance(x,number_type) and isinstance(y,number_type):
return x + y
else:
raise ValueError
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x*y
def divide(self, x,y):
if y == 0:
return 'NaN'
else:
return x/float(y)
def exponent(self, x,y):
return x ** y
def sqrt(self,x):
if x <= 0:
return 'NaN'
else:
return x**0.5
def square(self, x):
return x * x
def cube(self, x):
return x*x*x
def sin(self,x):
try:
return math.sin(x)
except:
raise ValueError
|
ec9ae0f533006c28d8975b1e14f5531b9a6eaab5 | leesusa/connect4-2 | /Connecter/Team8/move_selector_naive.py | 1,024 | 3.875 | 4 | import random
def validMoveRow(grid, col):
'''
Validates that a column has an available space on the game board by checking
top row for empty (row-major format)
:param col: column number
:return: True if column top row is empty, otherwise False
'''
if grid[0][col] == 0:
return True
return False
def validMoveCol(grid, col):
'''
Validates that a column has an available space on the game board by checking
top row for empty (column-major format)
:param col: column number
:return: True if column top row is empty, otherwise False
'''
if grid[col][0] == 0:
return True
return False
def randMove(gridObj):
'''
Generates a random column number in which to drop a game piece
:param grid: game board
:return: valid column number for move
'''
valid = False
while not valid:
col = random.randint(0, gridObj.width - 1)
if validMoveRow(gridObj.grid, col):
valid = True
return col |
2567ef4e8d4378850b6c50a5b1375c3959473649 | elenalb/geekbrains_python | /lesson4/module_functools.py | 403 | 3.625 | 4 | # functools
# reduce()
from functools import reduce
def my_func(el1, el2):
return el1 + el2
print(reduce(my_func, [1, 2, 3]))
# partial()
from functools import partial
new_my_func = partial(my_func, 10)
print(new_my_func)
print(new_my_func(10))
def my_func_1(el1, el2, el3):
return el1 + el2 ** el3
partial_my_func = partial(my_func_1, el1=10, el3=2)
print(partial_my_func(el2=10))
|
1322134d07bb278497db9b2e7e5372580923f079 | vimleshtech/python-tutorial | /Sandbox/ThreadingExample.py | 686 | 3.546875 | 4 | import time
import threading
def print1():
#while True:
for i in range(1,5):
#print('perfrom your job')
print(i)
#time.sleep(3)
def print2():
for j in range(11,15):
print(j)
#time.sleep(3)
def print3():
for j in range(101,105):
print(j)
#time.sleep(3)
#print1()
#print2()
t1 = threading.Thread(target=print1,name="process1")
t2 = threading.Thread(target=print2,name="process2")
t3 = threading.Thread(target=print3,name="process3")
#print()
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
#t1.join(t2) #t2 is dependend on t1
|
2af74f2831b258c20296f6c10e176b109612367e | Hiradoras/Python-Exercies | /29-May-2021/Alphabet war - airstrike - letters massacre.py | 1,868 | 4.21875 | 4 | """
Introduction
There is a war and nobody knows - the alphabet war!
There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. The letters called airstrike to help them in war - dashes and dots are spreaded everywhere on the battlefield.
Task
Write a function that accepts fight string consists of only small letters and * which means a bomb drop place. Return who wins the fight after bombs are exploded. When the left side wins return Left side wins!, when the right side wins return Right side wins!, in other case return Let's fight again!.
The left side letters and their power:
w - 4
p - 3
b - 2
s - 1
The right side letters and their power:
m - 4
q - 3
d - 2
z - 1
The other letters don't have power and are only victims.
The * bombs kills the adjacent letters ( i.e. aa*aa => a___a, **aa** => ______ );
Example
AlphabetWar("s*zz"); //=> Right side wins!
AlphabetWar("*zd*qm*wp*bs*"); //=> Let's fight again!
AlphabetWar("zzzz*s*"); //=> Right side wins!
AlphabetWar("www*www****z"); //=> Left side wins!
"""
def alphabet_war(fight):
result = "Let's fight again!"
left_side = ['s', 'b','p','w']
right_side = ['z','d','q','m']
left_point, right_point = 0,0
centered_fight = fight.center(len(fight)+2)
for i in range(len(fight)):
if fight[i] in left_side and centered_fight[i] != "*" and centered_fight[i+2] != "*":
left_point += left_side.index(fight[i]) + 1
elif fight[i] in right_side and centered_fight[i] != "*" and centered_fight[i+2] != "*":
right_point += right_side.index(fight[i]) + 1
if left_point>right_point:
result = "Left side wins!"
elif right_point>left_point:
result = "Right side wins!"
return result
print((alphabet_war("zzpd**b*spsqqmbb")))
|
8c18290ccada96048498b0d23e9a70eed6d0d20a | varshapwalia/Scrap_data_Basics | /specific_field_fetcher_from-website.py | 2,355 | 4 | 4 | # -------------------fetch fields froma website using a website url--------------------------------------------
# import libraries---
# to fetch webpage ---urllib, requests,to parse html webpage----bs4 n lxml
# to use regular expression---re, to read from csv and write to csv ---csv and pandas.
# to automate the procedure of opening a website and achieving a task (eg. scrapping website/ logging into a webite)---Selenium(python)
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pandas as pd
import requests,re
import bs4 as bs
import csv
import lxml
# path to identify selenium chrome drive in your system
path_to_chrome = 'C:/Users/AliImran/Downloads/chromedriver_win32 (1)/chromedriver'
# open a website using selenium webdrive
browser=webdriver.Chrome(executable_path = path_to_chrome)
# create variables to store the fetched data in list and dictionary
angel_all={}
comp_location=[]
url='https://angel.co/companies'
i=0
# open a webpage using selenium python
browser.get(url)
# sleep for 3 sec to let the page load
time.sleep(3)
num=20
# j=0
# loop through the more button to display result from all the pages(pagination)
while num<=400:
try:
more_button=browser.find_element_by_css_selector('div.more')
more_button.click()
time.sleep(2)
except:
break
num+=20
# to extract the required field, identify specific element locator from the webpage-- using inspect element
# use id/class/css selector/xpath
# use those locators as follows to extact required fields and store them in variables
all_comp_loc=browser.find_elements_by_css_selector('div.column.location div.value div a')
# loop through the variables to extract and append them to a variable list
for loc in all_comp_loc:
loc_text=(loc.text)
try:
if len(loc_text)<=1:
loc_text='Null'
comp_location.append(loc_text)
else:
comp_location.append(loc_text)
except:
continue
# update the list into a dictionary
angel_all.update({'Location': comp_location})
# get the dictionary in a dataframe format using pandas
df= pd.DataFrame(angel_all)
# drop duplicates
df_nod=df.drop_duplicates()
# write the dataframe into csv file
df.to_csv('angel_UAE_startups_city_info-fetch.csv', index=False, encoding="UTF-8")
print df_nod
print 'Done!!'
# done!!!!!!!! |
3665871d7d551a29fe1456fb3dd233bccca72378 | RAFASANT29/repositorio2 | /listasejercicio.py | 99 | 3.796875 | 4 | listas = [0,1,2,3,4,5,6,7,8,9,10]
for n in listas:
if n%3 == 0:
print(n)
|
f60d6960b93fc9a04a60112d838537491bff2b8c | shreyassk18/MyPyCharmProject | /OOPs_concept/Class_Object/named_nameless_objects.py | 305 | 3.796875 | 4 | #when we create an object without a reference, it is called as nameless object
class MyClass:
def myFunc(self):
pass
def display(self,name):
print("Name is :", name)
mc = MyClass() #named object
mc.myFunc()
mc.display("Shreyas")
MyClass().display("Kittur") #nameless object |
15076ff723b2b3e4f0dc675086bf4b4e38ff941f | nervylof/GloAcademy_python | /Урок 13/mini_project01.py | 1,462 | 4.125 | 4 | import random
print('Hello, you came to play the game "Guess the number"')
print('Enter the number to which you would like to guess :) :', end=' ')
n = int(input())
def is_valid(user_input):
global n
if user_input.isdigit():
user_number = int(user_input)
if user_number >= 1 and user_number <= n:
return True
else:
return False
else:
return False
secret_num = random.randint(1, n)
counter = 0
while True:
print('Enter the number:', end=' ')
user_input = input()
if not is_valid(user_input):
continue
user_number = int(user_input)
counter += 1
if secret_num > user_number:
print('The guessed number is greater than the entered number, try again:')
elif secret_num < user_number:
print('The guessed number is less than the entered number, try again:')
if secret_num == user_number:
print('Victory!')
print('You ve got it over with', counter, 'attempts!')
user = int(input('One more time ? if yes then send 1, if not then 0: '))
if user == 1:
print('Enter the number to which you would like to guess :) :', end=' ')
n = int(input())
counter = 0
secret_num = random.randint(1, n)
continue
else:
print('Goodbye! Waiting for you again!')
break
|
ca61aa4d72ba9d41bb4d49ab5b431cc5e7284041 | Snuggle/stringrev | /ReverseIndividualWords/ListReversing.py | 316 | 4.53125 | 5 | #!/usr/bin/env python3
my_input = input("Input string: ").split(" ")
# Split string into list by-spaces.
my_input.reverse()
# This method returns None but reverses the list in-place.
print("Output string: {}".format(" ".join(my_input)))
# Print the reversed output, join/concatenate items with a space in-between.
|
cf5260bde15553b2faf94dbc5beb100663cdc7fb | casseb/fatec.folders | /1º Semestre/Algoritmos/Altura_alunos.py | 497 | 4 | 4 | print('Digite as alturas e idades dos respectivos alunos e digite zero na altura para encerrar')
alturas = []
idades = []
quantidade = 0
while(True):
altura = float(input('Digite a Altura: '))
if(altura == 0 ):
break
alturas.append(altura)
idades.append(float(input('Digite a idade: ')))
media = sum(alturas)/len(alturas)
for i in range(len(alturas)):
if(idades[i]>13 and alturas[i]<=media):
quantidade = quantidade+1
print('Quantidade %i'%(quantidade))
|
844dc046623108c45a77f76aaae5c657dca92779 | lesliecoleman/CSE | /Fast Travel Testing - Leslie Coleman.py | 4,719 | 3.921875 | 4 | class Item(object):
def __init__(self, name):
self.name = name
def take(self):
if len(player_inv) < 15:
print("You grab the %s" % self.name)
player_inv.append(self)
elif len(player_inv) == 15:
print("You don't have space to pick up the %s" % self.name)
class KeyItem(Item):
def __init__(self, name):
super(KeyItem, self).__init__(name)
def take(self):
if len(player_inv) < 15:
print("You grab the %s" % self.name)
player_inv.append(self)
class Map(KeyItem):
def __init__(self, name, description, location):
super(Map, self).__init__(name)
def fast_travel(self):
print("You open the map and see some rooms that are different. There are 2 rooms, Movie Set and Basement"
"")
print("Where would you like to travel?")
room_dictionary = {
'Movie Set': movieset,
'Basement': basement
}
teleport = input(">_")
if teleport in room_dictionary:
print("You are now in(at)the %s " % teleport)
global current_node
current_node = room_dictionary[teleport]
else:
print('Sadly that room does not exist on the map.')
class Room(object):
def __init__(self, name, description, description2, north, south, east, west, northwest, southeast, southwest, up,
down, walls):
self.name = name
self.description = description
self.description2 = description2
self.north = north
self.south = south
self.east = east
self.west = west
self.northwest = northwest
self.southeast = southeast
self.southwest = southwest
self.up = up
self.down = down
self.walls = walls
self.visited = False
def move(self, direction):
global current_node
current_node = globals()[getattr(self, direction)]
LISTOFCOMMANDS = 'North, South, East, West, Northwest, Southeast, Southwest, Up, Down, Look, Quit, Party, Travel'
M_BOX = 'You wake up in a metal box. There is one path to the north. \nYou are wearing leather armor.'
MOVIESET = 'You enter what looks like a movie set. You close your eyes and see the filming of your favorite movie.'
BASEMENT = 'Hey!!! It\'s a basement!!!!'
PARTY = 'You had just defeated the ducks. You walk into a party room to celebrate the win ' \
'\nwith all the people who live in the house. Congrats on beating the game. You did a nice job.'
M_BOX2 = 'You are back in the metal box. Remember there is a path to the north'
m_box = Room('Metal Box', M_BOX, M_BOX2, 'bedroom', '', '', '', '', '', '', '', '', '')
party = Room('Party Central 101', PARTY, '', '', '', '', '', '', '', '', '', '', '')
movieset = Room('Movie Set', MOVIESET, '', '', '', '', '', '', '', '', '', '', '')
basement = Room('Basement', BASEMENT, '', '', '', '', '', '', '', '', '', '', '')
travel_map = Map('Piece of paper', 'You find a map and rooms that you have not seen are on there. You can travel '
'to the rooms by saying travel and then where you want to go.', '')
current_node = m_box
directions = ['north', 'south', 'west', 'east', 'northwest', 'southeast', 'southwest', 'up', 'down']
short_directions = ['n', 's', 'w', 'e', 'nw', 'se', 'sw', 'u', 'd']
is_playing = True
print(LISTOFCOMMANDS)
while is_playing:
# Rom information
print(current_node.name)
if not current_node.visited:
print(current_node.description)
# Input
command = input('>_').lower().strip()
# Pre-processing
if command == 'quit':
print('I am sorry this was hard. I wish you would continue.')
exit(0)
elif command in short_directions:
pos = short_directions.index(command)
command = directions[pos]
# Process input
if command == 'party':
print('Sorry you can not party yet. Beat the ducks and then you can celebrate brave adventurer.')
elif command in directions:
try:
current_node.visited = True
current_node.move(command)
except KeyError:
print("This way is not available. Please try again. Thank You")
elif command == 'travel':
travel_map.fast_travel()
elif command == 'look':
print(current_node.name)
print(current_node.description2)
else:
print("That command is not available. Please try again. Thank You.")
# Handling win conditions
if current_node == party:
print(current_node.name)
print(current_node.description)
is_playing = False
player_inv = []
key_inv = [travel_map]
|
851a6f4f0caec2e57c7bc15cc756378cb1c22a49 | danielhanold/Complete-Python-3-Bootcamp | /09-Built-in Functions/code_examples/zip.py | 415 | 4.5625 | 5 | # Zip two lists together.
x = [1, 2, 3]
y = [4, 5, 6]
result = zip(x, y)
print(result)
print(list(result))
# Zip two lists of different lengths.
x = [1, 2, 3]
y = [4, 5, 6, 7, 8]
print(list(zip(x, y)))
# Zip can be used on dictionaries as well.
d1 = {'a': 1, 'b': 2}
d2 = {'c': 4, 'd': 5}
zipped_keys = zip(d1, d2)
zipped_values = zip(d1.values(), d2.values())
print(list(zipped_keys))
print(list(zipped_values))
|
348ad1fe7a5ada1fd996930be3f03a2e9a7e8181 | minhanhc/chuminhanh-fundamentals-c4e14 | /Fundamentals/session2/if.py | 214 | 4.03125 | 4 | yob = int(input("Your year of birth?"))
age = 2017 - yob
print("Your age:", age)
if age < 10:
print("Baby")
elif age < 20:
print("Teenager")
elif age < 30:
print("Pre-Adult")
else:
print("Adult")
|
9370b31f59c70bffd2b6141abc083460fe590aea | sairampandiri/python | /twoeven.py | 210 | 4 | 4 | # Given two numbers display even numbers between two intervals
a,b=map(int,input().split())
for x in range(a,b):
if(x%2==0 and x<b-2):
print(x,end=" ")
elif(x%2==0 and x<b):
print(x,end="")
|
62082329270ff82e7ddc7778f6ae55b485e8c2db | ponkath/learn-python | /largest so far.py | 257 | 4.03125 | 4 | #loop: the largest so far IDIOM
largest_so_far = -1
print (('Before'), largest_so_far)
for the_num in [9,41,12,3,74,15]:
if the_num > largest_so_far:
largest_so_far = the_num
print (largest_so_far,the_num)
print (('After'),largest_so_far)
|
9f502a993d523e71aa694dc428bf4e25d5de1854 | gabriellaec/desoft-analise-exercicios | /backup/user_198/ch51_2019_12_09_23_12_33_580742.py | 268 | 3.65625 | 4 | def cresc(num):
cresc = []
primeiro = num[0]
cresc.append(primeiro)
maior = primeiro
for i in range(1,len(num)):
proximo = num[i]
if proximo > maior:
cresc.append(proximo)
maior = proximo
return cresc
|
f9ea3cb540b4dfdb52d7f112ed55efab1da70c7e | YaserMarey/tf_exp | /exp_2_cnn_template.py | 9,494 | 3.625 | 4 | # Exp-2
# ### Experiment # 2
# In this experiment I am developing a template like code that has the needed steps to train and classify images.
# I am testing this template with two datasets and I am using CNN as the following:
# Convolutional Neural Network to Detect Handwritten Digits - MINST DataSet http://yann.lecun.com/exdb/mnist/
# Convolutional Neural Network to Detect Fashion Articles - Fashion-MINST DataSet https://github.com/zalandoresearch/fashion-mnist
#
# #### DataSet
# The MNIST dataset contains images of handwritten digits from 0 to 9, with 28x28 grayscale images of 65,000 fashion products from 10 categories, and 6,500 images per category. The training set has 60,000 images, and the test set has 10,000 images.
# Similarly meant as a replacement to MNIST, the Fashion-MNIST dataset contains Zalando's article images, with 28x28 grayscale images of 65,000 fashion products from 10 categories, and 6,500 images per category. The training set has 60,000 images, and the test set has 10,000 images.
#
# #### Process
# - Load data from keras.datasets, normalize and reshape them to x,28,28,1 and convert labels to one hot.
# - continue the following steps using training set only, keep test set for final model verification
# - Construct the CNN according to the architecture detailed above.
# - Compile the model with Stochastic Gradient Descent, learning rate 0.01 and momentum is 0.9
# - Train and cross-validate on 5 folds train, test sets for 10 epochs using a batch size of 128 sample
# - Plot performance, diagnose, tune parameters and archicture, handle overfitting and variance.
# - Repeat until satisfied with the model accuracy.
# - Once done with developing the model as in the above steps:
# - Train the model on the entire training set
# - Test on the test set aside in the first step to verify the model performance.
# - Save the model parameters to the disk
#
# #### Architecture:
# I am using same architecture for both datasets and interestingly it works staifacotry enough without a change from MNIST to Fashion-MNIST datasets:
#
# - Convolutional layer with 32 3×3 filters
# - Pooling layer with 2×2 filter
# - Convolutional layer with 32 3×3 filters
# - Pooling layer with 2×2 filter
# - Dense layer with 100 neurons
# - Dense layer with 10 neurons, to predict the digit for the current image
import numpy as np
import sklearn.model_selection as sklrn
import tensorflow.keras as k
from matplotlib import pyplot
# The process of finding the best model passes through two phases:
# Phase I: We develop the model, by loading data, pre-process it, select architecture and different parameters
# train and test using cross-validation, diagnose, adjust and repeat until you are satisfied with the performance
# This is what is done by the following develop_the_model() function.
# Phase II: We come out of phase I with the right model we want to keep,
# now we fit the model to the entire training set and save the model parameters to the disk
# This is what is done by the save_final_model()
# Here is first Phase - I
def develop_the_model():
# Step - 1
# Load data, Keras already supports API interface for a number of
# wellknown data sets including MNIST.
# This interface allows us to load data as the following:
x_train, y_train, x_test, y_test = load_dataset()
# Step - 2
# Reshape, normalize and/or standardize data
x_train, y_train, x_test, y_test = prepare_data(x_train, y_train, x_test, y_test)
# Step - 3
# develop the model, that is we try to find best parameters by training the model
# and cross-validation
n_folds, epochs, batch_size = 5, 10, 128
model = construct_and_compile_model()
scores, histories = train_and_cross_validate(model, x_train, y_train, n_folds, epochs, batch_size)
# Step - 4 - A
# Diagnose, by observing the leanring curves over epochs for both training and validation for
# different (train, test) folds
plot_learning_curves(histories)
# Step - 4 - B
# summarize performance on test measured by the accuracy at the end
# of the epochs of each (train, test) fold. Summary is presneted as boxplot, and also
# mean, and standard deviation of all measured accuracies over folds
summarize_performance(scores)
return model, x_train, y_train, x_test, y_test, epochs, batch_size
# Then Phase - II
def save_final_model(model, x_train, y_train, epochs, batch_size, filename):
model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, verbose=0)
model.save(filename)
def evaluate_final_model(model, x_test, y_test):
# evaluate model on test dataset
_, acc = model.evaluate(x_test, y_test, verbose=0)
print('Final model accuracy > %.3f' % (acc * 100.0))
return (acc * 100.0)
# ###########################################
def load_dataset():
# (x_train, y_train), (x_test, y_test) = k.datasets.fashion_mnist.load_data()
(x_train, y_train), (x_test, y_test) = k.datasets.fashion_mnist.load_data()
# summarize loaded dataset
print('Train: X={0}, y={1}'.format(x_train.shape, y_train.shape))
print('Test: X={0}, y={1}'.format(x_test.shape, y_test.shape))
# plot_first_few_images(x_train)
return x_train, y_train, x_test, y_test
def prepare_data(x_train, y_train, x_test, y_test):
# Normalize data by dividing on maximum value which makes data values to come in the range [0,1]
x_train = x_train / 255.0
x_test = x_test / 255.0
# Reshape inputs to to 28,28,1 dimensions
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
# Convert class vectors to one hot encoded values
y_train = k.utils.to_categorical(y_train, 10)
y_test = k.utils.to_categorical(y_test, 10)
return x_train, y_train, x_test, y_test
def construct_and_compile_model():
model = k.Sequential(
[
k.Input(shape=(28, 28, 1)),
k.layers.Conv2D(32, kernel_size=(3, 3), activation="relu", kernel_initializer='he_uniform'),
k.layers.MaxPooling2D(pool_size=(2, 2)),
k.layers.Conv2D(32, kernel_size=(3, 3), activation="relu", kernel_initializer='he_uniform'),
k.layers.MaxPooling2D(pool_size=(2, 2)),
k.layers.Flatten(),
k.layers.Dense(100, activation='relu', kernel_initializer='he_uniform'),
k.layers.Dropout(0.4), # add this in Fashion-MNIST Case to regularize CNN
k.layers.Dense(10, activation="softmax")
]
)
model.compile(loss=k.losses.categorical_crossentropy,
optimizer=k.optimizers.SGD(lr=0.01, momentum=0.9),
metrics=['accuracy'])
return model
def train_and_cross_validate(model, x_data, y_data, n_folds, epochs, batch_size):
scores, histories = [], []
# prepare cross validation
kfold = sklrn.KFold(n_folds, shuffle=True, random_state=1)
# enumerate splits
for train_ix, test_ix in kfold.split(x_data):
# select rows for train and test
xx_train, yy_train, xx_test, yy_test = \
x_data[train_ix], y_data[train_ix], x_data[test_ix], y_data[test_ix]
# fit model = train the model
history = model.fit(xx_train,
yy_train,
epochs=epochs, # The more we train the more our model fits the data
batch_size=batch_size, # Smaller batch sizes = samller steps towards convergence
validation_data=(xx_test, yy_test),
verbose=0)
# evaluate model
_, accuracy = model.evaluate(xx_test, yy_test, verbose=0)
print('> %.3f' % (accuracy * 100.0))
# stores scores
scores.append(accuracy)
histories.append(history)
return scores, histories
# plot learning curves
def plot_learning_curves(histories):
for i in range(len(histories)):
# plot loss
pyplot.subplot(2, 1, 1)
pyplot.title('Cross Entropy Loss')
pyplot.plot(histories[i].history['loss'], color='blue', label='train')
pyplot.plot(histories[i].history['val_loss'], color='orange', label='test')
# plot accuracy
pyplot.subplot(2, 1, 2)
pyplot.title('Classification Accuracy')
pyplot.plot(histories[i].history['accuracy'], color='blue', label='train')
pyplot.plot(histories[i].history['val_accuracy'], color='orange', label='test')
pyplot.show()
# box plot summary of model performance
def summarize_performance(scores):
# print summary
print('Accuracy: mean=%.3f std=%.3f, n=%d' % (np.mean(scores) * 100, np.std(scores) * 100, len(scores)))
# box and whisker plots of results
pyplot.boxplot(scores)
pyplot.show()
# Utils
def plot_first_few_images(x_train):
# plot first few images
for i in range(9):
# define subplot
pyplot.subplot(330 + 1 + i)
# plot raw pixel data
pyplot.imshow(x_train[i], cmap=pyplot.get_cmap('gray'))
# show the figure
pyplot.show()
# Call to Phase I: Develpe the model
model, x_train, y_train, x_test, y_test, epochs, batch_size = develop_the_model()
# Call to Phase II: save_final_model() and evaluate_final_model()
save_final_model(model, x_train, y_train, epochs, batch_size, 'fashion_mnist_final_model.h5')
evaluate_final_model(model, x_test, y_test)
|
a2d867532f0e8cb9983f7e6fd8d53b4f6fe17ae6 | telday/discord_music | /bot/command_writer.py | 2,291 | 3.796875 | 4 | """
file: command_writer.py
author: Ellis Wright
language: python 3.6
description: Adds implementation for the bot to add custom commands
within the discord UI (not in code)
"""
from discord.ext import commands
import discord
#TODO add a command to remove commands from the bot. They will have to be removed from the file as well
class CommandWriter:
'''
Class allows users to add their own custom commands to the bot. Allowing
the bot to say things whenever they want so those commands don't need
to be hard programmed in
'''
def __init__(self, bot):
"""
Initialize the commands
bot: The bot this command writer is running on
"""
self.bot = bot
self.commands = self.load_commands()
def load_commands(self):
"""
load the commands this bot has from the commands file and return
them as a dictionary
"""
commands = {}
try:
file_ = open("commands", 'r')
for line in file_.readlines():
if line == "":
continue
commands[line.split("::")[0]] = line.split("::")[1].strip()
except OSError as e:
print("Something bad has happenned")
file_ = open("commands", 'w')
finally:
file_.close()
return commands
def save_command(self, command:str):
"""
Saves a command to the commands file. Must be used because there is no
"on_stop" method for the discord.py api wrapper
"""
file_ = open("commands", 'a')
file_.write(command + "::" + self.commands[command] + "\n")
file_.close()
@commands.command()
async def add_command(self, command:str, output:str):
"""
Actual bot command for adding a new command to the bot
command: The commands name
output: What the bot should reply to the command
"""
if not command in self.commands.keys():
self.commands[command] = output
await self.bot.say("Command added to the bot. {}::{}".format(command, output))
print(command + "::" + output)
self.save_command(command)
else:
await self.bot.say("Sorry the bot already has that command.")
async def process_command(self, channel, command):
"""
Used to process the commands by the main bot file.
channel: The discord.py Channel obj to write to
command: The command passed
"""
if command in self.commands.keys():
await self.bot.send_message(channel, self.commands[command])
|
6b0a178b69e774bce0c5eedc0e7f8dd052050f6a | JUNGEEYOU/Python-Team-Notes | /Sorting/quick.py | 321 | 3.75 | 4 | def quick_sort(a):
if len(a) <= 1:
return a
else:
pivot = a[0]
low = [i for i in a[1:] if i <= pivot]
high = [i for i in a[1:] if i > pivot]
return quick_sort(low) + [pivot] + quick_sort(high)
array = [7, 5, 9, 0, 1, 6, 2, 4, 8]
array = quick_sort(array)
print(array)
|
6712d87d4476a582e03bcb46d73c74d4134c4a8f | gonzalob24/Learning_Central | /Python_Programming/PythonUhcl/Dictionaries/example.py | 961 | 3.640625 | 4 | eng2sp = {}
eng2sp['one'] = 'uno'
eng2sp['two'] = 'dos'
eng2sp['three'] = 'tres'
eng22sp = {'one':'uno', 'two':'dos', 'three':'tres'}
one_dict_keys = eng2sp.keys()
one_list_keys = list(eng2sp.keys())
print(one_list_keys)
print(len(eng2sp))
print(eng2sp)
print(eng22sp)
print("Another example")
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
for akey in inventory.keys(): # the order in which we get the keys is not defined
print("Got key", akey, "which maps to value", inventory[akey])
ks = list(inventory.keys())
print(ks)
print("------")
print(list(inventory.values()))
print(list(inventory.items()))
for (k,v) in inventory.items():
print("Got", k, "that maps to", v)
print("_____")
for k in inventory:
print("Got", k, "that maps to", inventory[k])
print("_____")
print("get method for dictionaries")
print(inventory.get("apples"))
print(inventory.get("cherries"))
print(inventory.get("cherries", 0))
|
3e6907e45fa97f986ed7f4696b5b6ec1ee05483e | aishuse/image2sketch | /pythonProject/sketch.py | 758 | 3.75 | 4 | import cv2
image=cv2.imread("baby.jpg") # read the image
gray_image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # convert the colored image into grayscale
cv2.imwrite("gray.png",gray_image) # save the gray scale image
# apply inverted filter..
inverted_image=255-gray_image
cv2.imwrite("inv.png",inverted_image)
# apply gaussian blur to get blur image
blur=cv2.GaussianBlur(inverted_image,(21,21),0)
cv2.imwrite("blur.png",blur)
#convert blur image to inverted
inv_blur=255-blur
cv2.imwrite("inv_blur.png",inv_blur)
#convert it into sketch image..The sketch can be obtained by performing bit-wise division between the grayscale image and the inverted-blurred image.
sketch=cv2.divide(gray_image,inv_blur,scale=256.0)
cv2.imwrite("sktch.png",sketch)
|
d63e3f16746db0865844d6415023e832a4f100ec | fuzzymuzzywuzzy/leetcode | /python/findNumbers.py | 316 | 3.65625 | 4 | #https://leetcode.com/problems/find-numbers-with-even-number-of-digits/
class Solution(object):
def findNumbers(self, nums):
even = 0
for i, num in enumerate(nums):
if len(str(nums[i]))%2 == 0:
even += 1
else:
even += 0
return even |
b1bda62f25def061c70a1c106210d717df0833fa | unouno1224/workspace | /learning/src/excercise/train3.py | 792 | 3.8125 | 4 | #%%
def is_int(x):
try:
if int(x)==x:
return True
else: return False
except ValueError:
return False
print (is_int(-3.4))
print (is_int('aafdf'))
print (is_int(-2.0))
def digit_sum(x):
total = 0
for i in str(x):
total += int(i)
return total
print (digit_sum(23414))
def is_prime(x):
try:
x=int(x)
except:
ValueError
return '2이상의 정수를 입력하세요'
if x<2:return '2이상의 정수를 입력하세요'
for i in range(2,x):
if x % i == 0:
return '합성수'
else:
return '소수'
x = input('소수판별기, 정수로 입력하세요 :')
print (is_prime(x))
print ('abcde!@#$%'[::-1])
print (type(range(6)))
print ('abcde!@#$%'.strip('ae'))
|
cc68e0b25537a0cfcf070fb3021f750d763a7a64 | monda00/AtCoder | /Sample/bs_abc146.py | 620 | 3.703125 | 4 | a, b, x = map(int, input().split())
def is_ok(mid):
"""二分探索中の判定
Parameters
----------
mid : int
Returns
-------
resutl : bool
"""
if (a * mid) + (b * len(str(mid))) <= x:
return True
else:
return False
def binary_search(ok, ng):
"""二分探索
Parameters
----------
ok : int
ng : int
Returns
-------
ok : int
"""
while ng - ok > 1:
mid = (ok + ng) // 2
if is_ok(mid):
ok = mid
else:
ng = mid
return ok
ans = binary_search(0, 10**9+1)
print(ans)
|
148fa3f3deca76edd84a242dd0ebe3a1b151fe7b | aditp928/cyber-secruitiy- | /1-Lesson-Plans/Unit03-Python/2/11-Stu_ConditionalConundrum/Solved/ConditionalConundrum.py | 1,510 | 4.09375 | 4 | # 1. Not enough shoes!
pairs = 5
if (2 * pairs > 10):
print("Too many shoes!")
else:
print("Not enough shoes!")
# =====================================
# 2. Insecure Password :(
policy_length = 10
if (len("p4ssw0rd") < policy_length):
print("Insecure Password :(")
else:
print("Secure(ish) Password :)")
# =====================================
# 3. The math holds up!
x = 2
y = 5
if ((x**3 >= y) and (y**2 < 26)):
print("The math holds up!")
else:
print("Those values don't meet these conditions.")
# =====================================
# 4. Dan is in group three
name = "Dan"
group_one = ["Greg", "Tony", "Susan"]
group_two = ["Gerald", "Paul", "Ryder"]
group_three = ["Carla", "Dan", "Jefferson"]
if (name in group_one):
print(name + " is in the first group")
elif (name in group_two):
print(name + " is in group two")
elif (name in group_three):
print(name + " is in group three")
else:
print(name + " does not have a group. Poor " + name)
# =====================================
# 5. Can ride bumper cars
height = 66
age = 16
adult_permission = True
if ((height > 70) and (age >= 18)):
print("Can ride all the roller coasters")
elif ((height > 65) and (age >= 18)):
print("Can ride moderate roller coasters")
elif ((height > 60) and (age >= 18)):
print("Can ride light roller coasters")
elif (((height > 50) and (age >= 18)) or ((adult_permission) and (height > 50))):
print("Can ride bumper cars")
else:
print("Stick to lazy river")
|
63cf076fa185b20e094991ad255b0efdf8216ebe | RichieSong/algorithm | /算法/字符串/无重复字符的最长字串.py | 3,297 | 3.875 | 4 | # coding:utf-8
'''
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
'''
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
l = []
res = 0
for i in s:
if i in l:
l = l[l.index(i) + 1:]
l.append(i)
res = res if res > len(l) else len(l)
return res
# def lengthOfLongestSubstring1(self, s):
# """有问题 abb不通过"""
# if not s: return 0
# m = {} #
# start = 0 # 最长无重复字串的首个index
# length = 0 # 最长无重复字串的长度
# for i, ch in enumerate(s):
# if not m.get(ch):
# m[ch] = 0
# if m.get(ch) >= start:
# start = m.get(ch) + 1
# if i - start + 1 > length:
# length = i - start + 1
# m[ch] = i
# return length
def lengthOfLongestSubstring2(self, s):
# 存储历史循环中最长的子串长度
max_len = 0
# 判断传入的字符串是否为空
if s is None or len(s) == 0:
return max_len
# 定义一个字典,存储不重复的字符和字符所在的下标
str_dict = {}
# 存储每次循环中最长的子串长度
one_max = 0
# 记录最近重复字符所在的位置+1
start = 0
for i, m in enumerate(s):
# 判断当前字符是否在字典中和当前字符的下标是否大于等于最近重复字符的所在位置
if m in str_dict and str_dict[m] >= start:
# 记录当前字符的值+1
start = str_dict[m] + 1
# 在此次循环中,最大的不重复子串的长度
one_max = i - start + 1
# 把当前位置覆盖字典中的位置
str_dict[m] = i
# 比较此次循环的最大不重复子串长度和历史循环最大不重复子串长度
max_len = max(max_len, one_max)
return max_len
def lengthOfLongestSubstring3(self, s):
start = maxLength = 0
usedChar = {}
for i in range(len(s)):
if s[i] in usedChar and start <= usedChar[s[i]]:
start = usedChar[s[i]] + 1
else:
maxLength = max(maxLength, i - start + 1)
usedChar[s[i]] = i
return maxLength
if __name__ == '__main__':
s = Solution()
str = "abcbdefhgdgdfg"
print(s.lengthOfLongestSubstring(str))
# print(s.lengthOfLongestSubstring1(str))
print(s.lengthOfLongestSubstring2(str))
print(s.lengthOfLongestSubstring3(str))
|
50f9ec1d8ccbd7a644446484cd61834157a4c85a | yap-yeasin/Computer-Graphics-LAB-1 | /2.Draw A,B with turtle.py | 1,047 | 4.03125 | 4 | import turtle
turtle.title("Draw A, B")
# Circle Part
draw = turtle.Turtle()
# draw.speed(10)
draw.pu()
draw.goto(-200,0) # .goto(x, y)
draw.pendown()
# draw.shape("circle")
draw.pensize(10)
draw.pencolor("blue")
#A
draw.left(60)
draw.forward(200)
draw.right(120)
draw.forward(100)
draw.right(120)
draw.forward(95)
draw.right(180)
draw.forward(95)
draw.right(60)
draw.forward(100)
#B
draw.pu()
draw.left(60)
draw.forward(100)
draw.left(90)
draw.pendown()
draw.forward(180)
draw.right(90)
draw.circle(-45,180) #.circle(radius, extent=None, steps=None) minus diye direction change korchi
draw.right(180)
draw.circle(-45,180)
# B by for loop
draw.pu()
draw.left(180)
draw.forward(150)
draw.left(90)
draw.pendown()
draw.forward(180)
draw.right(90)
x=11
y=15
z=12
#half circle
for i in range(x):
draw.right(y) # rotation / Degree
draw.forward(z) # radius/diameter
draw.right(180)
#half circle
for i in range(12):
draw.right(16) # rotation / Degree
draw.forward(12) # radius/diameter
turtle.done()
# turtle.Screen().exitonclick()
|
30660db23d8d98df487c59ab74e2b45ddce702e0 | rpt5366/Challenge100_Code_Test_Study | /Codesik/DFS/DFS_Basic.py | 290 | 3.640625 | 4 | graph = {
1: [2,3,4],
2: [5],
3: [5],
4: [],
5: [6,7],
6: [],
7: [3],
}
def dfs(v, discovered = []):
discovered.append(v)
for w in graph[v]:
if w not in discovered:
discovered = dfs(w, discovered)
return discovered
print(dfs(1)) |
903656ff43baa3efa402467df78db8b1a331e759 | zezhouliu/datastructures-algorithms | /algorithms/dynamic_programming/spacer.py | 2,006 | 4.09375 | 4 | # Spacer
#
# -----------------------------------
# Takes an essay document of with no spaces and uses dynamic programming
# to readd the spaces such that the entire essay ends up with the correct
# spaces at the right places
import random
import string
WORDLIST_FILENAME = "words.txt"
MAX_LENGTH = 33
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
def spacer ():
# get words
words = loadWords()
# get doc
doc_path = raw_input("file name?: ")
doc = open(doc_path, 'r', 0)
essay = doc.read()
# D[j] implies that chars 1-j is a valid collection of words
D = []
next = 0
essay_length = len(essay)
for x in range(essay_length):
D.append(False)
# D[j] stores whether chars 1-j form a valid cluster of words
# We will first check D[1] and then D[1...j], if it is valid cluster we set D(j) = True
# To check further we loop through each k such that D[1...k] is true and D[k+1,j] belongs in dictionary
for j in range(1, essay_length + 1):
if essay[:j] in words:
D[j] = 0
else:
for k in range(1, j):
if (D[k] is not False) and (essay[k:j] in words):
D[j] = k
break
fixed = ""
start = D[essay_length - 1]
finish = essay_length
while (start is not False):
fixed = essay[start:finish] + " " + fixed
finish = start
start = D[start]
print fixed
|
ca6ee0c693b20eb9d50a3b151e472b04505f0a45 | justzino/algorithms | /Graph/10282.py | 933 | 3.53125 | 4 | import heapq
import sys
def dijkstra(start):
heap_data = []
heapq.heappush(heap_data, (0, start))
distance[start] = 0
while heap_data:
dist, now = heapq.heappop(heap_data)
if distance[now] < dist:
continue
for i in adj[now]:
cost = dist + i[1]
if distance[i[0]] > cost:
distance[i[0]] = cost
heapq.heappush(heap_data, (cost, i[0]))
input = sys.stdin.readline
for _ in range(int(input())):
n, d, start = map(int, input().split())
adj = [[] for i in range(n+1)]
distance = [1e9] * (n+1)
for _ in range(d):
x, y, cost = map(int, input().split())
adj[y].append([x, cost])
dijkstra(start)
count = 0
max_distance = 0
for i in distance:
if i != 1e9:
count += 1
if i > max_distance:
max_distance = i
print(count, max_distance)
|
f88e3cd4e8082ee7708a2ed9c966d627408dc7e1 | masakiaota/kyoupuro | /contests/ABC147/D.py | 1,877 | 3.546875 | 4 | import sys
read = sys.stdin.readline
def read_ints():
return list(map(int, read().split()))
def read_a_int():
return int(read())
def read_matrix(H):
'''
H is number of rows
'''
return [list(map(int, read().split())) for _ in range(H)]
def read_map(H):
'''
H is number of rows
文字列で与えられた盤面を読み取る用
'''
return [read()[:-1] for _ in range(H)]
def read_col(H, n_cols):
'''
H is number of rows
n_cols is number of cols
A列、B列が与えられるようなとき
'''
ret = [[] for _ in range(n_cols)]
for _ in range(H):
tmp = list(map(int, read().split()))
for col in range(n_cols):
ret[col].append(tmp[col])
return ret
n = 0
N = read_a_int()
A = []
for a in read().split():
A.append(int(a))
n = max(n, len(bin(int(a))) - 2)
def ret_binary(a: int): # 逆順で返すことに注意
tmp = bin(a)[2:]
ret_r = [0] * n
for i, t in enumerate(tmp[::-1]):
ret_r[i] = int(t)
return ret_r
def calc_sum(a_binary, n_1_ls, n_1_max):
'''
a_binaryはxorしてから和を取りたい数
n_1_lsは各桁の1の数
n_1_maxは最大1は何個あり得るか
'''
ret = 0
for i, (aa, n_1) in enumerate(zip(a_binary, n_1_ls)):
if aa == 0:
ret += (((2**i) % MOD) * n_1) % MOD
else:
ret += (((2**i) % MOD) * (n_1_max - n_1)) % MOD
return ret
def add_koko(lsa, lsb):
return [a + b for a, b in zip(lsa, lsb)]
MOD = 10**9 + 7
n_1_max = 0
n_1_ls = [0] * n
ans = 0
a_pre = A[N - 1]
a_pre_binary = ret_binary(a_pre)
for a in A[-2::-1]:
a_binary = ret_binary(a)
n_1_ls = add_koko(n_1_ls, a_pre_binary)
n_1_max += 1
tmp = calc_sum(a_binary, n_1_ls, n_1_max)
ans += tmp
ans %= MOD
a_pre_binary = a_binary
print(ans)
|
a2a5e8b1d5881befeeee89bbd1542b76365432ec | Fikialamsyah/DQLAB | /Python Fundamental For Data Science/for.py | 452 | 3.875 | 4 | for i in range(1,6): # perulangan for sebagai inisialisasi dari angka 1 hingga angka yg lebih kecil daripada 6
print("Ini adalah perulangan ke-", i)
count=[1, 2, 3, 4, 5] # element list
for number in range(count): # looping untuk menampilkan semua elemen pada count
print("Ini adalah elemen count : ", number)
# tugas praktek
for i in range (1,11):
if(i%2 == 0):
print("Angka genap",i)
else:
print("Angka ganjil",i)
|
77e277c60738cb7267b99e39559f198529ee5dcd | WojciechMoczydlowski/bin-packing | /BinPacking/algorithms/first_fit_bin_packing.py | 732 | 3.53125 | 4 | # Wojciech Moczydlowski bin packing problem
import time
from BinPacking.algorithms.result import AlgorithmResult
def first_fit_bin_packing(items):
algorithm_start = time.time()
boxes = []
for item in items:
if len(boxes) == 0:
boxes.append(0)
item_is_packed = False
for i in range(len(boxes) - 1):
if boxes[i] + item <= 1:
boxes[i] += item
item_is_packed = True
break
if not item_is_packed:
boxes.append(item)
algorithm_end = time.time()
algorithm_time = algorithm_end - algorithm_start
result = AlgorithmResult("first fit algorithm", len(items), len(boxes), algorithm_time)
return result
|
e7f92f5d8a12c9d4cf9078779458a291163b73ae | Vysogota99/qr_bot | /test.py | 144 | 3.53125 | 4 | import json
str = '{"name": "Alenka", "type": "confectionery", "length": 15, "width": 7, "height": 2}'
obj = json.loads(str)
print(obj['name']) |
987f8f8aafe17d93afbb8ad1af48512adb3411a4 | pawat88/learn | /PythonCrashCourse/ch4/number.py | 205 | 3.96875 | 4 | for value in range (1,5):
print(value)
for value in range (1,6):
print(value)
numbers = list(range(1,6))
print(numbers)
#Event numbers
event_numbers = list(range(2,11,2))
print(event_numbers)
|
4ac41403faac822cb6883e0f7c2a8fd9ac533ca3 | zeppertrek/my-python-sandpit | /pibm-training/sample-programs/if_example_001.py | 338 | 4.125 | 4 | #if_example_001.py
# Get two integers from the user
dividend = int(input('Please enter the number to divide: '))
divisor = int(input('Please enter dividend: '))
# If possible, divide them and report the result
if divisor != 0:
quotient = dividend/divisor
print(dividend, '/', divisor, "=", quotient)
print('Program finished')
|
7cc78a3103a70db68c5b70174dcc84c454158bcc | Umang070/Python_Programs | /for_string.py | 230 | 3.6875 | 4 | # name="umang"
# for i in range(len(name)):
# print(name[i]) //common for all language
print(i,end=",")
# no=input("enter a number")
# total=0
# for i in no:
# total+=int(i)
# print(total) |
385219e026913253bb9a6ede700f54b5262cc45c | altoid/misc_puzzles | /py/heaps_algorithm.py | 727 | 3.53125 | 4 | #!/usr/bin/env python
def generate(k, arr, level):
global nswaps
if k == 1:
# print('....' * level, end=' ')
print(arr)
pass
else:
for i in range(k):
# print('----' * level, end=' ')
# print(arr)
generate(k - 1, arr, level + 1)
if i < k - 1:
if k % 2 == 0:
arr[i], arr[k - 1] = arr[k - 1], arr[i]
else:
arr[0], arr[k - 1] = arr[k - 1], arr[0]
nswaps += 1
# print('====' * level, end=' ')
# print(arr)
if __name__ == '__main__':
nswaps = 0
arr = [1, 2, 3]
generate(len(arr), arr, 0)
print("nswaps = %s" % nswaps) |
d0fc74c4c704062e6822a48fd5239b52390fa3a3 | EllieSky/PythonBootcamp_Summer2021 | /tests/class_intro/test_lesson_3.py | 896 | 3.640625 | 4 | traffic_light = True
# traffic_light_color = get_color()
traffic_light_color = "off"
if traffic_light and traffic_light_color == 'red' and traffic_light == 'flashing':
print("Pause 3 seconds")
elif traffic_light and traffic_light_color == 'red':
print("Stop until green")
elif traffic_light and traffic_light_color == 'yellow':
print("Slow down")
else:
print("keep going")
data = ["word", 34, False, 0.99]
for count, item in enumerate(data):
print(f"The value '{item}' is of datatype '{type(item)}' and is located at index '{count}'")
# ls1 = []
# for item in data:
# ls1.append(str(item))
ls1 = [str(x) for x in data]
print(data)
print(ls1)
for item in {'name': 'Jane', 'age': 12, 'id': '123-45-6789'}.items():
print(f"{item[0]} is {item[1]}")
for key, value in {'name': 'Jane', 'age': 12, 'id': '123-45-6789'}.items():
print(f"{key} is {value}")
|
041680b99e2af7ad8deb7cf36c7d34c127aac9ed | jhe226/BOJ-Python | /[21단계]이분탐색/210812_1920/수찾기_02.py | 525 | 3.6875 | 4 | import sys
def binary_search(arr, target, start, end):
while start <= end:
mid = (start+end)//2
if arr[mid] == target:
return 1
elif arr[mid] > target:
end = mid - 1
else:
start = mid + 1
return 0
n = int(sys.stdin.readline())
N = list(map(int, sys.stdin.readline().split()))
N.sort()
m = int(sys.stdin.readline())
M = list(map(int, sys.stdin.readline().split()))
for i in range(m):
print(binary_search(N, M[i], 0, n-1)) |
63c1ba296f7601c8fd6cc49ab6688de50caf26f9 | suhassrivats/Data-Structures-And-Algorithms-Implementation | /Problems/Leetcode/643_MaximumAverageSubarrayI.py | 978 | 3.65625 | 4 | # Brute Force
class Solution:
"""
Time complexity: O(n * k)
Space complexity (auxiliary): O(1)
"""
def findMaxAverage(self, nums: List[int], k: int) -> float:
result = []
for i in range(len(nums)-k+1):
total = 0
for j in range(i, i+k):
total += nums[j]
result.append(total/k)
return max(result)
# Optimized - Sliding window
class Solution:
"""
Time complexity: O(n)
Space complexity (auxiliary): O(1)
"""
def findMaxAverage(self, nums: List[int], k: int) -> float:
result = float('-inf')
window_start, window_sum = 0, 0.0
for window_end in range(len(nums)):
window_sum += nums[window_end]
if window_end >= k-1:
window_avg = window_sum/k
result = max(result, window_avg)
window_sum -= nums[window_start]
window_start += 1
return result
|
783244603f9b1bd0f8555f590a8f009b73270028 | ssbagalkar/PythonDataStructuresPractice | /DP-aditya-verma-playlist/LCS/08_min_number_of_del_to_make_palindrome.py | 2,780 | 4.03125 | 4 | """
Problem:
Minimum number of deletions to make a string palindrome
Given a string of size ‘n’. The task is to remove or delete minimum number of
characters from the string so that the resultant string is palindrome.
Example:
Input : s = "aebcbda", output = 2
Remove characters 'e' and 'd'
Resultant string will be 'abcba'
which is a palindromic string
Problem Link: https://www.geeksforgeeks.org/minimum-number-deletions-make-string-palindrome/
Video link: https://www.youtube.com/watch?v=CFwCCNbRuLY&list=PL_z_8CaSLPWekqhdCPmFohncHwz8TY2Go&index=28
Complexity Analysis:
n is length of longest string
Time Space
Recursion O(2^n) O(1)
Memoization O(n^2) O(n^2)
Tabular O(n^2) O(n^2 ) ?
Verified in Leetcode - ?
Note: The solution is exactly the same if they ask for min number of insertions as well
"""
def min_del_palindrome_recursion(str_one, str_two, n, m):
# Base condition
if n == 0 or m == 0:
return 0
# From choice diagram
if str_one[n-1] == str_two[m-1]:
return 1 + min_del_palindrome_recursion(str_one, str_two, n-1, m-1)
else:
return max(min_del_palindrome_recursion(str_one, str_two, n-1, m), min_del_palindrome_recursion(str_one, str_two, n, m-1))
def min_del_palindrome_memoization(str_one, str_two, n, m, memo):
# Base Condition and checking
if memo[n][m] != 0:
return memo[n][m]
if n == 0 or m == 0:
return 0
# From choice diagram
if str_one[n - 1] == str_two[m - 1]:
memo[n][m] = 1 + min_del_palindrome_memoization(str_one, str_two, n - 1, m - 1, memo)
else:
memo[n][m] = max(min_del_palindrome_memoization(str_one, str_two, n - 1, m, memo),
min_del_palindrome_memoization(str_one, str_two, n, m - 1, memo))
return memo[n][m]
def min_del_palindrome_tabular(str_one, str_two, n, m):
dp = [[0 for _ in range(m+1)] for _ in range(n+1)]
for ii in range(1, n+1):
for jj in range(1, m+1):
if str_one[ii-1] == str_two[jj-1]:
dp[ii][jj] = 1 + dp[ii-1][jj-1]
else:
dp[ii][jj] = max(dp[ii-1][jj], dp[ii][jj-1])
return dp[n][m]
s1 = "aebcbda"
s2 = s1[::-1]
n = len(s1)
m = len(s2)
print("Recursion Results:")
print(f"Min Deletions-->{n-min_del_palindrome_recursion(s1, s2, n, m)}")
print(" ------------------------------------------- ")
print("Memoization Results:")
memo = [[0 for _ in range(m+1)] for _ in range(n+1)]
print(f"Min Deletions-->{n -min_del_palindrome_memoization(s1, s2, n, m, memo)}")
print(" --------------------------------------------- ")
print("Tabular Results:")
print(f"Min Deletions-->{m -min_del_palindrome_tabular(s1, s2, n, m)}")
|
281af27a163bcec2def22a166c00d0f24356bce4 | erjan/coding_exercises | /find_xor_sum_of_all_pairs_bitwise_and.py | 1,166 | 4.25 | 4 | '''
The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.
For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.
Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.
Return the XOR sum of the aforementioned list.
'''
class Solution:
#example 1
#result =[(1&6)^(1&5)^(2&6)^(2&5)^(3&6)^(3&5)]
\ / \ / \ /
# (1&(6^5)) ^ (2&(6^5)) ^ (3&(6^5))
\ | /
\ | /
\ | /
\ | /
# ((1^2^3) & (6^5))
def getXORSum(self, a, b):
x = 0
for i in range(len(a)):
x = x ^ a[i]
y = 0
for j in range(len(b)):
y = y ^ b[j]
return x & y
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.