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 |
|---|---|---|---|---|---|---|
b42337083c1ced5e502db36d46e6c64c6a04fe0d | csmooremac/Python | /WhatCollegeAttending.py | 453 | 4.375 | 4 | # This small program will ask the user what college they are or plan on attending
# A description statement will explain why the user is attending the college
# The 2 answers are put together to print out a complete sentance.
college = input('What college are you attending, or plan on attending?')
description = input("Why are you attending" + college + "?")
collegeStatement = ('I am attending' + college + description)
print(collegeStatement)
|
eb31eb97b410174925554271d2ac6b688fbe7300 | abhicse32/SPOJ_codes | /BISHOPS.py | 109 | 3.921875 | 4 | while True:
try:
num=input()
except:
break;
else:
if num==1:
print "1"
else:
print(2*num-2)
|
648471d3476db409fa3fef0753477245602bd317 | behlmann/AdventOfCode_2020 | /10.py | 823 | 3.5625 | 4 | """Simple script to solve Day 10"""
# === Load input file
from sys import argv, exit
fName = 'input/10.txt' if len(argv)<2 else argv[1]
try:
fIn = open(fName,'r')
except FileNotFoundError:
print("Error in {}: File {} was not found".format(__file__, fName))
exit(-1)
adapters = [int(ll.strip()) for ll in fIn.readlines()]
adapters.sort()
maxJolts = adapters[-1]+3
adapters.append(maxJolts)
nAdapters = len(adapters)
adapters.insert(0,0)
dJolts = [adapters[j+1]-adapters[j] for j in range(nAdapters)]
nd3, nd1 = dJolts.count(3), dJolts.count(1)
print("Part 1:",nd3 * nd1)
print(nAdapters)
print([dJolts.count(x) for x in range(5)])
nRoutes = [0] * (maxJolts+1)
nRoutes[0] = 1
for j in range(1,maxJolts+1):
if j in adapters:
jMin = max(0,j-3)
nRoutes[j] = sum(nRoutes[jMin:j])
print("Part 2:",nRoutes[maxJolts]) |
88b885214ee98b609821be0aa08149806fc3308f | BorisDundakov/Python--Programming-Basics | /05. While Loop - Lab/05. Account Balance.py | 373 | 3.953125 | 4 | command = (input())
total_sum = 0
while command != "NoMoreMoney":
command = float(command)
if command >= 0:
print(f"Increase: {command :.2f}")
total_sum += command
command = input()
else:
print("Invalid operation!")
print(f"Total: {total_sum}")
break
else:
print(f"Total: {total_sum :.2f}")
|
9d4605572df278c666498520398f9ca7e47c350a | RAJANNITCS/Pyhton_practice | /class_variables.py | 244 | 4.03125 | 4 | class Circle:
pi=3.14
def __init__(self,radius):
self.radius=radius
def calc_circumference(self):
return 2*self.radius*self.pi
# Circle.pi=7.4
c=Circle(2)
c.pi=23
print(c.calc_circumference())
print(c.__dict__) |
2a03b64bad069cc691e4028380b96009c8fcfcec | rudyard2021/math-calculator | /tests/main.py | 963 | 3.703125 | 4 | import unittest
from source.function import Function
class TestFunction(unittest.TestCase):
def __init__(self, methodName):
super().__init__(methodName)
self.function = Function()
def test_operators(self):
self.function.start("---3+11-9*5/-15")
self.assertEqual(self.function.f(), 11)
def test_variables(self):
self.function.start("3x^2-8x-10")
self.assertEqual(self.function.f({"x":2}), -14)
self.function.start("-10^y+-raiz(x)+raiz(8;3)")
self.assertEqual(self.function.f({"y":2, "x":36}), -104)
def test_functions(self):
err = self.function.start("sin(pi/2)+cos(2pi)+abs(-3)*5-4!")
self.assertEqual(self.function.f(), -7)
def test_summa(self):
err = self.function.start("summa(2^x;x;1;5)+root(125;3)")
self.assertEqual(self.function.f(), 67)
if __name__ == "__main__":
unittest.main("")
# python -m unittest tests/test_something.py |
9d04508b129b4d15c2d7c96219a7300d85c6fd8d | kilura69/softuni_proj | /2_advanced/exam_prep/2020-08-19-01_taxi_express.py | 2,181 | 4.09375 | 4 |
'''
You will receive a list of the cutomers (numbers seperated by comma and space ", ")
and list of your taxis (numbers seperated by comma and space ", ").
-- Each number from the customer list represents how much time it takes to drive the customer to his/her destination.
-- Each number from the taxis list represents how much time they can drive, before they need to refill their tanks.
-- Keep track of the total time passed to drive all the customers to their destinations (values of all customers).
-- Each time you tend customers you should put the first customer in the last taxi until there are no customers left.
- If the taxi can drive the customer to his/her destination, he does and
- You must add the time passed to drive the customer to his/her destination to the total time.
- Remove both the customer and the taxi.
- If the taxi cannot drive the customer to his/her destination,
leave the customer at the beginning of the queue and remove the taxi.
At the end if you have successfully driven all the customers to their destinations,
print "All customers were driven to their destinations Total time: {total_time} minutes"
Otherwise, if you ran out of taxis and there are still some customers left print
"Not all customers were driven to their destinations Customers left: {left_customers joined by ", "}""
'''
from collections import deque
customers = deque([int(i) for i in input().split(", ")])
taxis = [int(i) for i in input().split(", ")]
#print(customers)
#print(taxis)
total_drive = 0
taxis_left = True
while customers:
if len(taxis) > 0:
customer = customers[0]
taxi = taxis[-1]
if taxi >= customer:
total_drive += customer
customers.popleft()
taxis.pop()
else:
taxis.pop()
else:
taxis_left = False
break
if len(customers) == 0:
print("All customers were driven to their destinations")
print(f'Total time: {total_drive} minutes')
else:
print('Not all customers were driven to their destinations')
print(f'Customers left: {", ".join([str(c) for c in customers])}')
|
12af40abe838be1aca5b8a91b2bdaeca58977f99 | hdjewel/lettercount | /lettercount.py | 535 | 3.625 | 4 | from sys import argv
import string
def process_input_file(filename):
line = open(filename)
line = line.read()
for char in line:
index = ord(string.lower(char)) - 97
alpha_table[i] += 1
def setup_alphabet_table():
# alphabet=[abcdefghijklmnopqrstuvwxyz]
alpha_table = []
for i in range(26):
print i
alpha_table[i] = 0
def count_letters_in_the_file(argv):
script, filename = argv
process_input_file(filename)
def main():
setup_alphabet_table()
count_letters_in_the_file(argv)
if __name__ == "__main__":
main() |
acbaaa488910dd4d103e43b6cb1006c290f671df | ShashankNagraj/Python-Projects | /tictactoe.py | 2,958 | 4 | 4 | import random
def DisplayBoard(board):
#
# the function accepts one parameter containing the board's current status
# and prints it out to the console
#
print("+-------+-------+-------+")
print("| | | |")
print("| "+str(board[1])+" | "+str(board[2])+" | "+str(board[3])+" |")
print("| | | |")
print("+-------+-------+-------+")
print("| | | |")
print("| "+str(board[4])+" | "+str(board[5])+" | "+str(board[6])+" |")
print("| | | |")
print("+-------+-------+-------+")
print("| | | |")
print("| "+str(board[7])+" | "+str(board[8])+" | "+str(board[9])+" |")
print("| | | |")
print("+-------+-------+-------+")
def EnterMove(board):
#
# the function accepts the board current status, asks the user about their move,
# checks the input and updates the board according to the user's decision
#
while(True):
move=int(input("Enter your move: "))
if 0<move<10:
if board[move]!="O" and board[move]!="X":
board[move]="O"
return
def MakeListOfFreeFields(board):
# the function browses the board and builds a list of all the free squares;
# the list consists of tuples, while each tuple is a pair of row and column numbers
#
lst=[]
for values in board:
if values not in ["O","X"]:
lst.append(values)
return lst
def VictoryFor(board, sign):
if(board[1]==sign and board[2]==sign and board[3]==sign):
return True
if(board[4]==sign and board[5]==sign and board[6]==sign):
return True
if(board[7]==sign and board[8]==sign and board[9]==sign):
return True
if(board[1]==sign and board[4]==sign and board[7]==sign):
return True
if(board[2]==sign and board[5]==sign and board[8]==sign):
return True
if(board[3]==sign and board[6]==sign and board[9]==sign):
return True
if(board[1]==sign and board[5]==sign and board[9]==sign):
return True
if(board[3]==sign and board[5]==sign and board[7]==sign):
return True
def DrawMove(board):
while(True):
comp=random.randrange(1,10)
if board[comp]!="O" and board[comp]!="X":
board[comp]="X"
return
board=[value for value in range(10)]
board[5]="X"
DisplayBoard(board)
while(True):
EnterMove(board)
DisplayBoard(board)
if VictoryFor(board,"O"):
print("You won!")
break
if(len(MakeListOfFreeFields(board))==0):
print("GameOver")
break
DrawMove(board)
DisplayBoard(board)
if VictoryFor(board,"X"):
print("Computer won!")
break
if(len(MakeListOfFreeFields(board))==1):
print("GameOver")
break
|
1dfc9193a698e711026153aab7b8f47c758fc6ab | asheed/tryhelloworld | /excercise/ex127.py | 331 | 3.6875 | 4 | number = 48
print("숫자 맞추기 게임에 오신 것을 환영합니다.")
guess = int(input("1부터 100 사이의 숫자를 추측해보세요: "))
if number == guess:
print("맞았습니다.")
else:
print("틀렸습니다.")
print("정답은 {}입니다.".format(number))
print("게임이 종료되었습니다.")
|
bb4e3f8242ce4d903d63d6979f23e152e7bd4b5d | omarchq/clase4 | /automovil_con_metodos_de_clase.py | 571 | 3.6875 | 4 | class auto():
gasolina=0
"""Abstracion a objeto de un auto, e
sta clase va a arrancar segun su nivel de gasolina"""
def __init__(self,gasolina):
auto.gasolina= gasolina
print "tenemos", gasolina, "Litros"
@classmethod
def arrancar (cls,gasolina):
if gasolina >0:
print "arranca"
else:
print "NO arranca"
@classmethod
def conducir(cls,gasolina):
#while(self.gasolina>0):
while gasolina>0:
print "Quedan", gasolina, "Litros"
gasolina -=1
else:
print "El auto no se mueve"
"""x=auto(10)
x.arrancar()
x.conducir()""" |
b923b5a98ad98e7970ca99e04b7c88b6f1f95586 | daisuke834/exercise_algorithm_python | /src/B_GRL_1_A_Dijkstra.py | 2,517 | 3.515625 | 4 | import sys
import heapq
class Edge:
def __init__(self, vertex_to, weight):
self.vertex_to = vertex_to
self.weight = weight
class Vertex:
def __init__(self):
self.distance = sys.maxsize
self.fixed: bool = False
self.edges_from_this_vertex = []
class DijkstraAlgorithm:
def __init__(self, number_of_vertices):
self._number_of_vertices = number_of_vertices
self._number_of_edges = 0
self._vertices = [Vertex() for _ in range(number_of_vertices)]
self._priority_queue = []
heapq.heapify(self._priority_queue)
def add_vertex(self, from_index, to_index, weight):
self._vertices[from_index].edges_from_this_vertex.append(Edge(to_index, weight))
def calculate_shortest_paths(self, start_vertex_index):
self._vertices[start_vertex_index].distance = 0
heapq.heappush(self._priority_queue, (self._vertices[start_vertex_index].distance, start_vertex_index))
while len(self._priority_queue) > 0:
shortest_vertex_distance, shortest_vertex_index = heapq.heappop(self._priority_queue)
self._vertices[shortest_vertex_index].fixed = True
for c_edge in self._vertices[shortest_vertex_index].edges_from_this_vertex:
if not self._vertices[c_edge.vertex_to].fixed:
distance_candidate = shortest_vertex_distance + c_edge.weight
if distance_candidate < self._vertices[c_edge.vertex_to].distance:
self._vertices[c_edge.vertex_to].distance = distance_candidate
heapq.heappush(self._priority_queue, (distance_candidate, c_edge.vertex_to))
def print(self):
for c_vertex in self._vertices:
if c_vertex.distance == sys.maxsize:
print('INF')
else:
print(c_vertex.distance)
def call_dijkstra_algorithm():
inputs = list(map(int, input().strip().split(' ')))
number_of_vertices = inputs[0]
number_of_edges = inputs[1]
start_vertex_index = inputs[2]
dijkstra = DijkstraAlgorithm(number_of_vertices)
for _ in range(number_of_edges):
inputs = list(map(int, input().strip().split(" ")))
from_index = inputs[0]
to_index = inputs[1]
weight = inputs[2]
dijkstra.add_vertex(from_index, to_index, weight)
dijkstra.calculate_shortest_paths(start_vertex_index)
dijkstra.print()
if __name__ == '__main__':
call_dijkstra_algorithm()
|
ecc66cf107acc4da5a1d4264f240d14c2fdbe224 | daiki1998/python_library | /graph/kruskal.py | 2,499 | 3.59375 | 4 | """
計算量
O(ElogE)
辺の数が頂点に比べて少ないときに優位
1. 辺集合Eをコストの小さい順にソート
2. 残っている辺から最小の辺を取り出す.
3. 2で選んだ辺を追加しても閉路にならない(UnionFind)なら追加
4. 2-3をV-1個の辺を選ぶまで続ける.
"""
from collections import defaultdict
class UnionFind():
# indexの0は無視する
def __init__(self, n):
self.n = n
self.parents = [-1 for _ in range(n+1)]
def find(self, x): # xの親を探す O(1)
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def same(self, x, y): # xとyが同じグループか O(1)
return self.find(x) == self.find(y)
def union(self, x, y): # xとyを同じグループにする O(1)
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def member(self, x): # xと同じグループの番号を返す O(N)
root = self.find(x)
return [i for i in range(1, self.n+1) if self.find(i) == root]
def all_group_members(self): # すべての要素の同じgroupのmemberを返す O(N)
group_members = defaultdict(list)
for member in range(1, self.n+1):
group_members[self.find(member)].append(member)
return group_members
def roots(self): # 根となっている番号を返す O(N)
return [i for i in range(1, self.n+1) if self.find(i) == i]
def num_group(self): # groupの数を返す O(N)
return len(self.roots())
def size(self, x): # xのgroupの要素数を返す O(1)
return -self.parents[self.find(x)]
"""
graphは[cost, nodeA, nodeB]の多次元配列
return: 使用する[cost, nodeA, nodeB]の集合,最小コスト
"""
def kruskal(N, graph):
uf = UnionFind(N)
edges = []
sm_cost = 0
graph.sort(reverse=True)
while len(edges) < N-1:
now = graph.pop()
if not uf.same(now[1], now[2]):
uf.union(now[1], now[2])
edges.append(now)
sm_cost += now[0]
return edges, sm_cost
V, E = map(int, input().split())
graph = []
for _ in range(E):
s, t, w = map(int, input().split())
graph.append([w, s, t])
_, res = kruskal(V, graph)
print(res) |
a4447bebeb2ea9df759e2793cc445df844279fb1 | yenchanglu/takingYourOrder | /food_order.py | 6,701 | 3.671875 | 4 | import pyttsx3
list_food = []
list_drink = []
list_item_price = [0] * 100
class ORDER:
def reset():
global list_drink, list_food, list_item_order, list_item_price
list_item_order = [0] * 100
def welcome():
bot = Speaking()
bot.speak("Hello How are you today")
bot.speak("What would you like to have")
ORDER.process_order()
def process_order():
while True:
bot = Speaking()
print("*" * 26 + " ORDER FOOD & DRINK " + "*" * 26)
print(" |NO| |FOOD NAME| |PRICE| | |NO| |DRINK NAME| |PRICE|")
i = 0
while i < len(list_food) or i < len(list_drink):
var_space = 1
if i <= 8:
var_space = 2
if i < len(list_food):
food = " (" + str(i + 1) + ")" + " " * var_space + str(list_food[i]) + " | "
else:
food = " " * 36 + "| "
if i < len(list_drink):
drink = "(" + str(41 + i) + ")" + " " + str(list_drink[i])
else:
drink = ""
print(food, drink)
i += 1
print("\n (P) PAYMENT (M) MAIN MENU (C) CHANGE ORDER (E) EXIT\n" + "_" * 72)
input_ops = input("Please Select Your Operation: ").upper()
bot.speak("Please Select Your Operation")
if (input_ops == 'P'):
print("\n" * 10)
ORDER.bill_please()
break
if (input_ops == 'M'):
print("\n" * 10)
ORDER.process_order()
break
if (input_ops == 'C'):
ORDER.modify_order()
break
if (input_ops == 'E'):
ORDER.cancel_order()
break
try:
int(input_ops)
if ((int(input_ops) <= len(list_food) and int(input_ops) > 0) or (int(input_ops) <= len(list_drink) + 40 and int(input_ops) > 40)):
try:
print("\n" + "_" * 72 + "\n" + str(list_food[int(input_ops) - 1]))
except:
pass
try:
print("\n" + "_" * 72 + "\n" + str(list_drink[int(input_ops) - 41]))
except:
pass
input_qty = input("How Many You Want to Order? ").upper()
bot.speak("How Many You Want to Order")
if int(input_qty) != 0:
if int(input_qty) > 0:
list_item_order[int(input_ops) - 1] += int(input_qty)
print("\n" * 10)
print("Successfully Ordered!")
ORDER.process_order()
break
else:
if (list_item_order[int(input_ops) - 1]) <= 0:
print("\n" * 10 + "ERROR: Invalid Input (" + str(input_qty) + "). Try again!")
else:
if ( int(input_qty) + list_item_order[int(input_ops) - 1] >= 0):
list_item_order[int(input_ops) - 1] += int(input_qty)
print("\n" * 10)
print("Successfully Ordered!")
ORDER.process_order()
break
else:
print("\n" * 10 + "ERROR: Invalid Input (" + str(input_qty) + "). Try again!")
else:
print("\n" * 10 + "ERROR: Invalid Input (" + str(input_qty) + "). Try again!")
except:
print("\n" * 10 + "ERROR: Invalid Input (" + str(input_ops) + "). Try again!")
def menu_reader():
file_food = open('menu/list_food.fsd', 'r')
for i in file_food:
list_food.append(str(i.strip()))
file_food.close()
file_drink = open('menu/list_drink.fsd', 'r')
for i in file_drink:
list_drink.append(str(i.strip()))
file_drink.close()
i = 0
while i <= (len(list_food) - 1):
if 'US' in list_food[i]:
list_food[i] = str(list_food[i][:list_food[i].index('US') - 1]) + ' ' * (20 - (list_food[i].index('US') - 1)) + str(list_food[i][list_food[i].index('US'):])
i += 1
i = 0
while i <= (len(list_drink) - 1):
if 'US' in list_drink[i]:
list_drink[i] = str(list_drink[i][:list_drink[i].index('US') - 1]) + ' ' * (20 - (list_drink[i].index('US') - 1)) + str(list_drink[i][list_drink[i].index('US'):])
i += 1
def price_reader():
global list_food, list_drink
list_food = sorted(list_food)
list_drink = sorted(list_drink)
i = 0
while i < len(list_food):
list_item_price[i] = float(list_food[i][int(list_food[i].index("US") + 3):])
i += 1
i = 0
while i < len(list_drink):
list_item_price[40 + i] = float(list_drink[i][int(list_drink[i].index("US") + 3):])
i += 1
def modify_order():
print("\n" * 10)
bot = Speaking()
bot.speak("Here is your order list")
print("*" * 30 + " ORDER LIST " + "*" * 30 + "\n")
total_price = 0
i = 0
while i < len(list_item_order):
if(list_item_order[i] != 0):
if (i >= 0) and (i < 40):
print(" " * 17 + " (" + str(i + 1) + ")" + str(list_food[i]) + " x " + str(list_item_order[i]))
total_price += list_item_price[i] * list_item_order[i]
if (i >= 40) and (i < 80):
print(" " * 17 + " (" + str(i + 1) + ")" + str(list_drink[i - 40]) + " x " + str(list_item_order[i]))
total_price += list_item_price[i] * list_item_order[i]
i += 1
else:
i += 1
print(" " * 17 + "_" * 35 + "\n" + " " * 17 + "TOTAL PRICES: US " + str(round(total_price, 2)) + "\n")
ORDER.process_order()
def cancel_order():
bot = Speaking()
bot.speak("Thank you")
print("*" * 32 + " THANK YOU " + "*" * 31 + "\n")
def bill_please():
while True:
bot = Speaking()
bot.speak("Here is your bill")
print("*" * 32 + " PAYMENT " + "*" * 33 + "\n")
total_price = 0
i = 0
while i < len(list_item_order):
if(list_item_order[i] != 0):
if (i >= 0) and (i < 40):
print(" " * 17 + str(list_food[i]) + " x " + str(list_item_order[i]))
total_price += list_item_price[i] * list_item_order[i]
if (i >= 40) and (i < 80):
print(" " * 17 + str(list_drink[i - 40]) + " x " + str(list_item_order[i]))
total_price += list_item_price[i] * list_item_order[i]
i += 1
else:
i += 1
print(" " * 17 + "_" * 35 + "\n" + " " * 17 + "TOTAL PRICES: US " + str(round(total_price, 2)))
print("\n (P) PAY (M) MAIN MENU (C) CHANGE ORDER (E) EXIT\n" + "_" * 72)
bot.speak("Please select your operation")
input_ops = str(input("Please Select Your Operation: ")).upper()
if (input_ops == 'P'):
print("\n" * 10)
if (total_price > 0):
bot.speak("Successfully paid")
print("Successfully Paid!")
else:
bot.speak("Thank you")
print("*" * 32 + " THANK YOU " + "*" * 31 + "\n")
break
elif (input_ops == 'M'):
print("\n" * 10)
ORDER.process_order()
break
elif (input_ops == 'C'):
print("\n" * 10)
ORDER.modify_order()
break
elif ('E' in input_ops) or ('e' in input_ops):
ORDER.cancel_order()
break
else:
print("\n" * 10 + "ERROR: Invalid Input (" + str(input_ops) + "). Try again!")
class Speaking:
def speak(self, audio):
engine = pyttsx3.init()
engine.say(audio)
engine.runAndWait()
if __name__ == '__main__':
ORDER()
ORDER.reset()
ORDER.menu_reader()
ORDER.price_reader()
ORDER.welcome() |
9b13b6dc77a4d2c36f5f63ce8bc44114cafd877f | RenanBertolotti/Python | /Uri Judge - Python/URI-1134.py | 909 | 3.75 | 4 | """Um Posto de combustíveis deseja determinar qual de seus produtos tem a preferência de seus clientes.
Escreva um algoritmo para ler o tipo de combustível abastecido (codificado da seguinte forma: 1.Álcool 2.Gasolina
3.Diesel 4.Fim). Caso o usuário informe um código inválido (fora da faixa de 1 a 4) deve ser solicitado um novo código
(até que seja válido). O programa será encerrado quando o código informado for o número 4.
Entrada
A entrada contém apenas valores inteiros e positivos.
Saída
Deve ser escrito a mensagem: "MUITO OBRIGADO" e a quantidade de clientes que abasteceram cada tipo de combustível,
conforme exemplo."""
al = 0
ga = 0
di = 0
x = 0
while x != 4:
x = int(input())
if x == 1:
al = al + 1
if x == 2:
ga = ga + 1
if x == 3:
di = di + 1
print('MUITO OBRIGADO')
print('Alcool: {}'.format(al))
print('Gasolina: {}'.format(ga))
print('Diesel: {}'.format(di))
|
fff4a9000429035636d21d00e448b4c4096b4993 | garandria/python-micro-benchmark | /sort_compare/main.py | 1,987 | 3.59375 | 4 |
import sys
import argparse
def main():
""" """
parser = argparse.ArgumentParser()
# size
parser.add_argument('--size', default=MAXSIZE, type=int)
# data structure choice
parser.add_argument('--data-structure', choices=['list', 'narray'],
help='data structure to do the test on', required=True)
# types
parser.add_argument('--type', choices=['integer', 'float', 'str'],
help='data type', required=True)
#
parser.add_argument('--action', choices=['iteration-for',
'iteration-while',
'iteration-for-range',
'insertion-comp',
'insertion-beginning',
'insertion-middle',
'insertion-end',
'random-access',
'random-removal',
'clean',
'pop',
'extend',
'insertion',
'insertion-comp',
'iteration-key',
'iteration-kv',
'not-in',
'iteration',
'random-in'],
help='action to perform on the data structure',
required=True)
# Number of elements to add when adding/deleting from a data structure
parser.add_argument('--extra', default=EXSIZE, type=int,
help='number of extra element to add in the data structure')
|
826ec43684460ca31f5d1f7e64d2e0a1a82f605a | linhlk49/HackerEarth | /Python/8.py | 366 | 3.609375 | 4 | # Complete String
a = input()
c = []
for i in range(a):
b = raw_input()
c.append(b)
mau = "qwertyuioplkjhgfdsazxcvbnm"
for i in c:
if len(i) < 26:
print "NO"
else:
dem = 0
for j in mau:
if j in i:
dem += 1
if dem == len(mau):
print "YES"
else:
print "NO"
|
d1e0812c6c28222880ee86ff0d3f3165a7028439 | ValeriaOchoa/Proyecto4 | /nombre.py | 3,676 | 3.625 | 4 | import turtle
from turtle import *
import os
turtle.setup(1300, 600)
win = turtle.Screen()
win.bgcolor("black")
t = turtle.Pen()
t.reset()
## LETRA D
def letraD():
t.left(180)
t.forward(400)
t.left(180)
t.color(0,1,0)
t.begin_fill()
t.dot(15,"red")
t.left(90)
t.forward(200)
t.right(90)
t.dot(15,"red")
t.forward(100)
t.right(45)
t.dot(15,"red")
t.forward(50)
t.right(45)
t.dot(15,"red")
t.forward(130)
t.left(315)
t.dot(15,"red")
t.forward(50)
t.left(315)
t.dot(15,"red")
t.forward(100)
t.backward(25)
t.right(90)
t.end_fill()
t.forward(170)
t.right(90)
t.color(0,0,0)
t.begin_fill()
t.forward(70)
t.right(45)
t.forward(30)
t.right(45)
t.forward(100)
t.left(315)
t.forward(30)
t.right(45)
t.forward(70)
t.end_fill()
t.color(0,1,0)
t.begin_fill()
t.left(90)
t.forward(27)
t.end_fill()
## LETRA A
def letraA():
t.left(90)
t.dot(15,"green")
t.forward(100)
t.forward(50)
t.color(1,0,0)
t.begin_fill()
t.left(90)
t.dot(15,"green")
t.forward(80)
t.right(90)
t.dot(15,"green")
t.forward(40)
t.right(90)
t.dot(15,"green")
t.forward(80)
t.left(90)
t.dot(15,"green")
t.forward(30)
t.left(90)
t.dot(15,"green")
t.forward(200)
t.left(90)
t.dot(15,"green")
t.forward(100)
t.left(90)
t.dot(15,"green")
t.forward(200)
t.end_fill()
t.left(90)
t.forward(30)
t.left(90)
t.forward(170)
t.right(90)
t.color(0,0,0)
t.begin_fill()
t.forward(40)
t.right(90)
t.forward(60)
t.right(90)
t.forward(40)
t.end_fill()
t.color(1,0,0)
t.begin_fill()
t.left(90)
t.forward(30)
t.left(90)
t.forward(40)
t.right(90)
t.forward(80)
t.left(90)
## LETRA N
def letraN():
t.forward(80)
t.color(0,1,0)
t.begin_fill()
t.left(90)
t.dot(15,"red")
t.forward(170)
t.left(215)
t.dot(15,"red")
t.forward(210)
t.left(55)
t.dot(15,"red")
t.forward(30)
t.left(90)
t.dot(15,"red")
t.forward(200)
t.left(90)
t.dot(15,"red")
t.forward(30)
t.left(90)
t.dot(15,"red")
t.forward(160)
t.right(145)
t.dot(15,"red")
t.forward(200)
t.left(55)
t.dot(15,"red")
t.forward(35)
t.left(90)
t.dot(15,"red")
t.forward(203)
t.end_fill()
t.left(90)
t.dot(15,"red")
t.forward(30)
t.left(90)
t.dot(15,"red")
t.forward(170)
t.left(215)
t.dot(15,"red")
t.forward(210)
t.left(55)
t.dot(15,"red")
t.forward(20)
def letraA1():
t.dot(15,"green")
t.forward(50)
t.color(1,0,0)
t.begin_fill()
t.left(90)
t.dot(15,"green")
t.forward(80)
t.right(90)
t.dot(15,"green")
t.forward(40)
t.right(90)
t.dot(15,"green")
t.forward(80)
t.left(90)
t.dot(15,"green")
t.forward(30)
t.left(90)
t.dot(15,"green")
t.forward(200)
t.left(90)
t.dot(15,"green")
t.forward(100)
t.left(90)
t.dot(15,"green")
t.forward(200)
t.end_fill()
t.left(90)
t.forward(30)
t.left(90)
t.forward(170)
t.right(90)
t.color(0,0,0)
t.begin_fill()
t.forward(40)
t.right(90)
t.forward(60)
t.right(90)
t.forward(40)
t.end_fill()
t.color(1,0,0)
t.begin_fill()
t.left(90)
t.forward(30)
t.left(90)
t.forward(40)
t.right(90)
t.forward(80)
t.left(90)
letraD()
letraA()
letraN()
letraN()
letraA1()
|
3d5a5ec29c8d58682a852692d80857522d077d99 | zangguojun/Algorithm | /labuladong/四天训练/Day 04 手把手带你刷二叉树(第一期).py | 5,551 | 3.78125 | 4 | class Node(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
class Tree:
def __init__(self, root=None):
self.root = root
def add(self, item):
node = Node(item)
if self.root is None:
self.root = node
else:
q = [self.root]
while True:
pop_node = q.pop(0)
if pop_node.left is None:
pop_node.left = node
return
elif pop_node.right is None:
pop_node.right = node
return
else:
q.append(pop_node.left)
q.append(pop_node.right)
def get_parent(self, item):
# 找到item的父节点
if self.root.data == item:
return None
q = [self.root]
while q:
pop_node = q.pop(0)
if pop_node.left and pop_node.left.data == item:
return pop_node
elif pop_node.right and pop_node.right.data == item:
return pop_node
else:
if pop_node.left is not None:
q.append(pop_node.left)
if pop_node.right is not None:
q.append(pop_node.right)
return None
def delete(self, item):
'''
从二叉树中删除一个元素
先获取 待删除节点 item 的父节点
如果父节点不为空,
判断 item 的左右子树
如果左子树为空,那么判断 item 是父节点的左孩子,还是右孩子,如果是左孩子,将父节点的左指针指向 item 的右子树,反之将父节点的右指针指向 item 的右子树
如果右子树为空,那么判断 item 是父节点的左孩子,还是右孩子,如果是左孩子,将父节点的左指针指向 item 的左子树,反之将父节点的右指针指向 item 的左子树
如果左右子树均不为空,寻找右子树中的最左叶子节点 x ,将 x 替代要删除的节点。
删除成功,返回 True
删除失败, 返回 False
'''
if self.root is None: # 如果根为空,就什么也不做
return False
parent = self.get_parent(item)
if parent:
del_node = parent.left if parent.left.data == item else parent.right # 待删除节点
if del_node.left is None:
if parent.left.data == item:
parent.left = del_node.right
else:
parent.right = del_node.right
del del_node
return True
elif del_node.right is None:
if parent.left.data == item:
parent.left = del_node.left
else:
parent.right = del_node.left
del del_node
return True
else: # 左右子树都不为空
tmp_pre = del_node
tmp_next = del_node.right
if tmp_next.left is None:
# 替代
tmp_pre.right = tmp_next.right
tmp_next.left = del_node.left
tmp_next.right = del_node.right
else:
while tmp_next.left: # 让tmp指向右子树的最后一个叶子
tmp_pre = tmp_next
tmp_next = tmp_next.left
# 替代
tmp_pre.left = tmp_next.right
tmp_next.left = del_node.left
tmp_next.right = del_node.right
if parent.left.data == item:
parent.left = tmp_next
else:
parent.right = tmp_next
del del_node
return True
else:
return False
def preorder(self, root):
if not root:
return []
result = [root.data]
left_item = self.preorder(root.left)
right_item = self.preorder(root.right)
return result + left_item + right_item
def inorder(self, root):
if not root:
return []
result = [root.data]
left_item = self.inorder(root.left)
right_item = self.inorder(root.right)
return left_item + result + right_item
def postorder(self, root):
if not root:
return []
result = [root.data]
left_item = self.postorder(root.left)
right_item = self.postorder(root.right)
return left_item + right_item + result
def traverse(self):
if self.root is None:
return None
q = [self.root]
res = [self.root.data]
while q != []:
pop_node = q.pop(0)
if pop_node.left is not None:
q.append(pop_node.left)
res.append(pop_node.left.data)
if pop_node.right is not None:
q.append(pop_node.right)
res.append(pop_node.right.data)
return res
def fastSort(nums,lo,hi):
p = partition(nums,lo,hi)
sort(nums,lo,p-1)
sort(nums,p+1,hi)
if __name__ == '__main__':
t = Tree()
for i in range(10):
t.add(i)
print(t.preorder(t.root))
print(t.inorder(t.root))
print(t.postorder(t.root))
print(t.traverse())
|
a31ed18358d4274afa591d270d6fd3dbfcc1b68e | pepaslabs/px-ref | /kicad/releases/v2.6/ohmtek.py | 1,289 | 3.734375 | 4 | #!/usr/bin/env python
import itertools
def powerset(iterable):
# thanks to https://docs.python.org/2/library/itertools.html
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s)+1))
def parallel(a, b):
return 1/(1/float(a)+1/float(b))
r4h = 25100.0
r4as = [4180.0, 1040.0, 261.0, 181.0]
r4bs = [4180.0, 1040.0, 261.0]
r5a = 2270.0
r5b = 2080.0
r5 = parallel(r5a, r5b)
combos = []
for a in powerset(r4as):
for b in powerset(r4bs):
combos.append((a,b))
configurations = []
for (a,b) in combos:
aa = (list(a) + [r4h])
aa.sort(reverse=True)
bb = (list(b) + [r4h])
bb.sort(reverse=True)
r4a = sum(aa)
r4b = sum(bb)
r4 = parallel(r4a, r4b)
ratio = r4 / r5
entry = (ratio, r4, r5, aa, bb)
configurations.append(entry)
configurations.sort()
print "| Ratio | Bank A | Bank B | Temp (C) |"
print "|---|---|---|---|"
for (ratio, r4, r5, aa, bb) in configurations:
bank_a = ", ".join(["%s" % int(a) for a in aa])
bank_b = ", ".join(["%s" % int(b) for b in bb])
temp_c = 310.0 - 7.0 * 500.0 * r5 / (r4 + r5)
print "| %0.3f:1 | %s | %s | %0.1f |" % (ratio, bank_a, bank_b, temp_c)
|
030c00ad05f50a8ae940367d5901dfa115342f62 | ashirwadsangwan/DS-and-Algos---UCSD | /Algorithmic-Toolbox/w1_progChal/maxPairwiseProd/max_pairwise_product.py3 | 335 | 3.515625 | 4 | def maxPairProd(numbers):
maxProd = 0
for i in range(len(numbers)):
for j in range(i+1,len(numbers)):
maxProd = max(maxProd, (numbers[i] * numbers[j]))
return maxProd
if __name__ == "__main__":
n = int(input())
arr = list(map(int, input().split()))
print(maxPairProd(arr)) |
8b20a764588a41008466ad13600d50f13b88ecfe | blackox626/python_learn | /leetcode/top100/longestValidParentheses.py | 993 | 3.515625 | 4 | """
给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
"""
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
dic = {')': '(', ']': '[', '}': '{'}
stack = []
indexStack = []
maxLen = 0
curLen = 0
for index, i in enumerate(s):
if stack and i in dic:
if stack[-1] == dic[i]:
stack.pop()
indexStack.pop()
curLen = index - (indexStack[-1] if len(indexStack) > 0 else -1)
maxLen = max(curLen, maxLen)
else:
indexStack.append(index)
stack.append(i)
else:
indexStack.append(index)
stack.append(i)
return max(curLen, maxLen)
print(Solution().longestValidParentheses("(()))())("))
|
e047c2224dfe8890d23744b6250aa58c2e7ef191 | zeenatali5710/Wumpus | /KB.py | 4,802 | 3.59375 | 4 | ######################################
# The KB class will store information about your interactions with the game.
# You will use the KB to help you make a decision about where to move next.
# So, for example, if you use the MOVE command and the game gives you the following results:
# You are in room 4.
# Passages lead to [1, 3, 8]
# I smell a Wumpus!
#
# The KB would suggest which is a better option of the three possibilities using previous facts and inference.
#####################################
import aima3.utils
import aima3.logic
class KB():
clauses = []
breeze=[]
not_breeze=[]
smell=[]
not_smell=[]
safe=[]
conns={}
def __init__(self):
self.conns["1"] = [2,4,5]
self.conns["2"] = [3,1,6]
self.conns["3"] = [4,2,7]
self.conns["4"] = [1,3,8]
self.conns["5"] = [1,6,8]
self.conns["6"] = [2,7,5]
self.conns["7"] = [3,8,6]
self.conns["8"] = [4,5,7]
def smell_info(self, location, smell_wumpus):
if smell_wumpus:
if str(location) not in (self.smell):
self.smell.append(str(location))
else:
if str(location) not in (self.not_smell):
self.not_smell.append(str(location))
def breeze_info(self, location, feel_breeze):
if feel_breeze:
if str(location) not in (self.breeze):
self.breeze.append(str(location))
else:
if str(location) not in (self.not_breeze):
self.not_breeze.append(str(location))
def location_info(self, current_room):
suggestion=""
if not str(current_room) in self.safe:
self.safe.append(str(current_room))
def make_suggestion(self, options):
suggestion=""
for rm in options:
found=False
if str(rm) in self.smell and str(rm) in self.breeze:
if str(rm) in self.safe:
suggestion =suggestion + "You have been here before but you could safely move to room " + str(rm) + "\n"
found=True
else:
suggestion =suggestion + "Strong suggestion to move to room " + str(rm) + "\n"
found=True
else:
#print("Step 1")
if not rm in self.breeze:
#print("Step 2")
conns_to_room=self.conns[str(rm)]
#print("is " + str(conns_to_room) + " in " + str(self.breeze))
counter=0
for rm_conn in conns_to_room:
if rm_conn==rm:
continue
##If one of the connected rooms senses a breeze then maybe the room has a pit
if str(rm_conn) in self.breeze:
counter = counter + 1
if counter ==1 and str(rm) not in self.safe:
suggestion =suggestion + "Uh oh: There is a chance that room " + str(rm) + " could mean trouble.\n"
found=True
elif counter >=2 and str(rm) not in self.safe:
suggestion =suggestion + "Uh oh: Room " + str(rm) + " means trouble.\n"
found=True
if not rm in self.smell:
#print("Step 3")
conns_to_room=self.conns[str(rm)]
#print("is " + str(conns_to_room) + " in " + str(self.smell))
counter=0
for rm_conn in conns_to_room:
if rm_conn==rm:
continue
##If one of the connected rooms senses a smell then maybe the room has a wumpus
if str(rm_conn) in self.breeze:
counter = counter + 1
if counter ==1 and str(rm) not in self.safe:
suggestion =suggestion + "Uh oh: There is a chance that room " + str(rm) + " could mean trouble.\n"
found=True
elif counter >=2 and str(rm) not in self.safe:
suggestion =suggestion + "Uh oh: Room " + str(rm) + " means trouble.\n"
found=True
if not found:
if str(rm) in self.safe:
suggestion =suggestion + "Sometimes safety is a place you've been before, try room " + str(rm) + "\n"
else:
suggestion += "I don't have enough information about room: " +str(rm) + ". Sorry, you are on your own.\n"
if (len(suggestion))<1:
suggestion="KB Doesn't Have Enough Information to Help--Sorry"
print(suggestion)
|
6ae271bf7aacb7a309051f53ca3a9eedceb3a1db | chadat23/CS | /6.01/Lecture_2/add_ex_2.3.5.py | 318 | 3.640625 | 4 | def slow_mod(a, b):
if a < b:
return a
return slow_mod(a - b, b)
a, b = 5, 2
print(f'slowmod({a}, {b}) = {slow_mod(a, b)}')
a, b = 6, 2
print(f'slowmod({a}, {b}) = {slow_mod(a, b)}')
a, b = 8, 3
print(f'slowmod({a}, {b}) = {slow_mod(a, b)}')
a, b = 4, 6
print(f'slowmod({a}, {b}) = {slow_mod(a, b)}')
|
17aa2b2173388c03994a2ecf24eb82f5877820da | eeshannarula29/Climate-Change-Report-csc110-project | /analyze_data.py | 3,914 | 4.15625 | 4 | """In this file we will visualize the data and answer some
questions about climate change
The dataset we are using is a collection of 7000 tweets,
with information about sentiment score of the tweet,all
the hashtags associated with the tweets,number of likes
the tweet got,number of times the tweet was retweeted,
date of creation,username of the user,users followers
count,and location of the user.
The dataset is made by us, using the twitter API, to
extract tweets on 6 hashtags on climate change. The
sentiments were calculated using dataset of words
called the Sentiword dataset, which contains positive
and negative words, with their corresponding scores.
References:
- https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value
"""
import operator
from typing import Dict
from datetime import datetime
import matplotlib.pyplot as plt
from data_manager import Dataset
def load_data(filename: str) -> Dataset:
"""Use data handler library to extract data from our dataset
@param filename: path for the dataset
@return: dataset as a list of list
"""
return Dataset(filepath=filename,
types=[str, float, str, list, int, int, datetime, str, int, str])
def grp_by_days(date: datetime) -> float:
"""This is a filter function for grouping the data by dates
:param date: the datetime object
:return: the day of the datetime object
"""
return date.day
def plot_sentiments(filepath: str) -> None:
"""Use matplotlib.pyplot to plot a scatterplot with lines joining the points
@param filepath: path for the dataset
@return: The function just plots a graph
"""
data = load_data(filepath)
x, y = data.calculate_average(6, 1, grp_by_days)
date, value = x.pop(), y.pop()
list.insert(x, 0, date)
list.insert(y, 0, value)
plt.plot(x, y, marker='o')
plt.show()
def word_count(string: str) -> Dict[str, int]:
"""Count the number of times all the words are occurring in the string
and return a dict with each word mapped to its count
@param string: The string for which we want word count
@return: dict mapping word to its count
"""
tags = ['#climatechange',
'#climatechangeisreal',
'#actonclimate'
'#globalwarming',
'#climatechangehoax',
'#climatedeniers',
'#climatechangeisfalse',
'#globalwarminghoax',
'#climatechangenotreal']
words = {}
text = string. \
replace('.', ''). \
replace('"', ''). \
replace(',', ''). \
replace('-', ''). \
replace('_', ''). \
replace('#', ''). \
replace('?', ''). \
replace('@', '').lower()
for element in text.split():
if len(element) > 6 and all(element not in hashtag for hashtag in tags):
if element in words:
words[element] += 1
else:
words[element] = 1
return words
def plot_top_10(filepath: str) -> None:
"""Plot a count-plot for the highest occurring words in the tweets
@param filepath: path to the dataset
"""
data = Dataset(filepath)
text = ''
for tweet in data.get():
text += tweet[0]
words = word_count(text)
sorted_words = sorted(words.items(), key=operator.itemgetter(1), reverse=True)[:11]
plt.bar([word[0] for word in sorted_words],
[word[1] for word in sorted_words])
plt.show()
if __name__ == '__main__':
import python_ta
python_ta.check_all(config={
'extra-imports': ['datetime',
'matplotlib.pyplot',
'data_manager',
'typing',
'operator'],
'allowed-io': [],
'max-line-length': 150,
'disable': ['R1705', 'C0200']
})
|
3894eb83159b04601d91bab072886c9cd1da17f9 | guilhermeribg/pythonexercises | /conta_char.py | 483 | 3.59375 | 4 | def conta_letras(frase, contar="vogal"):
contador_vogal = 0
contador_consoantes = 0
frasesp = frase.replace(" ","") #frase sem espaço
for i in frasesp:
if i == "A" or i == "E" or i == "I" or i == "O" or i == "U" or i == "a" or i == "e" or i == "i" or i == "o" or i == "u":
contador_vogal+=1
else:
contador_consoantes+=1
if contar == "consoantes":
return contador_consoantes
else:
return contador_vogal
|
5fbb0c4b8139df482afbe8ba249af6f97cce882c | ckxckx/ckxsnippet | /python_code/misc_before/mypython/trytwo.py | 296 | 3.75 | 4 | # -*- coding: utf-8 -*-
import urllib
def print_list(list):
for i in list:
print i
def demo():
s=urllib.urlopen('http://www.douban.com/people/brainlink/')
# print_list(s.readlines())
print_list(dir(s.info()))
# print 'hello'
if __name__=='__main__':
demo() |
f27567a24fdfdff6463475ccd9a96149c6a39813 | Vikash082/algo-1 | /three_number_sum.py | 703 | 4.09375 | 4 | def threeNumberSum(array, targetSum):
array.sort()
results = []
for i, _ in enumerate(array):
left = i + 1
right = len(array) - 1
while left < right:
sum_of_left_right = array[left] + array[right]
if array[i] + sum_of_left_right == targetSum:
results.append([array[i], array[left], array[right]])
left += 1
right -= 1
elif array[i] + sum_of_left_right > targetSum:
right -= 1
elif array[i] + sum_of_left_right < targetSum:
left += 1
return results
if __name__ == '__main__':
print(threeNumberSum([12, 3, 1, 2, -6, 5, -8, 6], 0))
|
a92add9bfb58fa3ef5e8441eb054ca4ba8d31118 | ARWA-ALraddadi/python-tutorial-for-beginners | /02-How to Use Pre-defined Functions Demos/8-random_scrabble.py | 1,823 | 4.375 | 4 | #-------------------------------------------------------------
#
# Demonstration - Random Scrabble
#
# As a simple demonstration of how we can create a pattern
# by calling functions from the Turtle and Random modules,
# this program draws a random image that looks like a
# game of Scrabble, consisting of vertically and
# horizontally arranged white squares on a grey background.
# Each square has a randomly chosen alphabetic letter in it.
#
# Import the graphics and random functions required
from turtle import *
from random import choice, randint
# Define some fixed values
square_size = 20 # pixels
border = 2 # pixels (around each square)
how_many_squares = 100 # how many squares to draw
offset = 8 # how many pixels the letters are offset from the square's centre
# Set up the drawing window
setup()
title("Random Scrabble")
bgcolor('grey')
# Make the cursor a white square
color('white')
shape('square')
penup()
# Create a list of all the alphabetic letters
from string import ascii_uppercase, ascii_lowercase
letters = ascii_uppercase + ascii_lowercase
# Do the same action several times
for square_num in range(how_many_squares):
# Choose whether or not to turn (with going ahead most likely)
left(choice([-90, 0, 0, 0, 0, 90]))
# Move to the next position (leaving a little gap for the border)
forward(square_size + border)
# Draw the next square
stamp()
# Write a random letter exactly in the middle of the square
color('black')
letter = choice(letters) # Choose a random alphabetic letter
goto(xcor(), ycor() - offset) # Move down a little bit
write(letter, font=('Arial', 12, 'normal')) # Print the letter
goto(xcor(), ycor() + offset) # Move back to where we were
color('white')
# Exit gracefully
hideturtle()
done()
|
c624d789658d32556c6d49552cb79628fa60ec08 | superSeanLin/Algorithms-and-Structures | /143_Reorder_List/143_Reorder_List.py | 1,449 | 3.96875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
## Also can finish in three steps: 1. cut the list in two halves; 2. reverse the second half; 3. merge two parts
## Also recursive method
def reorderList(self, head: 'ListNode') -> 'None':
"""
Do not return anything, modify head in-place instead.
"""
## naive solution
if not head:
return head
prev = {head:None} # next:prev
p, q = head, head # q is prev of p
while p.next:
p = p.next
prev[p] = q
q = p
q = head # now p is the last one
while p and q and p != q: # not the same; q/p
temp1 = q.next
temp2 = temp1.next
if temp1 == p: # q->p
break
q.next = p
p.next = temp1
if temp1 != prev[p]:
temp1.next = prev[p]
q = temp2
if temp2 != prev[p]:
prev[p].next = q
p = prev[prev[p]]
if p == q: # q->x->y->z->p
q.next = None
break
else: # q->x->y->p
q.next = None
break
else: # q->x->p
temp1.next = None
break
|
3a9578137a2ac343af63cf909201f30da983fd54 | HyoHee/Python_month01_all-code | /day05/exercise06.py | 473 | 3.734375 | 4 | """
在终端中,循环录入字符串,如果录入空则停止.
停止录入后打印所有内容(一个字符串)
效果:
请输入内容:香港
请输入内容:上海
请输入内容:新疆
请输入内容:
香港_上海_新疆
"""
list_str = []
while True:
content = input("请输入内容:")
if content == "":
break
list_str.append(content)
result = "_".join(list_str)
print(result)
|
4091b1708f41ca22ccd16adddcc2d079f6908231 | rajiv990/password-generator | /password_gen.py | 770 | 4.125 | 4 | import random
import string
"""
Set #1 -
Password must have at least 12 characters
Characters must be alphanumeric and must have at least one special character
Ask how many passwords required to the user
"""
def simple_password_gen(count=12):
if count < 12:
return 'Password must have at least 12 characters'
simple_password = ''
while count != 0:
total = random.choice(string.ascii_letters) + \
random.choice(string.digits) + \
random.choice(string.punctuation)
simple_password += ''.join(random.sample(total, 1))
count -= 1
return simple_password
total_passwords = int(input('How many passwords do you need? '))
for i in range(total_passwords):
print(simple_password_gen())
|
1aed8d1d4256866dc7ec0064a21c3891a9a804f3 | Sreek-Swarnapuri/Python_Basics | /Functions/FunctionBasics.py | 666 | 4.46875 | 4 | #We have already used funcitons which are called pre-defined.
print("hello")
print(list(range(2,20)))
#We type the name of the function before paranthesis and values for the function in the paranthesis
print(list(range(2,10,3)))
#In addition to using pre-defined functions, we can also create custom funcitons
#creating a basic function without inputs or outputs
def func():
print("1")
print("2")
print("3")
print("4")
#Functions get executed only when they are called
func()
#We must define functions before they are called. In the same way we assign variables before using them.
#Following code will throw an error
Hello()
def Hello():
print("spam")
|
abab2bda86a37cef0df09423e8430cdf5a2befbe | Patrick-Gemmell/ICS3U-Unit4-03-Python | /loop_square.py | 600 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by: Patrick Gemmell
# Created on: OcTober 2019
# This program adds up a loop counter
def main():
# This function adds up a loop counter
integer = input("Enter an integer: ")
loop_counter = 0
total = 0
# inputs
try:
integer_as_number = int(integer)
for loop_counter in range(integer_as_number):
print("")
total = loop_counter**2
print("{0}^2 = {1}".format(loop_counter, total))
print("")
except Exception:
print("that is not an integer")
if __name__ == "__main__":
main()
|
682f2365c1bfeef44009917ffd628836fc0008b9 | mooksys/Python_Algorithms | /Chapter41/file_41_1_3.py | 394 | 3.796875 | 4 | def formula1(x):
if x == 5:
print("오류! 0-나눗셈")
else:
y = 3 * x / (x - 5) + (7 - x) / (2 * x)
print(y)
def formula2(x):
if x == -2:
print("오류! 0-나눗셈")
else:
y = (45 - x) / (x + 2) + 3 * x
print(y)
# 메인 코드
x = float(input("x 값을 입력하여라: "))
if x >= 1:
formula1(x)
else:
formula2(x)
|
5c02002b65072ce27e8a122233cb30ad2a6efbe0 | LiHua1997/Python-100-learn | /day7/day7_6.py | 754 | 3.609375 | 4 | """
杨辉三角
Version: 0.1
Author: St
"""
# def YangHui(rows):
# """
# 生成杨辉三角
# :param rows: 生成行数
# :return:
# """
# t = []
# for i in range(rows):
# t.append([])
# for j in range(i+1):
# if j == 0 or j == i :
# t[i].append(1)
# else:
# t[i].append(t[i - 1][j - 1] + t[i - 1][j])
# return t
def YangHui(num):
t = [[]] * num
for row in range(len(t)):
t[row] = [None] * int(row + 1)
for col in range(row+1):
if col == 0 or col == row:
t[row][col] = 1
else:
t[row][col] = t[row - 1][col] + t[row - 1][col - 1]
return t
print(YangHui(5))
|
a8f42858eaa17d152b3a6d7c8a5cd69a4c7cc8ba | DarshanGowda0/LC-Grind | /Daily-Grind/recover_from_preorder.py | 990 | 3.5625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
import re
class Solution:
def recoverFromPreorder(self, S: str) -> TreeNode:
# 1 (2--3--4) (5--6--7)
# 2 3 4 # 5 6 7
# 1 (2--3--4) (5--6---7)
#. 2 3 4 # 5 (6--7) # 6 7
# 1 (401--349---90--88)
# 401 349---90 88
def recur(string, dashes):
if not string:
return None
exp = "(?<=\\d)[-]{" + str(dashes) + "}(?=\\d)"
arr = re.split(exp, string)
node = TreeNode(int(arr[0]))
if len(arr) > 1:
node.left = recur(arr[1], dashes + 1)
if len(arr) > 2:
node.right = recur(arr[2], dashes + 1)
return node
return recur(S, 1)
|
d5b2ad52a3ab9030311d9284bbd77a76b7e36ad0 | yoshiharuka/MemoPad | /dbmodule.py | 7,773 | 3.578125 | 4 | # DB
import sqlite3
import os
# アプリ定数
DBMANE = 'database/database.db'
# ---------------------------------------------------------------------------
# dbmodule
#
# データベース操作用の関数を分離
# ---------------------------------------------------------------------------
# データベース生成
# ---------------------------------------------------------------------------
def create_database():
# ディレクトリ確認
try:
os.makedirs('database')
except:
pass
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
# categoryテーブルの定義
ddl = """
CREATE TABLE category
(
category_id INTEGER PRIMARY KEY AUTOINCREMENT,
category_name TEXT NOT NULL UNIQUE
)
"""
c.execute(ddl)
# デフォルト:なし
c.execute("INSERT INTO category VALUES(1,'なし')")
# itemテーブルの定義
ddl = """
CREATE TABLE items
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
category_id INTEGER NOT NULL,
name TEXT NOT NULL,
maintext TEXT,
FOREIGN KEY(category_id) REFERENCES category(category_id)
ON UPDATE CASCADE ON DELETE CASCADE
)
"""
c.execute(ddl)
except:
print('作成エラー')
c.commit()
c.close()
# ---------------------------------------------------------------------------
# メモ全件取得
# ---------------------------------------------------------------------------
def select_memo():
result = []
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
sql = """
SELECT id, name, category_name, maintext
FROM items as i, category as c
WHERE i.category_id = c.category_id
"""
result = c.execute(sql)
print('取得完了')
except:
print('取得エラー')
return list(result)
# ---------------------------------------------------------------------------
# メモ1件取得
# ---------------------------------------------------------------------------
def select_memo_one(id):
result = []
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
sql = """
SELECT id, name, category_name, maintext
FROM items as i, category as c
WHERE i.category_id = c.category_id
AND id = {}
""".format(id)
result = c.execute(sql)
print('取得完了')
except:
print('取得エラー')
return list(result)
# ---------------------------------------------------------------------------
# カテゴリ別メモ取得
# ---------------------------------------------------------------------------
def select_memo_category(category):
result = []
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
sql = """
SELECT id, name, category_name, maintext
FROM items as i, category as c
WHERE i.category_id = c.category_id
AND i.category_name = '{}'
""".format(category)
result = c.execute(sql)
print('取得完了')
except:
print('取得エラー')
return list(result)
# ---------------------------------------------------------------------------
# メモ登録
# ---------------------------------------------------------------------------
def insert_memo(memo):
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
print(memo)
sql = """
INSERT INTO items(name, category_id, maintext)
VALUES('{}', {}, '{}')
""".format(memo[0], memo[1], memo[2])
c.execute(sql)
c.commit()
c.close()
print('登録成功')
except:
print('登録エラー')
# ---------------------------------------------------------------------------
# メモ編集
# ---------------------------------------------------------------------------
def update_memo(memo):
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
print(memo)
sql = """
UPDATE items
SET name = '{}', category_id = {}, maintext = '{}'
WHERE id = {}
""".format(memo[0], memo[1], memo[2], memo[3])
c.execute(sql)
c.commit()
c.close()
print('更新成功')
except:
print('更新エラー')
# ---------------------------------------------------------------------------
# メモ削除
# ---------------------------------------------------------------------------
def delete_memo(id):
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
sql = """
DELETE FROM items
WHERE id = {}
""".format(id)
c.execute(sql)
c.commit()
c.close()
print('削除成功')
except:
print('削除エラー')
# ---------------------------------------------------------------------------
# カテゴリ全件取得
# ---------------------------------------------------------------------------
def select_category():
result = []
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
sql = """
SELECT category_id, category_name
FROM category
"""
result = c.execute(sql)
print('取得完了')
except:
print('取得エラー')
return list(result)
# ---------------------------------------------------------------------------
# カテゴリ名取得
# ---------------------------------------------------------------------------
def select_category_name(c_id):
result = []
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
sql = """
SELECT category_name
FROM category as c
WHERE c.category_id = {}
""".format(c_id)
result = c.execute(sql)
print('取得完了')
except:
print('取得エラー')
return list(result)
# ---------------------------------------------------------------------------
# カテゴリID取得
# ---------------------------------------------------------------------------
def select_category_id(c_name):
result = []
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
sql = """
SELECT category_id
FROM category as c
WHERE c.category_name = '{}'
""".format(c_name)
result = c.execute(sql)
print('取得完了')
except:
print('取得エラー')
return list(result)
# ---------------------------------------------------------------------------
# カテゴリ登録
# ---------------------------------------------------------------------------
def insert_category(c_name):
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
print(c_name)
sql = """
INSERT INTO category(category_name)
VALUES('{}')
""".format(c_name)
c.execute(sql)
c.commit()
c.close()
print('登録成功')
except:
print('登録エラー')
# ---------------------------------------------------------------------------
# カテゴリ削除
# ---------------------------------------------------------------------------
def delete_category(c_id):
c = sqlite3.connect(DBMANE)
c.execute("PRAGMA foreign_keys = ON")
try:
sql = """
DELETE FROM category
WHERE category_id = {}
""".format(c_id)
c.execute(sql)
c.commit()
c.close()
print('削除成功')
except:
print('削除エラー')
|
0c06c19b7f1936cf45d13e06c3a85e78fcb23389 | mariascervino/basics | /Learn Python for Total Begginers/Exercises/DictValues.py | 122 | 3.5 | 4 | toys = {"robot": "40", "car":"25", "iroman": "12"}
print(toys.values())
print(eval("{} + {} + {}".format(*toys.values()))) |
31a0fb79b91e73de5a2367bd2d94695a95328cff | wqhyw/ans_core_python_programming | /ch02/02.10.py | 219 | 3.578125 | 4 | #! /usr/bin/env python
while True:
src = int(raw_input("Input a num between 1 and 100: "))
if src < 101 and src > 0:
print "Done."
break
else:
print "Input error, please try again."
|
e4bed90e02be0550fdc6f6cfdbcd60eab6a587f8 | TrigonaMinima/Alphas | /numsys.py | 2,235 | 3.625 | 4 | from Alphas import core
def binary(char):
"""
numsys.binary(char) -> int
Returns binary value of any alphabet.
"""
return "{0:b}".format(ord(char))
def bi(start=0,end=26):
"""
numsys.bi([start, [end]]) -> dict
Returns a dictionary of alphabets (key is lowercase alphabet) and their ascii
codes in binary as the value.
"""
bi = {}
for a in core.alist(start,end):
bi[a] = binary(a)
return bi
def ubi(start=0,end=26):
"""
numsys.ubi([start, [end]]) -> dict
Returns a dictionary of alphabets (key is uppercase alphabet) and their ascii
codes in binary as the value.
"""
bi = {}
for a in core.ualist(start,end):
bi[a] = binary(a)
return bi
def octal(char):
"""
numsys.octal(char) -> int
Returns octal value of any alphabet.
"""
return "{0:o}".format(ord(char))
def oct(start=0,end=26):
"""
numsys.oct([start, [end]]) -> dict
Returns a dictionary of alphabets (key is lowercase alphabet) and their ascii
codes in octal as the value.
"""
octa = {}
for a in core.alist(start,end):
octa[a] = octal(a)
return octa
def uoct(start=0,end=26):
"""
numsys.uoct([start, [end]]) -> dict
Returns a dictionary of alphabets (key is uppercase alphabet) and their ascii
codes in octal as the value.
"""
octa = {}
for a in core.ualist(start,end):
octa[a] = octal(a)
return octa
def hexadecimal(char):
"""
numsys.hexa(char) -> int
Returns hexadecimal value of any alphabet.
"""
return "{0:x}".format(ord(char))
def hex(start=0,end=26):
"""
numsys.hex([start, [end]]) -> dict
Returns a dictionary of alphabets (key is lowercase alphabet) and their ascii
codes in hexadecimal as the value.
"""
hexa = {}
for a in core.alist(start,end):
hexa[a] = hexadecimal(a)
return hexa
def uhex(start=0,end=26):
"""
numsys.uhex([start, [end]]) -> dict
Returns a dictionary of alphabets (key is uppercase alphabet) and their ascii
codes in hexadecimal as the value.
"""
hexa = {}
for a in core.ualist(start,end):
hexa[a] = hexadecimal(a)
return hexa |
8e3fd347663e12dfa3e7a02339ecff88ee019749 | andrew1236/python | /calories burned calculator.py | 451 | 3.984375 | 4 | #calculates calories burned every 5 minutes starting at 10 minutes
def calculate_calories_burned():
print('Minutes Calories Burned')
print('-----------------------------------------')
counter=1
minutes=10
calories_burned=42
while counter<=5:
print(minutes,' ',format(calories_burned,'.1f'))
minutes=minutes+5
calories_burned+=21
counter+=1
main()
|
2a014a2a16db35e0377a06d4b0b52b9a7509d46c | hankerkuo/PythonPractice | /SamsungTest/snake_example_making.py | 2,269 | 3.515625 | 4 | import numpy as np
board = np.random.random_integers(2, 10)
apple = np.random.random_integers(0, board * board)
turn = np.random.random_integers(1, 10)
def random_D_L():
a = np.random.random_integers(0, 1)
if a == 0:
return 'L'
else:
return 'D'
lst =[]
lst_2 = []
R_D = []
vals = np.random.random_integers(1, board, (1000, 2))
vals = vals.tolist()
for item in vals:
if item not in lst:
lst.append(item)
# apple_position
vals_2 = np.random.random_integers(1, 50, (30))
vals_2 = vals_2.tolist()
for i in range(turn):
R_D.append(random_D_L())
for item in vals_2:
if item not in lst_2:
lst_2.append(item)
lst_2.sort()
print(board)
print(apple)
for i in range(apple):
print(lst[i][0], lst[i][1])
print(turn)
for i in range(turn):
print(lst_2[i], R_D[i])
import sys
sys.setrecursionlimit(100000000)
# def input():
# return sys.stdin.readline()[:-1]
N = board
K = apple
apple = []
for i in range(K):
x, y = lst[i][0], lst[i][1]
apple.append((x-1, y-1))
L = turn
change = []
for i in range(L):
x, y = lst_2[i], R_D[i]
change.append((int(x), y))
# arr = [뱀 존재 여부, 사과 존재 여부]
arr = []
for i in range(N):
arr.append([[False, False] for x in range(N)])
arr[0][0][0] = True
for i in range(K):
x = apple[i][0]
y = apple[i][1]
arr[x][y][1] = True
# move = [동, 남, 서, 북]
direction = [(0, 1), (1, 0), (0, -1), (-1, 0)]
move = 0
cnt = 0
result = 0
x, y = 0, 0
trace = [(0, 0)]
pointer = 0
while True:
if cnt < L:
if result == change[cnt][0]:
while True:
if change[cnt][1] == 'D':
move = (move+1) % 4
else:
move = (move-1) % 4
cnt += 1
if cnt == L or change[cnt][0] != result:
break
x += direction[move][0]
y += direction[move][1]
result += 1
if (x < 0 or x >= N) or (y < 0 or y >= N) or arr[x][y][0]:
print('ans:', result)
exit()
arr[x][y][0] = True
trace.append((x, y))
if not arr[x][y][1]:
delx = trace[pointer][0]
dely = trace[pointer][1]
arr[delx][dely][0] = False
pointer += 1
else:
arr[x][y][1] = False |
56dcb02619573f39d324e83676c5ec5ab42417df | georgiaoc/spring2019 | /20190219/mymodule.py | 251 | 3.5625 | 4 | # dunder file
def print_name():
print(__file__)
def multiply(x: int, y: int) -> int:
"""This function returns 5"""
return x * y
def something_terrible():
while True:
print('hi')
if __name__ == '__main__':
print_name()
|
0b09364f20f7c4d2ead699356b882a5848cc6a37 | chiragkalal/python_practice_programs | /test2.py | 1,457 | 4.125 | 4 | """
Let's assume you are given a window size of W and an array of integers S and that you can only see the W numbers of S in the window frame. Each time we slide the window over by one frame (from the left), we want you to output the maximum value within the window.
Print each element with white space in-between.
Test case
Each test case has only 1 line, and the first character is W, followed by array S. So below the input is W = 2 and S = [2,1,2,-1,3].
Limits
The length of S is always larger than or equal to W.
The window size W will be an integer in the range, 0 < W < 3,000,000,000.
An element Nn in the stream will be an integer in the range, -3,000,000,000 < Nn < 3,000,000,000.
Examples
input
2 2 1 2 -1 3
output
2 2 2 3
Analysis of output value
Since the window size is 2, output would be made in the following order:
2 1 2 -1 3 //Output 2 with 2 and 1
2 1 2 -1 3 //After excluding the initial data, output 2 with 1 and 2
2 1 2 -1 3 //Output 2 with 2 and -1
2 1 2 -1 3 //Output 3 with -1 and 3
"""
inp = input()
list_inp = inp.split(' ')
W = int(list_inp[0])
str_s = list_inp[1:]
S = [ int(num) for num in str_s]
if len(S) >= W and W in range(0, 3000000000):
fl = []
for i in range(0, len(S)-W+1):
if S[i] not in range(-3000000000, 3000000000):
break
winw = S[i:i+W]
print(winw)
fl.append(max(winw))
str_fl = [ str(item) for item in fl ]
print(" ".join(str_fl)) |
1a4c784123b1fbd562d30d8ec786b310588241fb | debasishsahoo/python | /file/file2.py | 193 | 3.625 | 4 | import os;
#rename file2.txt to file3.txt
os.rename("test.txt","TEST.txt")
##if os.rename:
## print("ok")
##else:
## print("not ok")
os.remove("TEST.txt")
|
6bc4f4f7c16b742e4705f6e171a6f5aeef19c080 | alabiansolution/python1901 | /day3/class/class-inherit.py | 853 | 3.8125 | 4 | class Car:
battery = 1
seat = 4
name = "Toyota"
model = "Camry 2010"
color = "Red"
def __init__(self, displacement, time):
self.displacement = displacement
self.time = time
def details(self):
print("Car name "+self.name+" Battery is "+str(self.battery)+" Model is "+self.model)
def speed(self):
speed = str(self.displacement / self.time) + "m/s"
print(speed)
# Toyota = Car(3000, 2)
# Toyota.speed()
#
# opel = Car(2000, 5)
# opel.name = "Opel"
# opel.battery = 2
# opel.details()
class Convertible(Car):
convertible = True
def __init__(self, displacement, time):
self.displacement = displacement
self.time = time
toyota = Convertible(500, 3)
toyota.color = "Green"
print(toyota.speed())
print(toyota.color)
print(toyota.name)
print(toyota.model)
|
14fec341b04555879d2a4051eec06b1408046f74 | neerja28/python-data-structures | /Dictionaries/Dictionaries.py | 2,910 | 4.46875 | 4 | # Dictionaries
# What is a collection?
# A collection is nice because we put more than one value in it and carry them all around in one convivient package
# We have a bunch of values in a single "variable"
# We do this by having more than one place "in" the variable
# We have ways of finding different places in the variable
# Lists and Dictionaries
List : A liner collection of values that stay in order
Dictionary : A bag of values, each with its own value
# Dictionaries
Dictionaries are pythons most powerful data collection
Dictionaries allow us to do fast database-like operations in python
They are memory based key-value stores
# Dictionaries
# lists index their entries based on the position in the list
# Dictionaries are like bags - no order
# So we index the things we put in the dictionary with a lookup tags
purse = dict()
purse['car_keys'] = 1
purse['badge'] = 2
purse['wallet'] = 3
print(purse) # {'car_keys': 1, 'badge': 2, 'wallet': 3}
print(purse['wallet']) # 3
purse['wallet'] = purse['wallet'] + 2
print(purse) # {'car_keys': 1, 'badge': 2, 'wallet': 5}
# Comparing Lists and Dictionaries
List and Dictionaries are MUTABLE.
Dictionaries are like lists except that they use keys instead of numbers to look up values
List use position to access values.
Dictionaries uses keys to access values.
lst = list()
lst.append(21)
lst.append(183)
print(lst) # [21, 183]
lst[0] = 23
print(lst) # [23, 183]
^^ same using dictionaries
numbers = dict()
numbers['age'] = 21
numbers['year'] = 2020
print(numbers) #{'age': 21, 'year': 2020}
numbers['age'] = 27
print(numbers) # {year': 2020', 'age': 27}
# Dictionary Literals
# Dictionary literals use curly braces and have a list of key : value pairs
# You can make an empty dictionary using empty curly braces
d = {'car_keys': 1, 'badge': 2, 'wallet': 5}
print(d) # {'badge': 2, 'wallet': 5, 'car_keys': 1}
empty_d = {}
print(dic) # {}
# Dictionary Tracebacks
# It is an error to reference a key which is not in the dictionary
# We can use the in operator to see if a key is in the dictionary
d = dict()
print(d['age']) # traceback error keyError
>>>'age' in d # False
# Example1
counts = dict()
names = ['Neerja', 'rooney', 'Lucky', 'Micky', 'Mini', 'Neerja']
for name in names:
if name in counts:
counts[name] = counts[name] + 1
else:
counts[name] = 1
print(counts)
# {'Neerja': 2, 'rooney': 1, 'Lucky': 1, 'Micky': 1, 'Mini': 1}
# Example2
# the get method for dictionaries
# the pattern of checking ato see if a key is already in a dictionary and assuming a default value if the key is not there is so comman
# that there is a method called get() that does this for us
# Default value if key does not exist (and no traceback)
counts = dict()
names = ['Neerja', 'rooney', 'Lucky', 'Micky', 'Mini', 'Neerja']
for name in names:
counts[name] = counts.get(name, 0) + 1 # the default value is zero
print(counts)
|
7d1ba7c6f915aa7cb13291f7cc954ee519c0cc6e | sergatron/deep_learning | /basics/mnist_clf.py | 2,052 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 23 14:59:43 2020
@author: smouz
"""
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
# Import necessary modules
from keras.layers import Dense, BatchNormalization, Dropout
from keras.models import Sequential
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping
from keras.utils import to_categorical
#%%
# =============================================================================
# MNIST digit images
# =============================================================================
mnist_df = pd.read_csv('data/mnist.csv')
mnist_df.head()
# NOTE: this data has no HEADER
# extract predictors and target
# X: everything after first column
# y: first column
X = mnist_df.iloc[:, 1:]
y = mnist_df.iloc[:, :1]
# convert target to categorical; there are 10 digits in this case
y = to_categorical(y.values)
#%%
# Train Model
# Create the model: model
model = Sequential()
optimizer = Adam(0.001)
# Add the first hidden layer
model.add(Dense(64, activation='relu', input_shape=(784,)))
# Add the second hidden layer
model.add(Dense(32, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dense(64, activation = "relu"))
model.add(Dense(128, activation = "relu"))
model.add(BatchNormalization())
model.add(Dropout(0.3))
# Add the output layer
# there are ten possible digits
model.add(Dense(10, activation='softmax'))
# Compile the model
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
early_stopping_monitor = EarlyStopping(patience=5, verbose=False)
# Fit the model
model_trained = model.fit(X,
y,
validation_split=0.2,
epochs=100,
callbacks=[early_stopping_monitor],
verbose=False
)
print(model.summary())
print("Accuracy:", model_trained.history['val_accuracy'][-1])
|
440487b6b3408a75687b8af0f798482471b47416 | margaret254/py_learn | /lists_04/sum_of_even.py | 466 | 4.28125 | 4 | # The sum of even numbers is always even
# Let's prove it ! Write a program that takes a list of numbers, and returns the sum of its even numbers only
# If the list has no even numbers, return 0
# for more info on this quiz, go to this url: http://www.programmr.com/sum-even
def sum_even(arr_x):
a = []
for i in arr_x:
if i % 2 == 0:
a.append(i)
return sum(a)
if __name__ == "__main__":
print(sum_even([1, 2, 3, 4, 5, 6, 7]))
|
80f0192a1dfd94c0ae4b4cfaf11c9fa51885c1ac | lschanne/DailyCodingProblems | /year_2019/month_06/2019_06_03__get_root_to_leaf_paths.py | 2,154 | 3.90625 | 4 | '''
June 3, 2019
Given a binary tree, return all paths from the root to leaves.
For example, given the tree:
1
/ \
2 3
/ \
4 5
Return [[1, 2], [1, 3, 4], [1, 3, 5]].
'''
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def get_root_to_leaf_paths(root):
def _recurse(node, paths, current_path):
if node is None:
return paths
current_path = current_path + [node.value]
if (node.left is None) and (node.right is None):
paths.append(current_path)
return paths
paths = _recurse(node.left, paths, current_path)
paths = _recurse(node.right, paths, current_path)
return paths
return _recurse(root, [], [])
if __name__ == '__main__':
test_cases = []
# test 0
tree = BinaryTree(
1,
BinaryTree(2),
BinaryTree(
3,
BinaryTree(4),
BinaryTree(5),
)
)
result = [[1, 2], [1, 3, 4], [1, 3, 5]]
test_cases.append([tree, result])
# test 1
tree = BinaryTree(0)
result = [[0]]
test_cases.append([tree, result])
# test 2
tree = BinaryTree(
'a',
BinaryTree('b'),
BinaryTree('c'),
)
result = [['a', 'b'], ['a', 'c']]
test_cases.append([tree, result])
# idk there really aren't any edge cases for this.
all_passed = True
for idx, (tree, expected_result) in enumerate(test_cases):
try:
result = get_root_to_leaf_paths(tree)
except Exception:
print('test #{} threw an exception!'.format(idx))
all_passed = False
else:
if result != expected_result:
print('test #{} failed!'.format(idx))
print('expected: {}'.format(expected_result))
print('actual: {}'.format(result))
all_passed = False
else:
print('test #{} passed!'.format(idx))
print('--------------------------')
if all_passed:
print('All tests passed!') |
89a3f7ea394810f22975c0519d671e53f699c67f | rjc042/ProjectEuler | /pe75.py | 714 | 3.59375 | 4 |
def is_exactly_1(L, MAX_L):
num_tris = 0
a = 1
b = L / 2 - a
c = L - (a + b)
while a < L / 3:
while b < c:
# if L == 120:
# print a,b,c
if a**2 + b**2 == c**2:
num_tris += 1
if num_tris > 1:
return False
# print "L = %d" % (L)
# print "GOOD: ", a, b, c
b += 1
c = L - a - b
a += 1
b = max([L / 2 - a, a])
c = L - (a + b)
return num_tris
def main():
MAX_L = 1000
num_exactly_1 = 0
for L in range(10, int(MAX_L)):
num_exactly_1 += is_exactly_1(L, MAX_L)
print num_exactly_1
main()
|
e1abf61a440b7cb326b92b9386fc826c55be5a43 | yono/codeeval | /num_of_ones/num_of_ones.py | 316 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
infile = open(sys.argv[1]).read().splitlines()
TARGET_CHAR = '1'
for line in infile:
char_count = 0
binary = str(format(int(line), 'b'))
for c in binary:
if c == TARGET_CHAR:
char_count = char_count + 1
print char_count
|
7c4670dfb7fb7e73cdf0177b7890febf752ba09d | jiaopi404/python_demos | /my_test_003/demo_09_hash_func.py | 423 | 3.65625 | 4 | # test func of hash
a = 2
b = 2
c = [1, 2, 3]
d = [1, 2, 3]
e = d
print('hash of a is: %s, hash of b is: %s' % (hash(a), hash(b)))
print('hash of c\'s id is: %s, hash of d\'s id is: %s, hash of e\'s id is: %s' % (hash(id(c)),
hash(id(d)),
hash(id(e))))
|
40a00116ff70250fcca083eb4bc10c782dec86cb | AWW-dev/samouk | /rozdz 13/lst252.py | 795 | 3.8125 | 4 | class Rectangle():
def __init__(self, w, l):
self.width = w
self.len = l
def area(self):
return self.width * self.len
class Data:
def __init__(self):
self.nums = [1, 2, 3, 4, 5]
def change_data(self, index, n):
self.nums[index] = n
data_one = Data()
data_one.nums[0] = 100
print(data_one.nums)
data_two = Data()
data_two.change_data(0, 100)
print(data_two.nums)
class Shape():
def __init__(self, w, l):
self.width = w
self.len = l
def print_size(self):
print("""{} na {}""".format(self.width, self.len))
class Square(Shape):
def area(self):
return self.width * self.len
my_shape = Shape(20,20)
my_shape.print_size()
a_square = Square(10,20)
a_square.print_size()
print(a_square.area()) |
43aab070d6a725873230b8318dd0d9fb34f0ef5b | MathMargarita/Bioinformatics-Rosalind | /Python/Chapter6/BA6F.py | 2,365 | 3.578125 | 4 | """
A solution to a ROSALIND bioinformatics problem.
Problem Title: Implement ChromosomeToCycle
Rosalind ID: BA6F
URL: http://rosalind.info/problems/ba6f/
"""
def ChromosomeToCycle(Chromosome):
Nodes=[]
for j in range(0,len(Chromosome)):
i=Chromosome[j]
if i > 0:
Nodes.append(2*i-1)
Nodes.append(2*i)
else:
Nodes.append(-2*i) #minus because i is negative
Nodes.append(-2*i-1)
return Nodes
if __name__ == '__main__':
x = '''(+1 -2 -3 +4)'''
x = x[1:-1]
p = x.split(" ")
for i in range(len(p)):
p[i] = int(p[i])
res = ChromosomeToCycle(p)
for i in range(len(res)):
res[i] = str(res[i])
res = " ".join(res)
res = "(" + res + ")"
print(res)
print(res == '''(1 2 4 3 6 5 7 8)''')
x = '''(+1 +2 -3 -4 +5 -6 +7 +8 -9 +10 -11 -12 +13 -14 +15 -16 +17 +18 +19 -20 +21 -22 -23 -24 +25 +26 +27 -28 +29 -30 -31 +32 +33 +34 -35 +36 +37 +38 -39 +40 -41 -42 +43 -44 -45 -46 -47 +48 +49 -50 +51 -52 -53 -54 +55 +56 +57 -58 -59 -60 +61 +62 +63 -64 +65 +66 +67 -68 -69)'''
x = x[1:-1]
p = x.split(" ")
for i in range(len(p)):
p[i] = int(p[i])
res = ChromosomeToCycle(p)
for i in range(len(res)):
res[i] = str(res[i])
res = " ".join(res)
res = "(" + res + ")"
print(res)
print(
res == '''(1 2 3 4 6 5 8 7 9 10 12 11 13 14 15 16 18 17 19 20 22 21 24 23 25 26 28 27 29 30 32 31 33 34 35 36 37 38 40 39 41 42 44 43 46 45 48 47 49 50 51 52 53 54 56 55 57 58 60 59 62 61 63 64 65 66 67 68 70 69 71 72 73 74 75 76 78 77 79 80 82 81 84 83 85 86 88 87 90 89 92 91 94 93 95 96 97 98 100 99 101 102 104 103 106 105 108 107 109 110 111 112 113 114 116 115 118 117 120 119 121 122 123 124 125 126 128 127 129 130 131 132 133 134 136 135 138 137)''')
x = '''(-1 -2 +3 +4 +5 +6 +7 +8 -9 -10 +11 -12 -13 +14 -15 +16 -17 -18 -19 -20 -21 -22 +23 -24 +25 +26 -27 -28 +29 -30 -31 -32 -33 +34 +35 -36 +37 +38 -39 +40 -41 +42 +43 -44 +45 -46 -47 -48 -49 -50 +51 -52 +53 +54 +55 -56 +57 -58 -59 +60 +61)'''
x=x[1:-1]
p=x.split(" ")
for i in range (len(p)):
p[i]=int(p[i])
res=ChromosomeToCycle(p)
for i in range (len(res)):
res[i]=str(res[i])
res=" ".join(res)
res="("+res+")"
print(res)
|
743c4cb725a3bc24b66ae329d2dc9c4cbdc3524c | msaindon/deuces | /go.py | 1,329 | 3.75 | 4 | from deuces import Card, Evaluator, Deck
# create a card
card = Card.new('Qh')
# create a board and hole cards
board = [
Card.new('2h'),
Card.new('2s'),
Card.new('Jc')
]
hand = [
Card.new('Qs'),
Card.new('Th')
]
# pretty print cards to console
Card.print_pretty_cards(board + hand)
# create an evaluator
evaluator = Evaluator()
# and rank your hand
rank = evaluator.evaluate(board, hand)
print()
# or for random cards or games, create a deck
print("Dealing a new hand...")
deck = Deck()
board = deck.draw(5)
player1_hand = deck.draw(2)
player2_hand = deck.draw(2)
print("The board:")
Card.print_pretty_cards(board)
print("Player 1's cards:")
Card.print_pretty_cards(player1_hand)
print("Player 2's cards:")
Card.print_pretty_cards(player2_hand)
p1_score = evaluator.evaluate(board, player1_hand)
p2_score = evaluator.evaluate(board, player2_hand)
# bin the scores into classes
p1_class = evaluator.get_rank_class(p1_score)
p2_class = evaluator.get_rank_class(p2_score)
# or get a human-friendly string to describe the score
print(f"Player 1 hand rank = {p1_score} {evaluator.class_to_string(p1_class)}")
print(f"Player 2 hand rank = {p2_score} {evaluator.class_to_string(p2_class)}")
# or just a summary of the entire hand
hands = [player1_hand, player2_hand]
evaluator.hand_summary(board, hands)
|
df4d5aa077c17e4309f6f1226bfbaf539c6f625f | xiaohaiguicc/CS5001 | /hw09_Chenxi_Cai/word_ladder_starter/word_ladder.py | 3,968 | 4.15625 | 4 | from queue import Queue
from stack import Stack
class WordLadder:
"""A class providing functionality to create word ladders"""
# TODO:
# Implement whatever functionality is necessary to generate a
# stack representing the word ladder based on the parameters
# passed to the constructor.
def __init__(self, w1, w2, wordlist):
"""Constructor.
w1 and w2 are begining and end of word ladder.
Wordlist is a dictionary containing set of words
with lengths between [len(w1), len(w2)].
String, String, Dictionary -> None"""
self.w1 = w1
self.w2 = w2
self.worddic = wordlist # worddic is a dictionary
self.queue = Queue()
self.wordset = set()
def initialize(self):
"""Initialize a queue containing a single stack
None -> None"""
stack = Stack()
stack.push(self.w1)
self.queue.enqueue(stack)
def make_ladder(self):
"""1. First generate all possible words with the same length as w1.
(This part of word is the Algorithm of hw9).
2. Then enqueue each stack and get top word.
(i)If top word is shorter than w2,
for each position of the word, (->word<-, from 0 to len(word)).
For each letter in the alpahbet,
add letter to the position. The len(word) increase by 1.
(ii)If top word is longer than w2,
for each position of the word, (->word<-, from 0 to len(word)).
delete character in this position from it. The len(word) decrease by 1.
Add new word to stack and enqueue stack to queue.
Continue step 2 until we get the final w2.
If word ladder exist, return the word ladder stack
Else, return None
None -> Stack/None"""
self.initialize()
alph = "abcdefghijklmnopqrstuvwxyz"
while not self.queue.isEmpty():
stack = self.queue.dequeue()
word = stack.peek()
for i in range(len(word)):
for letter in alph:
new_word = word[:i]
new_word += letter
new_word += word[i + 1:]
new_stack = self.word_in_wordlist(new_word, stack)
if new_stack is not None:
return new_stack
if len(word) < len(self.w2):
for i in range(len(word) + 1):
for letter in alph:
new_word = word[:i]
new_word += letter
new_word += word[i:]
new_stack = self.word_in_wordlist(new_word, stack)
if new_stack is not None:
return new_stack
elif len(word) > len(self.w2):
for i in range(len(word)):
new_word = word[:i]
new_word += word[i + 1:]
new_stack = self.word_in_wordlist(new_word, stack)
if new_stack is not None:
return new_stack
return None
def word_in_wordlist(self, new_word, stack):
"""1.First check if the new word in the wordset.
2.Then check if the new word is in wordlist.
If it is in wordlist, copy stack and put it into new stack.
3.(i)If the word is the last word of the word ladder,
return the new stack.
(ii)If the word is not the last word of the ladder,
enqueue the new stack onto the end of the queue and return None.
String, Stack -> Stack/None"""
if new_word not in self.wordset:
self.wordset.add(new_word)
wordlist = self.worddic[len(new_word)]
if new_word in wordlist:
new_stack = stack.copy()
new_stack.push(new_word)
if new_word == self.w2:
return new_stack
self.queue.enqueue(new_stack)
|
58202592f7879c314ff2235ef98ade868f345c20 | badordos/Doliner-labs-Python-2018 | /11) Словари/Task2 db/Task2.py | 868 | 3.71875 | 4 | #Составьте программу-переводчик, которая на основе имеющего словаря
#будет переводить предложения. В случае, если подобного слова нет в словаре,
#программа должна запросить это слово и его перевод
import shelve
db=shelve.open('db_file')
while True:
inp = (input('Введите предожение для перевода с английского на русский: '))
words=inp.split()
translate = list
for i in words:
if db.get(i) == None:
print (i,'- слова нет в базе')
newValue = input('Введите перевод: ')
db[i] = newValue
db.update()
else: print ('Перевод: ',i,':',(db.get(i)))
|
5019cfd84f9cb64ba8d7e4d72cfe18d23ba0f894 | VishalSahu/30DaysOfCode | /Day_25_Running_Time_and_Complexity.py | 377 | 3.96875 | 4 | import math
def isPrime(n):
if n<=1:
return False
sqrtn = math.sqrt(n)
if sqrtn.is_integer():
return False
for i in range(2,int(sqrtn)+1):
if n%i==0:
return False
return True
numt = int(input())
for i in range(numt):
n= int(input())
if isPrime(n):
print("Prime")
else:
print("Not prime")
|
c938545b851de0739ccc7f7724f0b3c67a904a7d | ActiveState/learn-python | /src/operators/test_membership.py | 782 | 4.25 | 4 | """Membership operators
@see: https://www.w3schools.com/python/python_operators.asp
Membership operators are used to test if a sequence is presented in an object.
"""
def test_membership_operators():
"""Membership operators"""
# Let's use the following fruit list to illustrate membership concept.
fruit_list = ["apple", "banana"]
# in
# Returns True if a sequence with the specified value is present in the object.
# Returns True because a sequence with the value "banana" is in the list
assert "banana" in fruit_list
# not in
# Returns True if a sequence with the specified value is not present in the object
# Returns True because a sequence with the value "pineapple" is not in the list.
assert "pineapple" not in fruit_list
|
fb3a4f20c346da86d58580f1b8c7f03cbfaa61dd | ylada/ML | /Ch3Classification.py | 16,464 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 25 08:54:26 2018
Hands on machine Learning with Scikit-Learn and Tensorflow
Chapter 3: Classification using minst
@author: liaoy
------------ Prepare Data -------------------------
1. #load data, split to training and testing sets
1.1 X , y = mnist['data'], mnist['target']
X_train, X_test = X[:60000], X[60000:]
y_train, y_test = y[:60000], y[60000:]
1.2 #shuffle data, avoid sensitive to orders
shuffle_index = np.random.permutation(60000)
X_train, y_train = X[shuffle_index], y[shuffle_index]
1.3 #Optionally: Turn to binary classfications (optional, only if needed)
y_train_5, y_test_5 = y_train == 5, y_test == 5
1.4 #optionally: Standarize Data
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train.astype(np.float64))
------------- Training -------------------------
2. #Optionally split training sets; classify; Evaluate
2.1 #Pick classifiers: SGDCClassifier, RandomForest
clf = SGDCClassifier(random_state=42)
clf = RandomForestClassifier(random_state=42)
clf.fit(X_train, y_train_5) #binary or multiclass
clf.predict([some_digit_image]) #predict a digit image
2.2 #Optional: split training data to n, train n-1, validate the rest 1
from sklearn.model_selection import StratifiedKFold #iterate folds
from sklearn.base import clone #clone classifier in iteration
skfolds = StratifiedKFold(n_splits=3, random_state=42)
for train_index, test_index in skfolds.split(X_train, y_train_5):
clone_clf = clone(sgd_classifier)
X_train_folds = X_train[train_index]
.....
clone_clf.fit(X_train_folds, y_train_folds)
y_pred = clone_clf.predict(X_test_fold)
n_correct = sum(y_pred == y_test_fold)
print(n_correct / len(y_pred))
2.3 #Optional: cross evaluation, check scores
for scores, find the right threshold for recall, F1, ROC
from sklearn.model_selection import cross_val_score #score
sgd_score = cross_val_score(sgd_classifier, X_train, y_train_5, cv=3,
scoring="accuracy")
#scoring can be accuracy or other options
2.4 #Optional: check precision, recall, F1
#Precision and Recall: Precision=TP/(TP+FP) recall=TP/(TP+FN)
#F1 score, harmonic mean: F1=TP/(TP+(FN+FP)/2)
#detect bad content vidoe: prefer high precision, rejects many good video
#detct shoplifts: prefer high recall even precision low
#Some classifiers' decision_function returns decision score on input data
#can set a threshold for decision scor to filter
from sklearn.metrics import precision_score, recall_score, f1_score
print(precision_score(y_test_fold, y_pred))
print(recall_score(y_train_5, y_train_pred))
print(f1_score(y_test_fold, y_pred))
threshold = 200000
print(sgd_classifier.decision_function([some_digit])>threshold)
2.5 #Optional: calulate scores and set threshold to change precision/recall
#cross_val_predict(method="decision_function") calculate scores, not predict
#RandomForest has "predict_proba" only for score
#1st: calculate decision score for all training sets
#precision can be bumpier with threshold, recall is smooth with threshold
#2nd: set new threshold (scores>threshold), then get precision/recall
y_scores = cross_val_predict(sgd_classifier, X_train, y_train_5, cv=3,
method="decision_function")
# input 1-d arrays, return precision/recall for different thresholds
from sklearn.metrics import precision_recall_curve
precisions, recalls, thresholds = precision_recall_curve(y_train_5,
y_scores[:,1])
# plot precision/recalls vs thresholds
y_train_pred_90 = (y_scores[:,1] > 70000)
precision_score(y_train_5, y_train_pred_90)
#true, binary predict w. threshold
recall_score(y_train_5, y_train_pred_90)
# true, binary predict w. new threshold
2.6 # Optional:ROC curve, opposite to precicion/recall
# receiver operating characteristic (ROC) Curve for binary classifiers
# plot true positive rate (TPR) against false positive rate (FPR)
# high TRP -> high FPR, choose estimator away from diagonal (random classifier)
# compare classifier by measure area under the curve (AUC)
# perfect classifier has AUC = 1, random classifer AUC=0.5
# precision/recall: when positive is rare, care false postive than false negative
# ROC: opposite to precision/recall
# digit 5: few 5s than other digites, so use precision/recall
from sklearn.metrics import roc_curve, roc_auc_score
# input binary targets of training set, and scores of training set
fpr, tpr, thresholds = roc_curve(y_train_5, y_scores[:,1])
roc_auc_score(y_train_5, y_scores[:,1])
# plot roc curve (fpr, tpr)
2.7 # Error analysis
# Error analysis with training set, confusion matrix between predict & real
# plot with matshow, then analyze individual
y_train_pred = cross_val_predict(sgd_classifier, X_train_scaled, y_train, cv=3)
# row is actual, column predicted, FN FP TN TP; 2x2
conf_mx = confusion_matrix(y_train, y_train_pred)
print(conf_mx)
row_sums = conf_mx.sum(axis=1, keepdims=True) #sum of images of each class
norm_conf_mx = conf_mx / row_sums #average
np.fill_diagonal(norm_conf_mx, 0)
plt.matshow(norm_conf_mx, cmap=plt.cm.gray) #show where the errors are
plt.show()
3. # MultiClass
3.1. # Multiclass Classification; N classes; Sklearn will auto detect
# Random Forest, Naive Bayes, can do multiclass
# SVM, Linear classifers, are binary only
# one_vs_all is most common (e.g. 5 or not 5), except for SVM, N classify
# one_vs_one (5 or 1, 5 or 2...) is for SVM, N x(N-1/2) classify
# sklearn auto detect and use (oVo or oVo) for binary classifiers
# oVo: the score of decision_function is n x N array (n training set number)
sgd_classifier.fit(X_train, y_train)
print(sgd_classifier.predict([some_digit]))
some_digit_scores = sgd_classifier.decision_function([some_digit])
print(np.argmax(some_digit_scores)) #the index of max score
print(sgd_classifier.classes_) #the classes to be classified (0-10)
3.2 # to force to use one_vs_one for a classifier
from sklearn.multiclass import OneVsOneClassifier
ovo_clf = OneVsOneClassifier(SGDClassifier(random_state=42))
#ovo_clf.fit(X_train, y_train) # ovo_clf.predict([some_digit])
#len(ovo_clf.estimators_) #total 45
cross_val_score(sgd_classifier, X_train, y_train, cv=3, scoring="accuracy")
------------ End of Prepare Data -------------------------
"""
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# load mnist data, save to local cache
from sklearn.datasets import fetch_mldata
custom_data_home = 'Ch3Mnist' #save to local cache
#mnist is dict, has 'data', and 'target'
#mnist = fetch_mldata('MNIST original', data_home=custom_data_home)
# inspect data shape, plot a digit
X , y = mnist['data'], mnist['target']
#print(X.shape, y.shape)
some_digit = X[36000]
some_digit_image = X[36000].reshape(28, 28)
#plt.imshow(some_digit_image, cmap=matplotlib.cm.binary, interpolation="nearest")
#plt.axis("off")
#plt.show()
#print(y[36000])
# 1.1 define train and test sets, first 60000 are training sets
X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]
# 1.2 shuffle the data; avoid sensitivity to the order of training instances
shuffle_index = np.random.permutation(60000)
X_train, y_train = X[shuffle_index], y[shuffle_index]
# 1.3 turn into a binary classifier for digit 5
y_train_5, y_test_5 = (y_train==5), (y_test==5)
# 2.1 train the binary classifier
from sklearn.linear_model import SGDClassifier
sgd_classifier = SGDClassifier(random_state=42)
sgd_classifier.fit(X_train, y_train_5)
sgd_classifier.predict([some_digit])
# 2.3 Evaluation of training set using StratifiedKFold, split test sets to n
from sklearn.model_selection import StratifiedKFold
from sklearn.base import clone
skfolds = StratifiedKFold(n_splits=3, random_state=42)
# split to n folds, interate, train n-1 fold, test on the rest fold
for train_index, test_index in skfolds.split(X_train, y_train_5):
clone_clf = clone(sgd_classifier)
X_train_folds = X_train[train_index]
y_train_folds = y_train_5[train_index]
print("index: \t", test_index)
X_test_fold = X_train[test_index]
y_test_fold = y_train_5[test_index]
# all above are using training set (even for X_test)
# after training, using test set for prediction and evaluation
clone_clf.fit(X_train_folds, y_train_folds)
y_pred = clone_clf.predict(X_test_fold)
n_correct = sum(y_pred == y_test_fold)
print(n_correct / len(y_pred))
# 2.4 Evaluate using cross_val_score, not suitable for skewed data
# scoring="accuracy" compares the % of matching classification
from sklearn.model_selection import cross_val_score
sgd_score = cross_val_score(sgd_classifier, X_train, y_train_5, cv=3,
scoring="accuracy")
#print(sgd_score)
# 2.7 evaluate using confusion matrix: find true/false positve/negtive
# first train straftied data and predict the CLEAN fold of training set
# compare with the target of training set
# cros_val_predict(): K-fold cross-valid, returns prediction on each test fold
# cros_val_predict(): K-fold cross-valid, returns evaluation scores
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import confusion_matrix
#y_train_pred is prediction of each training data, same dimension as y_train
y_train_pred = cross_val_predict(sgd_classifier, X_train, y_train_5, cv=3)
#row is actual, column predicted, FN FP TN TP; 2x2
confusionMatrix = confusion_matrix(y_train_5, y_train_pred)
# 2.4 Precision and Recall: Precision=TP/(TP+FP) recall=TP/(TP+FN)
# F1 score, harmonic mean: F1=TP/(TP+(FN+FP)/2)
# detect bad content vidoe: prefer high precision even rejects many good videos
# detct shoplifts: prefer high recall even precision
# classifier.decision_function returns decision score on some test data
from sklearn.metrics import precision_score, recall_score, f1_score
print(precision_score(y_test_fold, y_pred))
print(recall_score(y_train_5, y_train_pred))
print(f1_score(y_test_fold, y_pred))
#set a threshold, and compare to decision score, can filter at threshold
threshold = 200000
print(sgd_classifier.decision_function([some_digit])>threshold)
# 2.5 Calulate Scores of test sets, set threshold, and calcuate precision/recall
# First: scores of an estimator, return decision score for all training sets
# cross_al_predict(method="decision_function) to caluate scores, not prediction
# precision can be bumpier with threshold, recall must be smoonth with threshold
# set new threshold by scores > threshold, compare to true to get precision/recall
y_scores = cross_val_predict(sgd_classifier, X_train, y_train_5, cv=3,
method="decision_function")
# inputs are 1-d arrays, return precision/recall for different thresholds
from sklearn.metrics import precision_recall_curve
precisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores[:,1])
def plot_precision_recall_vs_threshold(precisions, recalls, thresholds):
plt.plot(thresholds, precisions[:-1], "b--", label="Precision")
plt.plot(thresholds, recalls[:-1], "g--", label="Recall")
plt.xlabel("Threshold")
plt.legend(loc="upper left")
plt.ylim([0, 1])
plot_precision_recall_vs_threshold(precisions, recalls, thresholds)
plt.show()
# set threshold for decision scores, calculate precision/recall of new threshold
y_train_pred_90 = (y_scores[:,1] > 70000)
precision_score(y_train_5, y_train_pred_90) #true, binary predict w. threshold
recall_score(y_train_5, y_train_pred_90) # true, binary predict w. new threshold
# 2.6 receiver operating characteristic (ROC) Curve for binary classifiers
# plot true positive rate (TPR) against false positive rate (FPR)
# high TRP -> high FPR, choose estimator away from diagonal (random classifier)
# compare classifier by measure area under the curve (AUC)
# perfect classifier has AUC = 1, random classifer AUC=0.5
# precision/recall: when positive is rare, care false postive than false negative
# ROC: opposite to precision/recall
# digit 5: few 5s than other digites, so use precision/recall
from sklearn.metrics import roc_curve, roc_auc_score
# input binary targets of training set, and scores of training set
fpr, tpr, thresholds = roc_curve(y_train_5, y_scores[:,1])
roc_auc_score(y_train_5, y_scores[:,1])
def plot_roc_curve(fpr, tpr, label="None"):
plt.plot(fpr, tpr, linewidth=2, label=label)
plt.plot([0, 1], [0, 1], 'k--')
plt.axis([0, 1, 0, 1])
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plot_roc_curve(fpr, tpr, "ROC")
plt.show()
# 2.6 Random Forest and others have predict_proba function, not decision_function
# to plot ROC, use proba of positive class as score
from sklearn.ensemble import RandomForestClassifier
forest_classifier = RandomForestClassifier(random_state=42)
y_probas_forest = cross_val_predict(forest_classifier, X_train, y_train_5, cv=3,
method="predict_proba")
fpr_forest, tpr_forest, thresholds_forest = roc_curve(y_train_5,
y_probas_forest[:,1])
plt.plot(fpr, tpr, "b:", label="SGD")
plot_roc_curve(fpr_forest, tpr_forest, "Random Forest")
plt.legend(loc="lower right")
plt.show()
# 3.1 Multiclass Classification; N classes; Sklearn will auto detect
# Random Forest, Naive Bayes, can do multiclass
# SVM, Linear classifers, are binary only
# one_vs_all is most common (e.g. 5 or not 5), except for SVM, N classify
# one_vs_one (5 or 1, 5 or 2...) is for SVM, N x(N-1/2) classify
# sklearn auto detect and use (oVo or oVo) for binary classifiers
# oVo: the score of decision_function is n x N array (n training set number)
sgd_classifier.fit(X_train, y_train)
print(sgd_classifier.predict([some_digit]))
some_digit_scores = sgd_classifier.decision_function([some_digit])
print(np.argmax(some_digit_scores)) #the index of max score
print(sgd_classifier.classes_) #the classes to be classified (0-10)
# 3.2 to force to use one_vs_one for a classifier
from sklearn.multiclass import OneVsOneClassifier
ovo_clf = OneVsOneClassifier(SGDClassifier(random_state=42))
#ovo_clf.fit(X_train, y_train) # ovo_clf.predict([some_digit])
#len(ovo_clf.estimators_) #total 45
cross_val_score(sgd_classifier, X_train, y_train, cv=3, scoring="accuracy")
# 1.4 Standardize the input, even for an image
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train.astype(np.float64))
cross_val_score(sgd_classifier, X_train_scaled, y_train, cv=3,
scoring="accuracy")
# Error analysis with training set, confusion matrix between predict & real
# plot with matshow, then analyze individual
y_train_pred = cross_val_predict(sgd_classifier, X_train_scaled, y_train, cv=3)
conf_mx = confusion_matrix(y_train, y_train_pred)
print(conf_mx)
row_sums = conf_mx.sum(axis=1, keepdims=True) #sum of images of each class
norm_conf_mx = conf_mx / row_sums #average
np.fill_diagonal(norm_conf_mx, 0)
plt.matshow(norm_conf_mx, cmap=plt.cm.gray) #show where the errors are
plt.show()
# Multilabel: one image has many faces; a number is even/odd and >9
# Multioutput: combination of multiclass and multilabel
# KNN Neighbor can do |
cc3682b7528c1ac43a9c41d2607cbc87c33c9c41 | GabrielRioo/Curso_em_Video | /Curso_Python/Exercícios/ex031.py | 592 | 4.03125 | 4 | #Desenvolva um programa que pergunte a distancia de uma viagem em km. Calcule o preço da passagem, cobrando R$0,50
#por km para viagens de até 200km e R$0,45 para viagens mais longas
distancia = int(input('Qual adistancia da viagem? '))
if distancia <= 200:
passagem = distancia * 0.50
print('A sua passage irá custar: R${:.2f}'.format(passagem))
else:
passagem = distancia * 0.45
print('A sua passagem irá custar: R${:.2f}'.format(passagem))
# ou
preco = distancia * 0.50 if distancia <= 200 else distancia * 0.45
print('O preço da passagem é de {}'.format(preco))
|
0b1326ab8739635fdbfd1eec2b9b74329028fd71 | marly22/python-for-everybody | /exercise_loop_while.py | 830 | 4.1875 | 4 | #Write a program that repeatedly prompts a user for
#integer numbers until the user enters 'done'.
#Once 'done' is entered, print out the largest and smallest of the numbers.
#If the user enters anything other than a valid number catch it with a try/except
#and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
smallest = None
largest = None
while True:
line = input("Enter a value:\n")
try:
line = int(line)
if smallest is None or line < smallest:
smallest = line
if largest is None or line > largest :
largest = line
except:
if line == 'Done' or line == 'done':
break
else:
print("Invalid input")
continue
print("Maximum is",largest)
print("Minimum is", smallest)
|
02b80449e1ba54cf705f62b491cfbef247a0f70f | lanttern/Principles-of-computing-science-Python-Rice- | /Homework0/9.py | 271 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 9 21:29:19 2014
@author: zhihuixie
"""
import poc_simpletest
def appendsum(lst):
for i in range(25):
lst.append(sum(lst[len(lst)-3:]))
return lst
sum_three = [0, 1, 2]
a = appendsum(sum_three)
print a[20]
|
d98e90b7c2b076b01f52d617641513293f43d5d7 | SomeProgrammerOrSomething/code_challenges | /python/ProjectEuler/p1_b.py | 100 | 3.671875 | 4 | # Multiples of 3 & 5
# Second Way:
print ( sum ( [ i for i in range(1000) if i%5==0 or i%3==0] ) )
|
f1e6108f9adab0bc7525242681ff44afa216f798 | HenriqueEstanislau/Python-exercises | /PythonExercises/Exercise3-Notepad/notepad.py | 3,197 | 4.03125 | 4 | import sqlite3
def select():
conector = sqlite3.connect("notepad.db")
cursor = conector.cursor()
sql = "SELECT * FROM notes"
cursor.execute(sql)
data = cursor.fetchall() # return all records produced by SELECT
cursor.close()
conector.close()
print("\nTable data: \n")
print("="*55)
print("{:7}{:20}{:>6}".format("id","title","description"))
print()
for d in data:
print("{:<7}{:20}{:>6}".format(d[0],d[1],d[2]))
print("="*55)
print("Found {} records".format(len(data)))
main()
def insert():
title = str(input("Enter title: "))
description = str(input("Enter description: "))
conector = sqlite3.connect("notepad.db")
cursor = conector.cursor()
sql = """
CREATE TABLE IF NOT EXISTS notes(
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
title TEXT,
description TEXT
);
"""
cursor.execute(sql)
sql = f"""
INSERT INTO notes (title, description) values('{title}', '{description}');
"""
cursor.execute(sql)
conector.commit()
print("Note added successfully!")
cursor.close
conector.close()
main()
def update():
try:
noteID = int(input("Enter note ID: "))
newTitle = str(input("Enter new note name: "))
newDescription = str(input("Enter new note description: "))
except:
print("Error")
update()
conector = sqlite3.connect("notepad.db")
cursor = conector.cursor()
cursor.execute("""
UPDATE notes
SET title = ?, description = ?
WHERE id=?
""", (newTitle,newDescription,noteID))
conector.commit()
cursor.close
conector.close()
main()
def delete():
try:
noteID = int(input("Enter note ID: "))
op = int(input(f"Are you sure you want to delete the note {noteID}?\n1 - yes\n2 - not\n>>> "))
if(op == 1):
conector = sqlite3.connect("notepad.db")
cursor = conector.cursor()
cursor.execute("""
DELETE FROM notes
WHERE id = ?
""", (noteID,))
conector.commit()
cursor.close
conector.close()
print("\nNote successfully deleted")
main()
else:
main()
except:
print("Error")
delete()
def main():
print("\nOptions:")
print("(1) - To check your notes")
print("(2) - To add a note")
print("(3) - To update a note")
print("(4) - To delete a nota")
try:
op = int(input(">>> "))
if( op > 0 and op < 5):
if(op == 1):
select()
elif(op == 2):
insert()
elif(op == 3):
update()
elif(op == 4):
delete()
else:
print("Invalid option")
main()
except:
print("Error")
main()
print("-"*24)
print("Simple notepad in python")
print("-"*24)
main()
|
d7fd279d3e3bb2b1fd0526f5de24fea09e498545 | dull-bird/DP-and-RL-demos | /shortest_path_problem/dp.py | 1,267 | 3.921875 | 4 | from shortest_path_problem import graph
#dp函数:对node节点进行一次规划,计算其到终点的最短距离,并保存路径
def dp(graph, node, J, path):
#获取node可以执行的所有action
actions = graph[node].action
#如果是最基本的问题,直接得到J和path
if 12 in actions:
J[graph[node].name] = actions[12]
path[graph[node].name] = [12]
return
#否则,利用更新公式计算最优的J,并记录path
else:
costs = {}
for action, dist in actions.items():
costs[action] = dist + J[action]
#选择最优的action
best_action = min(costs, key=costs.get)
#得到J
J[node] = costs[best_action]
#print(path)
#得到best_action的path,并在前面加入当前节点
path[node] = path[best_action].copy()
path[node].insert(0, best_action)
#从后往前遍历每一个点,得到所有的J和path
def dp_loop(graph):
J = {}
path = {}
for node in range(11, 0, -1):
dp(graph, node, J, path)
#打印最终的J和path
print("J:\n", J)
print("策略:\n", path)
if __name__ == "__main__":
#graph.n是路径图
dp_loop(graph.n) |
e8ee1dfb354910410114e0579f63a27010e5d99a | Psyconne/python-examples | /ex18.py | 388 | 3.75 | 4 | def print_two(*arg): #indent the body of every function
arg1, arg2 = arg
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_one(arg1):#:::::::::::::::
print "arg1: %r" % arg1
def print_none():
print "I got none"
print_two("Imane", "Marouane")
print_two_again("Me", "Him")
print_one("One")
print_none()
|
f7cdd75bf5d57da21d880c9587d7e4c8aa17817a | dersonf/aulaemvideo | /exercicios/ex012.py | 154 | 3.796875 | 4 | #!/usr/bin/python36
# Exercicio 012
preco = float(input('Digite o valor do produto: '))
print('O valor com desconto é de R${:.2f}'.format(preco*0.95))
|
341fefe34699bf79519b99664f78dbd868246124 | rohitagarwal28/Coursera_assignment-algorithm-toolbox | /Week2 programming challenge/week2_ass5.py | 397 | 3.5625 | 4 | def pisano(m):
a,b=0,1
for i in range(0,m*m):
a,b=b,(a+b)%m
if (a==0 and b==1):
return i+1
def fibo(n):
a=[0]*(n+1)
if n<2:
return n
a[0]=0
a[1]=1
for i in range(2,n+1):
a[i]=a[i-1]+a[i-2]
return a[-1]
n,m=map(int,input().split())
result=pisano(m)
rem=n%result
print(fibo(rem)%m)
|
a704df77548e351fe5529f366484c28395ba791a | kate-melnykova/LeetCode-solutions | /LC322-Coin-Change.py | 1,899 | 4.0625 | 4 | """
You are given coins of different denominations and a total amount of
money amount. Write a function to compute the fewest number of coins
that you need to make up that amount. If that amount of money cannot
be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
Example 1:
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Example 3:
Input: coins = [1], amount = 0
Output: 0
Example 4:
Input: coins = [1], amount = 1
Output: 1
Example 5:
Input: coins = [1], amount = 2
Output: 2
Constraints:
1 <= coins.length <= 12
1 <= coins[i] <= 2^31 - 1
0 <= amount <= 10^4
"""
from typing import List
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
if not amount:
return 0
coins = list(filter(lambda x: x <= amount, coins))
if not coins:
return -1
max_coin = max(coins)
dp = [float('inf'), ] * max_coin
dp[0] = 0
for n in range(amount):
# we can get n coins that by dp[0] steps
# then, it is possible to get (n + coin) coins with dp[0]+1 coins, where coin is one of the coin amounts
n_coins = dp.pop(0)
dp.append(float('inf'))
# then, 0-indexed entry corresponds to n+1 coins, 1-indexed - for n+2 coins, etc.
for coin in coins:
dp[coin - 1] = min(dp[coin - 1], n_coins + 1)
return dp[0] if dp[0] < float('inf') else -1
if __name__ == '__main__':
from run_tests import run_tests
correct_answers = [
[[1, 2, 5], 11, 3],
[[2, 5], 6, 3],
[[12356], 2, -1],
[[123456], 0, 0],
[[7, 5], 8, -1]
]
print(f'Running tests for coinChange')
run_tests(Solution().coinChange, correct_answers) |
b36fdbd800a1fd6dda34620ba8b04800d18d96cf | Swhite215/Code-Reference-Hardware | /raspberry_pi/Sense_HAT/sense_hat_orientation.py | 570 | 3.640625 | 4 | from sense_hat import SenseHat
from time import sleep
sense = SenseHat()
# Define some colours
p = (128, 0, 128) # Purple
b = (0, 0, 0) # Black
# Set up where each colour will display
letter_pixels = [
p, p, p, b, b, p, p, p,
p, p, b, p, p, b, p, p,
p, p, b, p, p, p, p, p,
p, p, p, b, b, p, p, p,
p, p, p, p, p, b, p, p,
p, p, b, p, p, b, p, p,
p, p, p, b, b, p, p, p,
p, p, p, p, p, p, p, p
]
sense.set_rotation(90)
# Display these colours on the LED matrix
sense.set_pixels(letter_pixels)
while True:
sleep(2)
sense.flip_h()
|
a4e5f6ab965ce959fa7bb50795ddd6c3308aa4ab | neighborpil/Py_EasyPython | /classTest.py | 1,139 | 4 | 4 | class Book(object): #최상위 클래스 object 상속
""" 책 클래스
이 클래스는 책 정보 저장
"""
def __init__(self, title, author):
""" 초기화
|name| 매개변수를 받아서 객체 멤버 변수 name에 저장한다
"""
self.title = title
self.author = author
self.borrowed = False
def borrow(self):
""" 책을 대여한다
책을 대여한다. 멤버 변수 borrowed 변수에
현재 상태를 기록한다
"""
self.borrowed = True
def takeBack(self):
""" 책을 반납한다
"""
self.borrowed = False
def printInfo(self):
log = []
log.append("Book:")
log.append(" - title : {}".format(self.title))
log.append(" - author : {}".format(self.author))
log.append(" - borrowed : {}".format(self.borrowed))
print('\n'.join(log))
b1 = Book(title = "The Ar of Cup", author = "도널드 크")
b2 = Book(title = "Design Patters : Elem", author = "Kim")
b1.printInfo()
b1.borrow()
b1.printInfo()
b1.takeBack()
b1.printInfo()
b2.printInfo()
|
0b26dfac3014929e8beda8ba6bf2092851a83f73 | asglglgl/PythonPILImage | /matpoltlibDemo/DrawColumnsChart.py | 1,419 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
绘制柱状图
"""
import matplotlib.pyplot as plt
import numpy as np
# 数据数目
n = 10
x = np.arange(n)
# 生成数据, 均匀分布(0.5, 1.0)之间
y1 = (1 - x / float(n)) * np.random.uniform(0.5, 1.0, n)
y2 = (1 - x / float(n)) * np.random.uniform(0.5, 1.0, n)
# x 横坐标的值
# height 高度 纵坐标的值
# width = 0.8 柱状图宽度
# bottom = None
# align = 'center' 可选['left'(default) | 'center']决定整个bar图分布 默认left表示默认从左边界开始绘制,center会将图绘制在中间位置
# edgecolor 边界颜色
#color 柱状图颜色
# 绘制柱状图, 向上
plt.bar(x, y1, color = 'blue', edgecolor = 'white')
# 绘制柱状图, 向下
plt.bar(x, -y2, color = 'red', edgecolor = 'white')
#zip函数会将x,y打包为((x1,y1),(x2,y2)...(xn,yn))
temp = zip(x, y2)
# 在柱状图上显示具体数值, ha水平对齐, va垂直对齐
for x, y in zip(x, y1):
# 第一个和第二个参数 描述显示的位置,第三个参数为显示的内容
plt.text(x + 0.05, y + 0.1, '%.2f' % y, ha = 'center', va = 'bottom')
for x, y in temp:
plt.text(x + 0.05, -y - 0.1, '%.2f' % y, ha = 'center', va = 'bottom')
# 设置坐标轴范围
plt.xlim(-1, n)
plt.ylim(-1.5, 1.5)
plt.title("这是标题",fontproperties = "Simhei",fontsize = "20")
# 去除坐标轴
plt.xticks(())
plt.yticks(())
plt.savefig("ColumnsChart")
plt.show()
|
f73adb75052872cd41d022f90455cca66f7b9f95 | johnvalmad/python-dsa-exercicios | /Módulo 2/jupyter.moduloloop3.exercicios.py | 3,060 | 3.984375 | 4 |
# Exercício 1 - Crie uma estrutura que pergunte ao usuário qual o dia da semana. Se o dia for igual a Domingo ou
# igual a sábado, imprima na tela "Hoje é dia de descanso", caso contrário imprima na tela "Você precisa trabalhar!"
dia = input('Que dia é hoje? ')
if dia == 'Domingo' or dia == 'Sabádo ':
print('Hoje é dia de descanso')
else:
print('Você precisa trabalhar')
# Exercício 2 - Crie uma lista de 5 frutas e verifique se a fruta 'Morango' faz parte da lista
lst_1 = ['Morango', 'Uva', 'Maça', 'Banana', 'Goiaba']
for fruta in lst_1:
if fruta == 'Morango':
print('O morango foi comprado')
# Exercício 3 - Crie uma tupla de 4 elementos, multiplique cada elemento da tupla por 2 e guarde os resultados em uma
# lista
tupla1 = (1, 8.5, 15, 150)
lst_2 = []
for i in tupla1:
new_value = i * 2
lst_2.append(new_value)
print(lst_2)
# Exercício 4 - Crie uma sequência de números pares entre 100 e 150 e imprima na tela
for i in range(100, 150, 2):
print(i)
# Exercício 5 - Crie uma variável chamada temperatura e atribua o valor 40. Enquanto temperatura for maior que 35,
# imprima as temperaturas na tela
temperatura = 40
while temperatura > 35:
print(temperatura)
temperatura = temperatura - 1
# Exercício 6 - Crie uma variável chamada contador = 0. Enquanto counter for menor que 100, imprima os valores na tela,
# mas quando for encontrado o valor 23, interrompa a execução do programa
contador = 0
while contador < 100:
if contador == 23:
break
print(contador)
contador += 1
# Exercício 7 - Crie uma lista vazia e uma variável com valor 4. Enquanto o valor da variável for menor ou igual a 20,
# adicione à lista, apenas os valores pares e imprima a lista
numeros = list()
num = 4
while (num <= 20):
numeros.append(num)
num = num + 2
print(numeros)
# Exercício 8 - Transforme o resultado desta função range em uma lista: range(5, 45, 2)
nums = range(5, 45, 2)
print(list(nums))
# Exercício 9 - Faça a correção dos erros no código abaixo e execute o programa. Dica: são 3 erros.
temperatura = float(input('Qual a temperatura? '))
if temperatura > 30
print('Vista roupas leves.')
else
print('Busque seus casacos.')
# Exercício 9 - Correção
# erros na identaçao
temperatura = float(input('Qual a temperatura? '))
if temperatura > 30:
print('Vista roupas leves.')
+else:
print('Busque seus casacos.')
# Exercício 10 - Faça um programa que conte quantas vezes a letra "r" aparece na frase abaixo. Use um placeholder na
# sua instrução de impressão
# “É melhor, muito melhor, contentar-se com a realidade; se ela não é tão brilhante como os sonhos, tem pelo menos a
# vantagem de existir.” (Machado de Assis)
frase = "É melhor, muito melhor, contentar-se com a realidade; se ela não é tão brilhante como os sonhos, tem pelo menos a vantagem de existir."
count = 0
for caracter in frase:
if caracter == 'r':
count += 1
print('A letra r na frase aparece %s'%(count))
|
08613e730491dfa64f8742cb055fe6f51f89cb2b | Honglei1990/PythonChallenge | /code/Code-03.py | 2,043 | 3.90625 | 4 | # -*- coding: utf-8 -*-
'''
第 03 题
author: Honglei1990
url:http://www.pythonchallenge.com/pc/def/equality.html
tips:One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.
(一封小信,周围有三个大保镖,两边各有一个。)一个小写字母 旁边三个大写字母
源代码网页有一些大小写英文随机组合,详情在Code-03.txt
'''
#使用正则表达式
'''
import re
text = open("Code-03.txt", 'r').read()
new_text = text
list1 = []
index = 0
# 创建符合的条件语句,patten1 完全符合 三个大写字母和一个小写字母组合,而不是四个大写字母或换行符的存在
patten1 = re.compile('[a-z][A-Z][A-Z][A-Z]([a-z])[A-Z][A-Z][A-Z][a-z]')
patten2 = re.compile('[a-z][A-Z][A-Z][A-Z]([a-z])[A-Z][A-Z][A-Z]\s')
patten3 = re.compile('\s[A-Z][A-Z][A-Z]([a-z])[A-Z][A-Z][A-Z][a-z]')
# while循环查找符合的值 给list1
while index < len(new_text)-8:
if re.search(patten1,new_text[index:index+9]):
print(index, new_text[index:index+9])
list1.append(new_text[index:index+9])
index += 9
elif re.search(patten2,new_text[index:index+9]):
print(index, new_text[index:index+9])
list1.append(new_text[index:index+9])
index += 9
elif re.search(patten3,new_text[index:index+9]):
print(index, new_text[index:index+9])
list1.append(new_text[index:index+9])
index += 9
else:
index += 1
print('\n'.join(list1))
str1 = ''
# 循环取值最小字母 生成新链接
for s in list1:
str1+=s[4]
url = 'http://www.pythonchallenge.com/pc/def/{}.html'.format(str1)
print(url)
# 使用 正则表达式 re,实例化 compile方法和 search方法
'''
# 拒绝暴力循环取值
import re
text = open("Code-03.txt", 'r').read()
# 核心内容 正则表达式 '^' 非,'()' 取值范围 ,'{3}'重复3次
pattern = '[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]'
result = re.findall(pattern,text)
url = 'http://www.pythonchallenge.com/pc/def/{}.html'.format(''.join(result))
print(url)
|
b7ddf1a60853c0f5f0e2cbc5b055fb0297bf3d8f | Nhile19/nxGraphAlgorithms2019 | /functions/local_properties.py | 224 | 3.640625 | 4 | import networkx as nx
def neighbors(G,V):
return list(nx.neighbors(G,V))
"""
def set_neighbors(G,S) #G, S = list of vertices, return set of neighbors of verticies
N = []
for x in S:
N.append() ??
"""
|
8d40292c53db6b23319104d2f6bf9fcfbe35fa3f | alexmjn/cs-sprint-challenge-hash-tables | /hashtables/ex5/ex5.py | 1,514 | 3.546875 | 4 | # Your code here
def finder(files, queries):
"""
Strategy: create a hash table of possible queries (the ends of file
names), where each key is the file name and each value is the
possible paths attached to that file name.
First, we break up the files and pop out the file names. Next, for each
of those file names, we attach the rest of the full path as a value
in the dictionary.
Finally, we run through our queries -- if they're in the dictionary,
we reattach the full path to the filename and return it as part of
our results; if they aren't, we continue the loop.
"""
path_dict = {}
for path in files:
split_strings = path.split("/")
file_name = split_strings.pop()
rest_of_path = "/".join(split_strings)
if file_name in path_dict.keys():
path_dict[file_name].append(rest_of_path)
else:
path_dict[file_name] = [rest_of_path]
result = []
for query in queries:
# combine filename, if it exists, with all existing paths to that file
if query in path_dict.keys():
for path in path_dict[query]:
found_file = (path + "/" + query)
result.append(found_file)
else:
continue
return result
if __name__ == "__main__":
files = [
'/bin/foo',
'/bin/bar',
'/usr/bin/baz'
]
queries = [
"foo",
"qux",
"baz"
]
print(finder(files, queries))
|
422a5d807a6af094ab37834aa8fa80147d7449ec | Adherer/Python-Learning | /ch2 - Python Advanced Features/Itera.py | 1,234 | 4.0625 | 4 | # 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)。
# Python的for循环抽象程度要高于C的for循环,因为Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上。
# 默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values(),
# 如果要同时迭代key和value,可以用for k, v in d.items()。
# 字符串也是可迭代对象,因此,也可以作用于for循环:
# 如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:isinstance([1,2,3], Iterable) 输出: True
# 如何对list实现类似Java那样的下标循环操作?
# 答: Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身,下面是一个例子:
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
def findMinAndMax(L):
if len(L) == 0:
return (None, None)
min = L[0]
max = L[0]
for val in L:
if val > max:
max = val
if val < min:
min = val
return (min, max) |
90748b8da0d4793c439b43ef3fe5e66950d2a1f9 | HianYoon/algorithmForAllwithPython | /ch03_search_and_sort/problem7.py | 887 | 3.765625 | 4 | # 7-1
# def search_for_indexes(target, element):
# result = []
# if not isinstance(target, list):
# print("에러")
# return
#
#
# for i in range(0, len(target)):
# if target[i] == element:
# result.append(i)
#
# return result
#
#
# example_list = [200, 99, 31, 99, 200]
# print(search_for_indexes(example_list, 200))
# 7-3
stu_no = [39, 14, 67, 105]
stu_name = ["Justin", "John", "Mike", "Summer"]
def zip_method(no):
stu_dict = dict(zip(stu_no, stu_name))
return "?" if stu_dict.get(no) is None else stu_dict[no]
def index_search_method(no):
index = -1
for i in range(0, len(stu_no)):
if stu_no[i] == no:
index = i
break
return "?" if index == -1 else stu_name[index]
print(zip_method(39))
print(zip_method(22))
print(index_search_method(39))
print(index_search_method(22))
|
4f2fb80c48dced5b943087f9eb8468f3f0a42a41 | Ge0f3/Deep_Learning_with_PyTorch | /softmax.py | 928 | 4.125 | 4 | import numpy as np
# Write a function that takes as input a list of numbers, and returns
# the list of values given by the softmax function.
def softmax(L):
expL = np.exp(L)
sumexpL = sum(expL)
result = [i/sumexpL for i in expL]
return result
def sigmoid(L):
result = [1 / float(1 + np.exp(- x)) for x in L]
return result
#Lets consider the score after the perceptron
# Duck = 2
# Bever = 1
# penguin = 0
lis = [2,1,0]
sigmoid_inputs = [2, 3, 5, 6]
result = softmax(sigmoid_inputs)
resultsig = sigmoid(sigmoid_inputs)
print(" Softmax \n \nThe probability of it being Duck is {}\nThe probability of it being Bevenr is {}\nThe probability of it being Penguin is {}\n".format(result[0],result[1],result[2]))
print(" Sigmoid \n \nThe Prediction of it being Duck is {}\nThe Prediction of it being Bevenr is {}\nThe Prediction of it being Penguin is {}\n".format(resultsig[0],resultsig[1],resultsig[2])) |
e21290c2678cce87c2d3bd4a94e96a8c2d023722 | Sumyak-Jain/Python-for-beginners | /set2.py | 190 | 3.78125 | 4 | set1={"gaurav0","gaurav1","gaurav2","gaurav3","gaurav4"}
print(set1)
set1.add("jain")
print(set1)
set1.remove("gaurav0") #type1
set1.discard("gaurav1") #type2
set1.pop() #type3
print(set1)
|
b0da86f633e4b32f2f1971f46fb6e1046bbabd2b | dhulchuk/leetcode | /maximum_subarray/main.py | 509 | 3.609375 | 4 | # array divide_and_conquer dynamic_programming
from typing import List
class Solution:
def maxSubArray(self, nums: 'List[int]') -> 'int':
mini, res = 0, nums[0]
summ, maxi = 0, 0
for x in nums:
mini = min(mini, summ)
summ += x
res = max(res, summ - mini)
return res
if __name__ == '__main__':
assert Solution().maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
r = Solution().maxSubArray([-1, -1, -1])
assert r == -1, r
|
aa5087665c60d21299ee050ee58a7555b0ef4f44 | hwangse/python-A-to-Z | /9_list_2.py | 958 | 3.671875 | 4 | def char_freq(s) :
d={}
for letter in s :
if letter.isspace() :
continue
else :
letter=letter.lower()
d[letter]=d.get(letter,0)+1
return d
s="Follow me!"
D=char_freq(s)
for a,b in D.items() :
print("{} : {}".format(a,b))
kor_score = [49,79,20,100,80]
math_score = [43,59,85,30,90]
eng_score = [49,79,48,60,100]
midterm_score = [kor_score, math_score, eng_score]
for List in midterm_score :
for score in List :
if score >= 90 :
letter='A'
elif score >= 80 :
letter='B'
elif score >= 70 :
letter='C'
elif score >=60 :
letter='D'
else :
letter='F'
print(letter,end=" ")
print()
avg=[0]*len(kor_score)
for List in midterm_score :
for i,x in enumerate(List) :
avg[i] += x
for i in range(1,6) :
print("20170%d 평균: %.2f" %(i,avg[i-1]/3))
|
1a139b7e340ce3366dd9d045cd2775ff0f80eef7 | jralipe/ccs221 | /mandala/turtle_python_name-RodnieGalvan.py | 956 | 3.546875 | 4 | import turtle
window=turtle.Screen()
window.bgcolor("black")
t=turtle.Turtle()
t.color("yellow")
t.pensize(10)
t.up()
t.left(180)
t.forward(200)
t.down()
t.right(90)
t.forward(100)
t.right(90)
t.forward(20)
r=0
while r < 21:
t.right(10)
t.forward(5)
r+=1
t.left(165)
t.forward(68)
t.up()
t.left(45)
t.forward(60)
t.down()
t.circle(50)
t.up()
t.forward(65)
t.down()
t.left(90)
t.forward(100)
t.right(90)
t.forward(20)
p=0
while p < 16:
t.right(10)
t.forward(9)
p+=1
t.right(21)
t.forward(30)
t.up()
t.left(180)
t.forward(86)
t.down()
t.left(91)
t.forward(100)
t.right(146)
t.forward(120)
t.left(146)
t.forward(100)
t.right(90)
t.up()
t.forward(20)
t.down()
t.right(90)
t.forward(100)
t.left(90)
t.up()
t.forward(20)
t.down()
t.forward(60)
t.left(180)
t.forward(60)
t.right(90)
t.forward(100)
t.right(90)
t.forward(60)
t.left(180)
t.forward(60)
t.left(90)
t.forward(50)
t.left(90)
t.forward(40)
turtle.done()
|
d946f514c6c044cbc206e5ec7b2ae9fbf8421345 | fishleongxhh/LeetCode | /Heap/HeapSort.py | 1,489 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# Author: Xu Hanhui
# 此程序使用最小堆来对数组进行降序排列(同理,可以使用最大堆对数组进行升序排列)
#nums的第一个元素不是'inf'
#loc为需要执行下沉操作的位置
#size为最大堆最后一个元素的位置
def LeftChild(loc):
return 2*loc+1
#此函数用于对nums数组的loc位置元素进行下滤,以维持堆序性
def percolateDown(nums, loc, size):
if loc <= size:
tmp, LC = nums[loc], LeftChild(loc)
while LC <= size:
NextLoc = LC
if LC+1 <= size and nums[LC+1] > nums[LC]:
NextLoc = LC+1
if nums[NextLoc] > tmp:
nums[loc], loc = nums[NextLoc], NextLoc
LC = LeftChild(loc)
else:
break
nums[loc] = tmp
#对nums进行升序排序,会原地改变数组
def HeapSort(nums):
size = len(nums) - 1 #最后一个元素的下标
#将nums初始化为一个最大堆
for loc in range(size//2, -1, -1):
percolateDown(nums, loc, size)
#不停地将堆顶元素与最后一个元素进行交换,然后更新最大堆
while size > 0:
nums[size], nums[0] = nums[0], nums[size]
size -= 1
percolateDown(nums, 0, size)
if __name__ == "__main__":
nums = [4,3,5,6,7,2,44,2,13,13,45,65,147,864,213,653,31,51,536,735,1246,376,41,4,253,75,1,3]
print(nums)
print(sorted(nums))
HeapSort(nums)
print(nums)
|
4816b3eecb85851cfbd8c9fdc672bd00a8818a4f | Jdoublee/CodingTestPractice | /programmers/Level1/두개뽑아서더하기.py | 261 | 3.640625 | 4 | def solution(numbers):
answer = []
n = len(numbers)
for i in range(n) :
for j in range(i+1, n) :
res = numbers[i] + numbers[j]
answer.append(res)
answer = list(set(answer))
answer.sort()
return answer |
46b5dc4c17f3f83149da5ab3a93eef11001b1f2c | nikolayneykov92/python | /04.conditional_statements_exercise/05.time_plus_15_minutes.py | 177 | 3.828125 | 4 | from math import floor
hour = int(input())
minutes = int(input())
hour = (hour + floor((minutes + 15) / 60)) % 24
minutes = (minutes + 15) % 60
print(f"{hour}:{minutes:02}")
|
ac2b0347ad74916d0c23d0b73e0d30954fb230ec | 3152gs/Practice_Problems | /Codes/1stNonRepeatingChar.py | 258 | 3.75 | 4 | '''Print the first non repeating character in string'''
a = "aaaadgggee"
dict = {}
for i in range (0, len(a)):
if not a[i] in dict:
dict[a[i]] = 1
else:
dict[a[i]]+=1
for x in a:
if dict[x] == 1:
print (x)
break
|
ba2b198930715467da98e565295c54dbc16076de | midquan/classwork | /classwork/cmps140/p3/analysis_student.py | 3,357 | 3.5625 | 4 | ######################
# ANALYSIS QUESTIONS #
######################
# Change these default values to obtain the specified policies through
# value iteration.
def question2():
"""
Changed noise so that the chance of them falling off the bridge is 0. This means they will always choose to go across the bridge.
There is no chance of them falling when answer noise is 0.
"""
answerDiscount = 0.9
answerNoise = 0.0
""" YOUR CODE HERE """
""" END CODE """
return answerDiscount, answerNoise
def question3a():
"""
To make it prioritize the close exit, every living move must be penalized accordingly. This allows it to focus on getting out rather then getting to the better exit.
I put a negative living reward so that it prioritized escaping over everything else.
"""
answerDiscount = 0.9
answerNoise = 0.2
answerLivingReward = -3.0
""" YOUR CODE HERE """
""" END CODE """
return answerDiscount, answerNoise, answerLivingReward
# If not possible, return 'NOT POSSIBLE'
def question3b():
"""
To make it prioritize the close exit, but avoid the cliff, I penalized living less, but I also made it less important for the answer.
This allows for it to go through the other way yet still prioritize the close exit.
"""
answerDiscount = 0.5
answerNoise = 0.2
answerLivingReward = -1.0
""" YOUR CODE HERE """
""" END CODE """
return answerDiscount, answerNoise, answerLivingReward
# If not possible, return 'NOT POSSIBLE'
def question3c():
"""
To have it prioritize the far exit, but try to get there risking the cliff, I added a penalty for living to ensure that.
"""
answerDiscount = 0.9
answerNoise = 0.2
answerLivingReward = -1.0
""" YOUR CODE HERE """
""" END CODE """
return answerDiscount, answerNoise, answerLivingReward
# If not possible, return 'NOT POSSIBLE'
def question3d():
"""
The base code already ensures that it will prioritize the distant exit, yet still avoid cliff if possible.
"""
answerDiscount = 0.9
answerNoise = 0.2
answerLivingReward = 0.0
""" YOUR CODE HERE """
""" END CODE """
return answerDiscount, answerNoise, answerLivingReward
# If not possible, return 'NOT POSSIBLE'
def question3e():
"""
Prioritize Living over absolutely everything, so make the living reward huge.
"""
answerDiscount = 0.9
answerNoise = 0.2
answerLivingReward = 50.0
""" YOUR CODE HERE """
""" END CODE """
return answerDiscount, answerNoise, answerLivingReward
# If not possible, return 'NOT POSSIBLE'
def question6():
"""
Description:
[Enter a description of what you did here.]
"""
answerEpsilon = None
answerLearningRate = None
""" YOUR CODE HERE """
""" END CODE """
return answerEpsilon, answerLearningRate
# If not possible, return 'NOT POSSIBLE'
if __name__ == '__main__':
questions = [
question2,
question3a,
question3b,
question3c,
question3d,
question3e,
question6,
]
print('Answers to analysis questions:')
for question in questions:
response = question()
print(' Question %-10s:\t%s' % (question.__name__, str(response)))
|
8048ab9875474d4796306cd2c62feda10b94634e | surajprajapati110/list | /binary_search.py | 565 | 3.9375 | 4 | #Searching:
#Binary search
print("Enter Element in List\n")
a=[int(x) for x in input().split()]
print("Original List is \n",a)
a.sort()
start=0
end=len(a)-1
mid=int((start+end)/2)
n=int(input("Enter the Number to Search in list "))
while(n!=a[mid] and start<=end):
if(n<a[mid]):
end=mid-1
else:
start=mid+1
mid=int((start+end)/2)
if(n==a[mid]):
print(n," Exist in List at a[",mid,"]")
else:
print(n,"Does not Exist in List")
input()
#Time Complexity of Linear Search = O(n)
#Time COmplexity of Binary Search O(log2n): log(n)/log(2) |
2892a5260ca14ccd1be81cff1beb7db76f4ac9db | Jewel-Hong/SC-projects | /SC101Lecture_code/SC101_week1/mouse_draw.py | 614 | 3.53125 | 4 | """
File: mouse_draw.py
Name:
------------------------
This file shows how to use campy
mouse event to draw GOval
"""
from campy.graphics.gobjects import GOval
from campy.graphics.gwindow import GWindow
from campy.gui.events.mouse import onmousedragged, onmouseclicked
# This constant controls the size of the pen stroke
SIZE = 3
window = GWindow()
def main():
onmousedragged(draw)
onmouseclicked(draw)
def draw(m):
stroke = GOval(SIZE, SIZE)
stroke.filled = True
stroke.fill_color = 'black'
window.add(stroke, x=m.x - stroke.width / 2, y=m.y - stroke.height / 2)
if __name__ == '__main__':
main()
|
3c6ed469a78399c231d6b8ec45f496385a9d5b8d | tabaresjc/code_samples | /insert-a-node.py | 781 | 3.71875 | 4 | # -*- coding: utf-8 -*-
import sys
file = open("data/links/input.txt", "r")
def raw_input():
return file.readline()
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def InsertNth(head, data, position):
node = Node(data)
if not head or position == 0:
node.next = head
return node
current = head
for n in xrange(position - 1):
current = current.next
node.next = current.next
current.next = node
return head
lines = int(raw_input().strip())
head = None
for a in xrange(lines):
d, p = map(int, raw_input().strip().split(' '))
head = InsertNth(head, d, p)
while head.next:
print head.data
head = head.next
print head.data
|
c8a628d8fadc7130708c4eaeead414641a0b9f78 | messyv/Doga | /osztahot23mal.py | 187 | 3.75 | 4 | #414
num1 = int(input("Szám="))
if (num1 % 2 == 0) and (num1 % 3 == 0):
print("Osztható 2-vel és 3-mal.")
else:
print("Egyikkel sem vagy valamelyikkel nem osztható.")
|
348a3b1df17783135385f111aedc7061d3f1e663 | BenSchomp/ProjectEuler | /06.py | 859 | 3.875 | 4 | #/usr/bin/python
# Sum square difference
# Problem 6
#
# The sum of the squares of the first ten natural numbers is:
# 1^2 + 2^2 + ... + 10^2 = 385
#
# The square of the sum of the first ten natural numbers is:
# (1 + 2 + ... + 10)^2 = 55^2 = 3025
#
# Hence the difference between the sum of the squares of the first
# ten natural numbers and the square of the sum is 3025 - 385 = 2640.
#
# Find the difference between the sum of the squares of the first
# one hundred natural numbers and the square of the sum.
def sumOfSquares( a, b ):
sum = 0
for i in xrange( a, b+1 ):
sum += i * i
return sum
def squareOfSums( a, b ):
sum = 0
for i in xrange( a, b+1 ):
sum += i
return sum * sum
def differenceOfSumOfSquares( a, b ):
return squareOfSums( a, b ) - sumOfSquares( a, b )
# main
print differenceOfSumOfSquares( 1, 100 )
|
3e06fa8d6140279e27eb50952f62389ebf424031 | BlackCyn/IshmuratovDaniilVTIP5-OOP- | /VTIP5(OOP).py | 2,888 | 4.4375 | 4 | #Создайте класс Cat. Определите атрибуты name, color, weight
#Добавьте метод под названием meow. Создайте объект класса Cat, установите атрибуты, вызовите метод meow
class Cat:
name=""
color=""
weight=0
def meow(self):
print(self.name, "сказала мяу")
mycat=Cat()
mycat.name="Луна"
mycat.color="Серый"
mycat.weight=3
mycat.meow()
print()
#Напишите код, описывающий класс Animal:
#добавьте атрибут имени животного
#добавьте метод eat выводящий "Ням-ням"
#добавьте метод getName setName
#добавьте метод makeNoise, выводящий "Имя животного говорит Грр"
#добавьте конструктор классу Animal. выводящий "Родилось новое животное Имя эивотного"
#
class Animal:
name=""
def __init__(self,newname):
self.name=newname
print("Родилось животное", self.name)
def eat(self):
print("Ням-ням")
def getName(self):
return self.name
def setName(self,newname):
self.name=newname
def makeNoise(self):
print(self.name,"говорит Гррр")
Animal=Animal("Солнце")
Animal.eat()
Animal.getName()
Animal.setName("Марс")
print(Animal.getName())
Animal.makeNoise()
print()
#Создайте класс StringVar для работы со строковыми тимов данных, содержащий
#методы set get. метод set сулжит для изменения содержимого текста
#get-для получения содержимого текста
#создайте объект типа StringVar и протестируйте его методы
class StringVar:
znach="значение"
def get(self):
return self.znach
def set(self,newznach):
self.znach=newznach
s=StringVar()
print(s.get())
s.set("Новое значение")
print(s.get())
print()
#Создайте класс точка Point, позволяющий работать с координатами (x,y).
#Добавьте необходимые методы класса
class Point:
def __init__(self, x,y):
self.x=x
self.y=y
def get(self):
print(self.x, self.y)
def move(self, dx, dy):
'''Determines where x and y move'''
self.x = self.x + dx
self.y = self.y + dy
a=Point(1,1)
b=Point(5,2)
print("Объявляем переменные")
a.get()
b.get()
print("Перемещаем переменные")
a.move(2,2)
b.move(6,6)
a.get()
b.get()
|
ed8fb17705cadaab4d4d2ec9ec60b3ca3ce99b5d | NicolasIRAGNE/cryptkat | /fonctions/rot.py | 591 | 3.578125 | 4 | # Créé par Nicolas, le 04/12/2015 en Python 3.2
from fonctions.conversion import *
def effectuerRotation(messageClair, rotation):
message =""
i = 0
for i in range(0, len(messageClair)):
if messageClair[i].isalpha() == False: #si caractère != lettre, le caractère est ajouté à la chaîne message
message += str(messageClair[i])
i = i +1
else:
messageCrypte = conversion(messageClair[i]) + rotation
messageCrypte = conversion(messageCrypte)
message += str(messageCrypte)
return(message)
|
9112b0d7c98507a9ef7f2e05fedb39baefa7f7d4 | YorkShen/LeetCode | /python/week7,8/86.py | 832 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
left = lnil = ListNode(None)
right = rnil = ListNode(None)
while head:
if head.val < x:
left.next = head
left = left.next
else:
right.next = head
right = right.next
head = head.next
right.next = None
left.next = rnil.next
return lnil.next
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
a.next = b
b.next = c
s = Solution()
r = s.partition(a, 4)
while r:
print r.val
r = r.next
|
c891968433b8cbddecb64535969b0c430bdddd82 | VZakharuk/sofrserve_pythonc | /hw_4/Distance_Between_Two_Points.py | 351 | 4.03125 | 4 | """
Vasyl Zakharuk
Python Core 355
Codewars Kata: Simple: Find The Distance Between Two Points
"""
def distance(x1, y1, x2, y2):
import math
return round(math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2), 2)
x1 = int(input("Input x1="))
y1 = int(input("Input y1="))
x2 = int(input("Input x2="))
y2 = int(input("Input y2="))
print(distance(x1, y1, x2, y2))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.