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 |
|---|---|---|---|---|---|---|
7d5cdec139b3d5f058fc453ea02cca88c3776334 | salman98ansari/Practical | /OSTL/stringlen.py | 188 | 4.03125 | 4 | def stringl(x,y):
if(len(x)<=len(y)):
return(x)
else:
return(y)
a=str(input("entr string\n"))
b=str(input("enter string\n"))
print("the shortest strinf is",stringl(a,b))
|
df6b9a2cbad6361c3ab657f2023f0da27e7a7e29 | SaloniGandhi/leetcode | /48. Rotate Image.py | 1,094 | 3.875 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
#for nxn matrix we would have n/2 cycles to complete
#we go from outer boundry to the inner one
# #x=boundry
'''
N=len(matrix)
for i in range(N//2):
#y=in the current square boundry we take 4 elems at a time
for j in range(i,N-i-1):
temp=matrix[i][j]
matrix[i][j]=matrix[N-1-j][i]
matrix[N-1-j][i]=matrix[N-1-i][N-1-j]
matrix[N - 1 - i][N - 1 - j] = matrix[j][N - 1 - i]
matrix[j][N-1-i]=temp
return matrix
'''
#take transpose and reverse
for i in range(len(matrix)):
for j in range(i,len(matrix[0])):
matrix[j][i],matrix[i][j]=matrix[i][j],matrix[j][i]
print(matrix)
for i in range(len(matrix)):
matrix[i].reverse()
return matrix
|
9170e8bad7a2641598cc800e1a414f18c21122de | mszsorondo/Pr-cticas-y-programas-viejos | /herencia.py | 1,729 | 3.640625 | 4 | class movil():
def __init__(self, marca, modelo):
self.marca=marca
self.modelo=modelo
self.marcha=False
self.acelera=False
self.frena=False
def enmarcha(self):
self.marcha=True
def acelerar(self):
self.acelera=True
def frenar(self):
self.frena=True
def estado(self):
print("Marca: ",self.marca, "\n Modelo: ", self.modelo, "\n Marcha: ", self.marcha, "\n Acelera: ", self.acelera, "\nFrena: ", self.frena)
class furgoneta(movil):
def __init__(self, espacio, mark, model):
super().__init__(mark, model)
self.espacio=espacio
def estado2(self):
super().estado()
def informarespaciodisp(self):
print ("Hay ",self.espacio, "lugares restantes")
def cargado(self, cargar):
self.cargado=cargar
if (cargar):
return "La Furgoneta esta cargada"
else:
return "falta carga"
class moto(movil):
def metwil(self):
self.wilson=("Voy haciendo la Wilson y las demás subclases no pueden")
def estado(self):
print("Marca: ",self.marca, "\n Modelo: ", self.modelo, "\n Marcha: ", self.marcha, "\n Acelera: ", self.acelera, "\nFrena: ", self.frena, "\nCaballito: ", self.wilson)
Mimoto=moto("motomel", "dakar")
Mimoto.enmarcha()
Mimoto.acelerar()
Mimoto.metwil()
Mimoto.estado()
furgo1=furgoneta(7, "Volkswagen", "Multivan")
print(furgo1.cargado(True))
furgo1.estado2()
furgo1.informarespaciodisp()
class VEléctricos():
def __init__(self):
self.autonomía=100
def cargando(self, cargar):
self.carga=cargar
if (cargar):
return "El vehículo se está cargando"
else:
return "El vehículo está desenchufado"
class BiciEléctrica(movil, VEléctricos):
pass
miBici=BiciEléctrica("Vairo", "Crossmountain") |
e4af72846506e7d5749bf8e35f2cb1c31cf5df86 | DiegoSantosWS/estudos-python | /estudo-10/lambda7.py | 537 | 3.953125 | 4 | tabuada = [
lambda x: f"{x} * 1 = " + str(x * 1),
lambda x: f"{x} * 2 = " + str(x * 2),
lambda x: f"{x} * 3 = " + str(x * 3),
lambda x: f"{x} * 4 = " + str(x * 4),
lambda x: f"{x} * 5 = " + str(x * 5),
lambda x: f"{x} * 6 = " + str(x * 6),
lambda x: f"{x} * 7 = " + str(x * 7),
lambda x: f"{x} * 8 = " + str(x * 8),
lambda x: f"{x} * 9 = " + str(x * 9),
lambda x: f"{x} * 10 = " + str(x * 10)
]
numero = int(input("Informe o numero para gerar a tabuada: "))
for x in tabuada:
print(x(numero)) |
9ba6c41d20b1a67ba1660c2b060853792bfbc6af | Lewisw3/Tutorials | /assets/person.py | 357 | 3.8125 | 4 | class Person:
num_of_people = 0
all_names = []
def __init__(self, name, age, sex, height):
# initialise instance attributes
self.name = name
self.age = age
self.sex = sex
self.height = height
# update class attributes
Person.num_of_people += 1
Person.all_names.append(self.name) |
9ec6cef75aa74ae1f212435ff4844784dd22d68a | icicchen/PythonGameProgramming | /Monkeys.py | 778 | 4.1875 | 4 | '''
We have two monkeys, a and b, the parameters a_smile and b_smile indicate if each is smiling.
This program prints "We are in trouble" if they are both smiling or if neither of them is smiling, while in other conditions, we are fine.
'''
import sys
#reading arguments from the terminal
a_smile = sys.argv[1]
b_smile = sys.argv[2]
a_smile = input("Is monkey a smiling? (Yes/No) ")
if a_smile == "Yes":
True
if a_smile == "No":
False
b_smile = input("Is monkey b smiling? (Yes/No) ")
if b_smile == "Yes":
True
if b_smile == "No":
False
if a_smile == "Yes" and b_smile == "Yes" or a_smile == "No" and b_smile == "No":
print("We are in trouble.")
if a_smile == "Yes" and b_smile == "No" or a_smile == "No" and b_smile == "Yes":
print("We are fine.")
|
d1b687cce5af6e5a68a86326935da251761e65e4 | Ashwinbicholiya/cpp-Practice | /xplore11.py | 1,533 | 3.8125 | 4 | class Product:
def __init__(self,productName,productType,unitPrice,qtyinHand):
self.productName = productName
self.productType = productType
self.unitPrice = unitPrice
self.qtyinHand =qtyinHand
class Store:
def __init__(self,productList):
self.productList = productList
def purchaseProduct(self,name,quantity):
bill=0
for p in self.productList:
if(p.productName.lower() == name.lower()and p.qtyinHand==0):
return None
elif(p.productName.lower()==name.lower() and p.qtyinhand>=quantity):
bill = p.unitPrice*quantity
p.qtyinHand=p.qtyinHand-quantity
return bill
elif(p.productName.lower()==name.lower() and p.qtyinhand<quantity):
bill=p.unitPrice*p.qtyinHand
p.qtyinHand=0
return bill
return None
n=int(input())
productList=[]
for i in range(n):
productName = input()
productType= input()
unitPrice=int(input())
qtyinHand = int(input())
productList.append(Product(productName,productType,unitPrice,qtyinHand))
obj = Store(productList)
name = input()
quantity = int(input())
bill = obj.purchaseProduct(name,quantity)
if(bill==None):
print('Product not Available')
for p in obj.productList:
print(p.productName,end=' ')
print(p.qtyinHand)
else:
print(bill)
for p in obj.productList:
print(p.productName,end=' ')
print(p.qtyinHand)
|
7710e90593d889284c80a1e87704871e042ecc70 | yinty/python100day | /day5.py | 1,320 | 3.828125 | 4 | """
求解《百钱百鸡》问题
1只公鸡5元 1只母鸡3元 3只小鸡1元 用100元买100只鸡
问公鸡 母鸡 小鸡各有多少只
Version: 0.1
Author: 骆昊
Date: 2018-03-02
"""
for x in range(0, 20):
for y in range(0, 33):
z = 100 - x - y
if 5 * x + 3 * y + z / 3 == 100:
print('公鸡: %d只, 母鸡: %d只, 小鸡: %d只' % (x, y, z))
from random import randint
money = 1000
while money > 0:
print('你的总资产为:', money)
needs_go_on = False
while True:
debt = int(input('请下注: '))
if debt > 0 and debt <= money:
break
first = randint(1, 6) + randint(1, 6)
print('玩家摇出了%d点' % first)
if first == 7 or first == 11:
print('玩家胜!')
money += debt
elif first == 2 or first == 3 or first == 12:
print('庄家胜!')
money -= debt
else:
needs_go_on = True
while needs_go_on:
current = randint(1, 6) + randint(1, 6)
print('玩家摇出了%d点' % current)
if current == 7:
print('庄家胜')
money -= debt
needs_go_on = False
elif current == first:
print('玩家胜')
money += debt
needs_go_on = False
print('你破产了, 游戏结束!')
|
8856bd76f4542c419bc2906b7a66c615b0314041 | lakshay-saini-au8/PY_playground | /hackerrank/algorithm/warmup/timeConversion.py | 239 | 3.625 | 4 | def timeConversion(s):
hh, mm, ss = s[0:len(s)-2].split(":")
s_type = s[-2:]
if s_type == "PM" and int(hh) != 12:
hh = int(hh)+12
if int(hh) == 12 and s_type == "AM":
hh = '00'
return f"{hh}:{mm}:{ss}"
|
08005368c4a53e7aad98f7d7c8019635a52bda49 | MormonJesus69420/Knowledge-Based-Systems-Theory | /ass8/knn.py | 5,804 | 4.09375 | 4 | from typing import List, Tuple, Dict
from entry import Entry
import operator
class KNN:
"""Uses KNN algorithm to classify Entry elements.
Using KNN algorithm and other entries provided to the init methods finds
which class a specific entry belongs to.
"""
def __init__(self, entries: List[Entry], k: int = 3):
"""Initialize KNN with entries and number of neighbors to consider.
Arguments:
entries (List[Entry]): List of predefined and labeled entries.
Keyword Arguments:
k (int, optional): Number of neighbors to consider, defaults to 3.
"""
self._entries = entries
self._k = k
@property
def entries(self) -> List[Entry]:
"""Get and set list of entries used in KNN algorithm"""
return self._entries
@entries.setter
def entries(self, entries: List[Entry]) -> None:
self._entries = entries
@property
def k(self) -> int:
"""Get and set number of neighbors for consideration"""
return self._k
@k.setter
def k(self, k: int) -> None:
self._k = k
def classify(self, entry: Entry) -> None:
"""Assigns label to entry based on KNN algorithm.
Uses functions get_distances, get_neighbors and get_label to assign
appropriate label to entry.
Arguments:
entry (Entry): Entry for classification
"""
if len(self.entries) < self.k:
print(f"Len of entries is {len(self.entries)} while k is {self.k}")
return
distances = self.get_distances(entry)
neighbors = self.get_neighbors(distances)
entry.label = self.get_label(neighbors)
def get_label(self, neighbors: List[Entry]) -> str:
"""Returns label shared by most of entries in list.
Going through the list of neighbors it builds up votes for labels and
the label with most votes wins and is returned.
Arguments:
neighbors (List[Entry]): List of entries.
Returns:
str: Label shared by most entries.
"""
votes = {}
for ent in neighbors:
label = ent.label
if label in votes:
votes[label] += 1
else:
votes[label] = 1
lbls = sorted(votes.items(), key=operator.itemgetter(1), reverse=True)
return lbls[0][0]
def get_neighbors(self,
distances: List[Tuple[Entry, float]]) -> List[Entry]:
"""Returns k nearest entries from list of tuples.
Goes through list of tuples with entries and their distances and finds
k nearest neighbors.
Arguments:
distances (List[Tuple[Entry, float]]): List of tuples ordered by
distance.
Returns:
List[Entry]: List of k nearest entries.
"""
neighbors = list()
for x in range(self.k):
neighbors.append(distances[x][0])
return neighbors
def get_distances(self, entry: Entry) -> List[Tuple[Entry, float]]:
"""Returns list of tuples(Entry, float) ordered by distance from entry.
Finds distance from entry to entries and puts them in ordered list or
tuples.
Arguments:
entry (Entry): Entry to calculate distances to.
Returns:
List[Tuple[Entry, float]]: List of tuples(Entry, distance).
"""
distances = list()
for ent in self.entries:
distance = self.get_distance(entry, ent)
distances.append((ent, distance))
distances.sort(key=operator.itemgetter(1))
return distances
def get_distance(self, entry1: Entry, entry2: Entry) -> float:
"""Returns euclidean distance between two entries.
Arguments:
entry1 (Entry): First entry.
entry2 (Entry): Second entry.
Returns:
float: Euclidean distance between entries.
"""
distance = 0.0
for key, value in entry1.properties.items():
distance += pow(value - entry2.properties.get(key, None), 2)
return distance
entry1 = Entry("Tom", {"Math": 6, "English": 6, "Civics": 6,
"Science": 6, "PE": 6, "History": 6}, "Excellent")
entry2 = Entry("Peter", {"Math": 1, "English": 1, "Civics": 1,
"Science": 1, "PE": 1, "History": 1}, "Poor")
entry3 = Entry("Jane", {"Math": 3, "English": 6, "Civics": 4,
"Science": 4, "PE": 4, "History": 4}, "Good")
entry4 = Entry("Jack", {"Math": 6, "English": 2, "Civics": 2,
"Science": 5, "PE": 3, "History": 3}, "Good")
entry5 = Entry("Mary", {"Math": 4, "English": 4, "Civics": 5,
"Science": 4, "PE": 3, "History": 5}, "Good")
entry6 = Entry("Phyllis", {"Math": 4, "English": 2, "Civics": 2,
"Science": 6, "PE": 2, "History": 3}, "Good")
entry7 = Entry("Ron", {"Math": 2, "English": 4, "Civics": 3,
"Science": 2, "PE": 1, "History": 2}, "Poor")
entry8 = Entry("Diane", {"Math": 5, "English": 4, "Civics": 6,
"Science": 6, "PE": 4, "History": 6}, "Excellent")
entry9 = Entry("Fiona", {"Math": 5, "English": 5, "Civics": 5,
"Science": 5, "PE": 3, "History": 5}, "Excellent")
entry10 = Entry("Peter", {"Math": 2, "English": 2, "Civics": 2,
"Science": 3, "PE": 2, "History": 1}, "Poor")
entries = [entry1, entry2, entry3, entry4, entry5,
entry6, entry7, entry8, entry9, entry10]
entry = Entry("Bob", {"Math": 6, "English": 5, "Civics": 6,
"Science": 5, "PE": 6, "History": 5})
knn = KNN(entries)
knn.classify(entry)
print(entry)
|
d0db0ba8c0392ef5df3c2f93f88eeb4df6a7ec97 | ongsuwannoo/Pre-Pro-Onsite | /MRT Blue Line2.py | 631 | 3.703125 | 4 | """ MRT Blue Line 2 """
def main():
""" input station and card """
station = input()
card = input()
if "Adult" in card:
card = 1
elif "Student" in card:
card = 0.9
elif "Elder" in card:
card = 0.5
if "Chatuchak Park" in station:
price = 21 * card
elif "Phahon Yothin" in station:
price = 23 * card
elif "Lat Phrao" in station:
price = 25 * card
elif "Ratchadaphisek" in station:
price = 28 * card
if price - int(price) >= 0.5 and card != 1:
price += 1
else:
price += 0
print(int(price))
main()
|
3681ccd885542897c170212411e73b4311fb7cff | sourabhjain19/aps-2020 | /Code Library/29_fibonacci.py | 96 | 3.53125 | 4 | n=int(input())
arr=[0]*n
arr[1]=1
for i in range(2,n):
arr[i]=arr[i-1]+arr[i-2]
print(*arr)
|
524a71473eb17df59eb61364ff786111ef9de536 | SethKwashie/PythonLabs | /DataTypes/lab7.py | 107 | 3.71875 | 4 | # Fibonacci sequence
x,y=0,1
count = 0
while count < 21 :
count +=1
print(y)
x,y = y,x+y
|
8e88860e8c8bb9242c4b5973e29d24e187b74869 | timeisen/Helpers | /revcomp_by_line.py | 331 | 3.5625 | 4 | import fileinput
import sys
def reverse_complement(seq):
"""Get reverse complement of sequence"""
nt_dict = {'A':'T', 'T': 'A', 'C': 'G', 'G':'C', 'N': 'N'}
return ''.join([nt_dict[nt] for nt in seq][::-1])
for line in fileinput.input():
newline = reverse_complement(line.strip()) + "\n"
sys.stdout.write(newline)
|
3ce0c6eb3c670695c9b00beabe8a3a8615700d42 | ShawnBatson/Sprint-Challenge--Data-Structures-Python | /names/binary_search_tree.py | 5,799 | 4.28125 | 4 | """
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree.
This part of the project comprises two days:
1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`
on the BSTNode class.
2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods
on the BSTNode class.
"""
####### BELOW IS AN INSERT. FAR DOWN IS THE ASSIGNMENT ############
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value): # RECURSION NEEDED
# compare to the new value we want to insert 8 root 3 insert
if value < self.value:
if self.left is not None: # IF self.left is already taken by a node,
self.left.insert(value) # make that (left) node call insert.
else:
# set the left to the new node with the new value
self.left = BSTNode(value)
if value >= self.value: # if new value is >= self.value
if self.right is not None: # IF self.right is taken by a node
# make that (right) node call insert
self.right.insert(value)
else:
# set the right child to the new node with new value.
self.right = BSTNode(value)
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
if self.value == target:
return True
if target < self.value:
if self.left:
return self.left.contains(target)
else:
return False
if target >= self.value:
if self.right:
return self.right.contains(target)
else:
return False
# Return the maximum value found in the tree
def get_max(self):
# set the max value to a variable
# move right from the first value, if there is no right, you are at the highest.
max_value = self.value
if self.right is None:
return max_value
else:
max_value = self.right.get_max()
return max_value
# Call the function `fn` on the value of each node
def for_each(self, fn):
# call it on the original value
# check to see if the current node has a left attribute that isn't None
if self.left is not None:
# then call this function on the left value if there is one
self.left.for_each(fn)
fn(self.value)
# check to see if the current node has a right attribute that isn't None
if self.right is not None:
# Then call this function on the right value if there is one
self.right.for_each(fn)
# Part 2 -----------------------
# Print all the values in order from low to high
# Hint: Use a recursive, depth first traversal
def in_order_print(self, node): # node will be the first object used, root structure
# if the left attribute is not none (node.left)
if node.left is not None:
self.in_order_print(node.left)
print(node.value)
if node.right is not None:
self.in_order_print(node.right)
# Print the value of every node, starting with the given node,
# in an iterative breadth first traversal
def bft_print(self, node): # create a queue for nodes
queue = [] # create a queue for nodes
queue.append(node) # add the first node to the queue
# throw out a while loop:
while len(queue) > 0: # While queue is not empty
current_node = queue.pop(0) # remove the first node from the queue
print(current_node.value) # print the removed node
# add all children to the queue (left and right)
if current_node.left is not None:
queue.append(current_node.left)
if current_node.right is not None:
queue.append(current_node.right)
# Print the value of every node, starting with the given node,
# in an iterative depth first traversal
def dft_print(self, node):
stack = [] # create the stack
stack.append(node) # append the first node
while len(stack) > 0: # while the stack exists
# pull the last value in the stack
current_node = stack.pop(len(stack)-1)
print(current_node.value) # print that value
if current_node.right: # if there is a right attribute
stack.append(current_node.right) # add this value to the stack
if current_node.left: # if there is a left attribute
stack.append(current_node.left) # add that to the stack.
# Stretch Goals -------------------------
# Note: Research may be required
# Print Pre-order recursive DFT
def pre_order_dft(self, node):
print(self.value) # print the first value
if self.left is not None:
# call the function on all left attributes down the line
self.left.pre_order_dft(self.left) # recursive
if self.right is not None:
# then call the function on all the right attributes
self.right.pre_order_dft(self.right) # recursive
# Print Post-order recursive DFT
def post_order_dft(self, node):
if self.left is not None:
self.left.post_order_dft(self.left) # call all left attributes
if self.right is not None:
self.right.post_order_dft(self.right) # call all right attributes
print(self.value) # THEN print the value.
|
fddd94248a3b9c9ce314e4672cadbfc5857ba0e5 | canoc62/trees | /median_maintenance/heap_runner.py | 1,712 | 3.625 | 4 | import sys
import time
from heaps.heaps import Heap, MinHeap
HEAP_LENGTH_DIFF_THRESH = 2
def main():
try:
f = open("text/" + sys.argv[1])
except OSError as e:
print("OS error({0}): {1}".format(e.errno, e.strerror))
sys.exit()
except:
print("Usage: 'python heap_runner.py [name_of_text_file]'")
sys.exit()
data = f.read().strip()
nums = str.split(data, "\n")
nums = [int(num) for num in nums]
k_sum, runtime = k_median_sum(nums)
print("k median sum is: " + str(k_sum) + " and it took: " + str(runtime) + " s")
f.close()
def k_median_sum(nums):
if len(nums) == 0:
return 0, time.process_time()
elif len(nums) == 1:
return nums[0], time.process_time()
else:
start_time = time.process_time()
max_heap = Heap()
min_heap = MinHeap()
first_val = nums[0]
max_heap.insert(first_val)
k_sum = first_val
for num in nums[1:]:
if len(max_heap) == 0 or num <= max_heap.peek():
max_heap.insert(num)
if len(max_heap) - len(min_heap) == HEAP_LENGTH_DIFF_THRESH:
min_heap.insert(max_heap.extract())
else:
min_heap.insert(num)
if len(min_heap) - len(max_heap) == HEAP_LENGTH_DIFF_THRESH:
max_heap.insert(min_heap.extract())
if len(max_heap) >= len(min_heap):
k_sum += max_heap.peek()
else:
k_sum += min_heap.peek()
end_time = time.process_time()
length_time = end_time - start_time
return k_sum, length_time
if __name__ == '__main__':
main()
|
c0a39fec6b9bb26084ed42982a61883b65734964 | Abhrajyoti00/Tic-Tac-Toe | /main.py | 4,871 | 3.625 | 4 | class Node:
def __init__(self, val=None):
self.val = val
self.next = {}
class Board:
def __init__(self):
self.table = [[' ']*3 for i in range(3)]
self.available = {(col, row): True for col in range(3) for row in range(3)}
self.winner = ''
def put(self, col, row, sign):
self.table[col][row] = sign
self.available[(col, row)] = False
def delete(self, move):
self.table[move[0]][move[1]] = ' '
self.available[move] = True
self.winner = ''
def __str__(self):
return '\n'+'\n---------\n'.join(' | '.join(col) for col in self.table)+'\n'
def finished(self):
for col in range(3):
if self.table[col][0] == self.table[col][1] == self.table[col][2] != ' ':
self.winner = self.table[col][0]
return True
for row in range(3):
if self.table[0][row] == self.table[1][row] == self.table[2][row] != ' ':
self.winner = self.table[0][row]
return True
if self.table[0][0] == self.table[1][1] == self.table[2][2] != ' ' \
or self.table[0][2] == self.table[1][1] == self.table[2][0] != ' ':
self.winner = self.table[1][1]
return True
if not any(self.available.values()):
return True
return False
class Player:
def __init__(self, sign):
self.sign = sign
def next_move(self):
return divmod(int(input("enter a valid box number as shown above: "))-1, 3)
def play(self, board):
while True:
row, col = self.next_move()
if row > 2 or col > 2:
print("Bad input: Invalid box number")
continue
if board.available[(row, col)]: break
print("Bad input: Box is not empty")
board.put(row, col, self.sign)
return row, col
class Bot(Player):
def __init__(self, sign):
super().__init__(sign)
self.solution = Node()
def play(self, board):
if not len(self.solution.next): self.solve(board)
else:
for move in self.solution.next:
if not board.available[move.val]:
self.solution = move
break
val = -2
for move in self.solution.next:
if board.available[move.val] and self.solution.next[move] > val:
best_move = move
val = self.solution.next[move]
print("Opponent plays:", best_move.val[0]*3+best_move.val[1]+1)
self.solution = best_move
board.put(*best_move.val, self.sign)
def let(self, board, move, sign):
wins = [-2,2][sign == self.sign]
col, row = move.val
board.put(col, row, sign)
if board.finished():
if board.winner == self.sign: wins = 1
elif board.winner == '': wins = 0
else: wins = -1
board.delete(move.val)
return wins
for col, row in board.available:
if board.available[(col,row)]:
new_move = Node((col, row))
move.next[new_move] = self.let(board, new_move, ('X', 'O')[sign == 'X'])
if sign == self.sign: wins = min(wins, move.next[new_move])
else: wins = max(wins, move.next[new_move])
board.delete(move.val)
return wins
def solve(self, board):
for col, row in board.available:
if board.available[(col, row)]:
move = Node((col, row))
self.solution.next[move] = self.let(board, move, 'O')
class Game:
def __init__(self, board, player1, player2):
print("boxes and their numbers:")
print("\n---------\n".join((' | '.join(str(row*3+col+1) for col in range(3)) for row in range(3))))
self.board = board
self.player1 = player1
self.player2 = player2
def proceed(self):
move = self.player1.play(self.board)
print(self.board)
if self.board.finished():
if self.board.winner == '': print("IT'S A DRAW!!!")
elif type(self.player2) == Bot: print(f"YOU {('LOST', 'WON')[self.board.winner == self.player1.sign]}")
else: print(f"PLAYER{(2, 1)[self.board.winner == self.player1.sign]} WINS")
return
self.player2.play(self.board)
print(self.board)
while True:
n = input("choose: 1. vs Computer 2. Two Players\nEnter the corresponding number: ")
if n == '1': p2 = Bot('O')
elif n == '2': p2 = Player('O')
else:
print("Wrong Input")
continue
game = Game(Board(), Player('X'), p2)
while True:
game.proceed()
if game.board.finished():
break
if input("enter 'q' to quit, anything else to continue: ") == 'q': break |
247062347298a57522ac144ed0ed5683529d24c3 | haxzie/stackby | /scripts/get_files.py | 312 | 3.59375 | 4 | from os.path import isfile, isdir, join
from os import listdir
""" Method to return all files in the given directory """
def getFiles(dir):
#get all the contents of the dir
#add valid file to the array
files = [filename for filename in listdir(dir) if isfile(join(dir, filename))]
return files |
71c4f87d3e5973ab59f8a75a677c239567c47644 | TheRareFox/Socket-programming | /ws_battleship_client.py | 591 | 3.640625 | 4 | import socket
##MISSING CODE
#Code to create client socket
#Code to connected client socket to server socket
print("Welcome to Battleship! Try to guess where the ship is!\n")
while True:
##MISSING CODE
#Code to store data received into a variable named 'datareceived'
datareceived =
print(datareceived, end='')
if "Enter" in datareceived:
userinput = input()
client_socket.sendall(userinput.encode()) #Code to send encoded userinput
if "YOU WON" in datareceived or "YOU LOST" in datareceived:
break
client_socket.close()
####BATTLESHIP
|
25ac4296b96af23a0b7563aafe94b9c2c807f24a | nlakritz/video-poker | /maingame.py | 7,666 | 3.828125 | 4 | # Nathan Lakritz
# Fall 2016
# natejl123@gmail.com
import random
import VideoPoker
def create_deck():
'''Creates a deck of cards by storing character pairs into a list.
The elements are then randomized with a random shuffle function.'''
suits = "CDHS" # String of suits.
ranks = "23456789TJQKA" # String of ranks.
deck = []
for i in range(len(suits)):
for j in range(len(ranks)):
deck.append(ranks[j] + suits[i])
random.shuffle(deck)
return deck
def create_hand(deck):
''' Sets a player's hand based off the first 5 elements of the deck.'''
hand = deck[:5]
deck[:5] = [] # Need to remove hand from deck.
return hand
def suit_string(s):
'''Creates a string that represents suit frequencies.'''
frequencies = list(s.items())
suit_string = ""
for x in frequencies:
suit_string += str(x[1]) # Appending single suit frequencies.
return suit_string
def rank_string(r):
'''Creates a string that represents rank frequencies.'''
frequencies = list(r.items())
rank_string = ""
for x in frequencies:
rank_string += str(x[1])
return rank_string
def outcome(suits, ranks):
'''Determines outcome of player's hand.'''
for x in suits:
if x == "5": # If all suits are the same, there has to be some type of flush.
if ranks[8] == "1" and ranks[9] == "1" and ranks[10] == "1" and ranks[11] == "1" and ranks[12] == "1": # Checking for the specific cards required for a royal flush.
ranking = "Royal Flush"
elif ranks.count("11111") == 1: # Five consecutive cards means there is a straight flush.
ranking = "Straight Flush"
else:
ranking = "Flush" # If the flush isn't royal or straight, it's standard.
return ranking
for y in ranks:
if y == "4": # Checking for a frequency of four for any given card.
ranking = "Four of a Kind"
return ranking
elif y == "3":
if ranks.count("2") == 1: # Checking for a full house before a three of a kind because it's better.
ranking = "Full House"
elif ranks.count("2") == 0:
ranking = "Three of a Kind"
return ranking
if ranks.count("11111") == 1: # Regular straight
ranking = "Straight"
elif ranks.count("2") == 2:
ranking = "Two Pair"
elif ranks[9] == "2" or ranks[10] == "2" or ranks[11] == "2" or ranks[12] == "2": # Jacks or better.
ranking = "Pair"
else:
ranking = "Nothing" # The function will only get here if it hasn't returned a winning hand.
return ranking
starting_credits = int(input("How many credits would you like to start with? (10-1000) "))
while starting_credits < 10 or starting_credits > 1000: # Input validation
starting_credits = int(input("How many credits would you like to start with? (10-1000) "))
vp = VideoPoker.VideoPoker() # Initiating video poker graphics.
vp.set_status("Hello and Welcome to Video Poker!")
def poker_round(credits, deck):
'''Runs a round of poker and keeps the user updated on game status.
Current credit balance is updated based on gameplay.
Deck is from poker_game(), which runs a deck-builder function as needed.'''
vp.display_credits(credits) # Displaying starting credits.
bet = vp.get_credits_bet() # Taking user's bet (1-5 credits).
while bet > credits:
vp.set_status("You do not have enough credits for that bet. Bet again.")
bet = vp.get_credits_bet()
vp.set_status("You bet " + str(bet) + " credits.") # Updating game status.
credits = credits - bet # Decreasing user's credit balance.
vp.display_credits(credits) # Updating the credit balance on-screen.
hand = create_hand(deck) # Creating a hand based on the given deck.
vp.set_cards(hand) # Setting the displayed cards to the hand.
holding = vp.get_held_cards() # Generating a list containing cards the user chooses to keep.
# Drawing cards from the original deck to replace the cards that aren't held by the user.
for x in range(0, 5):
if holding.count(x) != 1:
hand[x] = deck[0]
deck.pop(0)
vp.set_cards(hand) # Setting the displayed cards to the updated hand.
suit_dic = {"C": 0, "D": 0, "H": 0, "S": 0}
for i in range(len(hand)):
suit_dic[hand[i][1]] += 1 # Adding frequencies
rank_dic = {"2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0, "9": 0, "T": 0, "J": 0, "Q": 0, "K": 0, "A": 0}
for j in range(len(hand)):
rank_dic[hand[j][0]] += 1
s = suit_string(suit_dic) # Converting dictionaries to strings.
r = rank_string(rank_dic)
result = outcome(s, r)
if result == "Royal Flush": # Reading result string.
if bet != 5:
new_bal = (bet * 250) + credits # Multiplying bet by designated credit amount and then adding previous balance to create new balance.
vp.set_status("You got a ROYAL FLUSH!!!! You have earned " + str(bet * 250) + " credits!") # Updating game status.
elif bet == 5: # Special payout case.
new_bal = 4000 + credits
vp.set_status("You got a ROYAL FLUSH!!!! You have earned " + str(4000) + " credits!")
elif result == "Straight Flush":
new_bal = (bet * 50) + credits
vp.set_status("You got a Straight Flush! You have earned " + str(bet * 50) + " credits!")
elif result == "Four of a Kind":
new_bal = (bet * 25) + credits
vp.set_status("You got a Four of a Kind! You have earned " + str(bet * 25) + " credits!")
elif result == "Full House":
new_bal = (bet * 9) + credits
vp.set_status("You got a Full House! You have earned " + str(bet * 9) + " credits!")
elif result == "Flush":
new_bal = (bet * 6) + credits
vp.set_status("You got a Flush! You have earned " + str(bet * 6) + " credits!")
elif result == "Straight":
new_bal = (bet * 4) + credits
vp.set_status("You got a Straight! You have earned " + str(bet * 4) + " credits!")
elif result == "Three of a Kind":
new_bal = (bet * 3) + credits
vp.set_status("You got a Three of a Kind! You have earned " + str(bet * 3) + " credits!")
elif result == "Two Pair":
new_bal = (bet * 2) + credits
vp.set_status("You got Two Pairs! You have earned " + str(bet * 2) + " credits!")
elif result == "Pair":
new_bal = (bet * 1) + credits
vp.set_status("You got One Pair! You have earned " + str(bet * 1) + " credit(s)!")
elif result == "Nothing":
new_bal = credits
vp.set_status("You got NOTHING. You have earned NO credits :(")
vp.display_credits(new_bal) # Showing the user their new balance if it changed.
vp.await_continue_button() # Waiting for the user to continue before starting another round.
return new_bal # Credit amount to be reused for next round.
def poker_game(balance):
'''Lets the user play a game of poker until they run out of credits.'''
deck = create_deck()
while True:
if balance <= 0:
break
elif len(deck) < 10: # Shuffle a new deck if there aren't enough cards for another round.
deck = create_deck()
balance = poker_round(balance, deck)
poker_game(starting_credits) # Starting the game cycle by calling the main function.
print("You have run out of credits! GAME OVER.")
|
fb55f4c31f7fb341ca848a72ec35d3dac86642db | zmjstime/mlLearn | /doubanBook/test.py | 589 | 3.5 | 4 | import urllib2
# import urllib
# import json
import socks
import socket
socks.set_default_proxy(socks.SOCKS5, "localhost", 9150)
socket.socket = socks.socksocket
# url = 'https://api.douban.com/v2/book/1220562'
# a = urllib2.urlopen(url).read()
# a = json.loads(a)
# for x in a:
# print a[x]
url = 'http://www.douban.com'
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers = {'User-Agent': user_agent}
req = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page
|
72d34a617fc5d2cbfd307c0dba3ed95de6df952a | nunenuh/raqm | /raqm/digital.py | 250 | 3.84375 | 4 | import math
def root(n, base=9):
return n % base or n and base
def root_with_factor(n, base=9):
base_factor = math.floor((n/base))
root = n % base or n and base
if get_factor:
return root, base_factor
return root
|
1263855dc788fb12e35b4067b892c02ad59b23dc | songzy12/LeetCode | /python/234.palindrome-linked-list.py | 1,310 | 3.640625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @return {boolean}
def isPalindrome(self, head):
# use fast and slow, slow = slow.next, fast = fast.next.next
# when fast meets the end, slow is right in the middle
if not head or not head.next:
return True
count = 1
pre = head
cur,pre.next = pre.next,None
while cur:
count += 1
post, cur.next, pre = cur.next, pre, cur
cur = post
half = count // 2 - 1
cur, pre.next = pre.next, None
while half:
half -= 1
post,cur.next,pre = cur.next,pre,cur
cur = post
head1 = pre
head2 = cur.next if count % 2 else cur
# print(head1.val, head2.val)
while head1:
if head1.val != head2.val:
break
head1, head2 = head1.next, head2.next
if head1:
return False
return True
N = 2
nodes = [ListNode(i) for i in range(N)] + [ListNode(11)] + \
[ListNode(i) for i in range(N-1, -1, -1)]
for i in range(2*N):
nodes[i].next = nodes[i+1]
print(Solution().isPalindrome(nodes[0]))
|
9dd05be7c3fcb978ee91932393c343cb9a876114 | heniu75/python-milanovich | /HelloWorld.py | 745 | 4.1875 | 4 | # HelloWorld.py
csvValues = "some, csv, values"
splitValues = csvValues.split(",")
# simple looping
for item in splitValues:
print(item.strip())
# indexed for looping
for x in range(0, len(splitValues)):
print(x, splitValues[x].strip())
# boolean
a = True
b = False
aliens_found = None
# if then else
number = "" # this is not very truthy
print(f"The number is defined as '{number}'")
if number == 5:
print("The number is 5")
else:
print("The number is not 5")
# truthy vs false
if number:
print("The number's value is truthy")
else:
print("The number's value is not truthy")
# ternary operator
a = 2
b = 4
out = "bigger" if a > b else "smaller"
print(f"Ternary operator test: a ({a}) is {out} than b {b}")
|
bcb572cf074b99adc54e35218b83ea05c83ebca7 | sprithiv/Algorithm-Design | /find_cyclic_graph.py | 2,462 | 3.6875 | 4 | def find_cyclic(matrix):
n = len(matrix)
#create adjacency list from given matrix
edges = {}
for i in range(0,n):
conn_node = []
for j in range(0,n):
if matrix[i][j] != 0:
conn_node.append(j+1)
edges[i+1] = conn_node
#Variables for calling depth first search function
initial_node = 1
visited_nodes = []
depth_level = 0
parent = 1
#Calling the depth first serach function
if dfs(initial_node , edges, visited_nodes, depth_level, parent):
return True
return False
def dfs(node, edges, visited_nodes, depth_level, parent):
#variable for tracking the visited nodes
visited_nodes.append(node)
#Depth first search algorithm to find if the graph is cyclic
for adj_node in edges[node]:
if adj_node in visited_nodes and depth_level > 1 and adj_node != parent:
return True
elif adj_node not in visited_nodes:
depth_level += 1
#Recursive call
if dfs(adj_node, edges, visited_nodes, depth_level, node):
return True
return False
def main():
#Testcase 1
#matrix = [[0,12,14,0,0,0,0,20],[12,0,10,6,28,0,0,0],[14,10,0,0,0,11,0,0],
# [0,6,0,0,0,0,19,0],[0,28,0,0,0,0,0,0],[0,0,11,0,0,0,0,0],
# [0,0,0,19,0,0,0,24],[20,0,0,0,0,0,24,0]]
#Testcase 2
#matrix = [[0,5,6,0,0,0],[5,0,0,7,8,9],[6,0,0,0,0,0],[0,7,0,0,0,0],
# [0,8,0,0,0,0],[0,9,0,0,0,0]]
#Testcase 3
matrix = [[0,0,24,0,0,0,0,0,5,0,17,0,24,0,0],[0,0,0,0,20,24,10,5,17,0,15,0,0,0,0],
[24,0,0,0,0,0,0,0,28,0,0,14,10,0,0],[0,0,0,0,26,0,26,0,0,22,0,0,0,6,22],
[0,20,0,26,0,0,0,0,26,0,0,17,0,0,11],[0,24,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,10,0,26,0,0,0,0,7,0,0,7,0,0,0],[0,5,0,0,0,0,0,0,0,18,20,16,0,0,0],
[5,17,28,0,26,0,7,0,0,0,24,7,0,0,0],[0,0,0,22,0,0,0,18,0,0,0,0,0,19,0],
[17,15,0,0,0,0,0,20,24,0,0,0,0,0,19],[0,0,14,0,17,0,7,16,7,0,0,0,0,0,0],
[24,0,10,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,6,0,0,0,0,0,19,0,0,0,0,27],
[0,0,0,22,11,0,0,0,0,0,19,0,0,27,0]]
#Find if the graph contains circle
if find_cyclic(matrix):
print "Yes, the graph contains circle"
else:
print "No, the graph doesn't contain circle"
if __name__ == "__main__":
main() |
a764d2b7bd8871f45edd0fe15bd81ad1d70e9a16 | RadkaValkova/SoftUni-Web-Developer | /Programming Fundamentals Python/17 Lists Advanced Exercise/messaging.py | 416 | 3.6875 | 4 | numbers = input().split()
text = input()
text_string = [char for char in text]
get_chars = []
for num in numbers:
num = [int(n) for n in num]
index = sum(num)
for char in text_string:
if index > len(text_string):
index = index % (len(text_string))
get_chars.append(text_string[index])
text_string.remove(text_string[index])
break
print(''.join(get_chars))
|
7d64abe351a88d925596381935ae633c66d431e1 | lincolnjohnny/py4e | /2_Python_Data_Structures/Week_1/example_13.py | 173 | 3.875 | 4 | # String Library - Lowercase and Uppercase
greet = 'Hello Bob'
print(greet)
print(greet.lower())
print(greet.upper())
print('Hello Bob'.lower())
print('Hello Bob'.upper())
|
300673a2855a3dcdde860b27a3b28d9b283a93e8 | GuhanSGCIT/Trees-and-Graphs-problem | /Mex division.py | 2,484 | 3.515625 | 4 | """
Given an array A of n non-negative integers. Find the number of ways to partition/divide the array into subarrays, such that mex in each subarray is not more than k. For example, mex of the arrays [1, 2] will be 0, and that of [0, 2] will be 1, and that of [0, 1, 2] will be 3. Due to the fact that the answer can turn out to be quite large, calculate it modulo 109 + 7.
Input
The first line of the input contains two integers n, k denoting the number of elements and limit of mex.
The second line contains n space-separated integers A1, A2, ... , An .
Output
Output a single integer corresponding to the answer of the problem.
Constraints
1 ≤ n ≤ 5 * 10^5
0 ≤ k, A[i] ≤ 10^9
Example
Input:
3 1
0 1 2
Output:
2
Explanation
The valid ways of partitioning will be [[0], [1, 2]] (mex of first subarray is 1, while that of the second is zero), and [[0], [1], [2]] (mex of first subarray is 1, and that of others is 0). There is no other way to partition the array such that mex is less than or equal to 1. For example, [[0, 1], [2]] is not a valid partitioning as mex of first subarray is 2 which is more than 1.
Input:
10 3
0 1 2 3 4 0 1 2 5 3
Output:
379
input:
7 3
4 8 5 2 6 3 0
output:
64
input:
3 1
1 1 0
output:
2
input:
11 2
1 5 8 9 6 3 2 11 8 9 1
output:
1024
"""
n,k=[int(i) for i in input().split()]
l=[int(i) for i in input().split()]
cons=int(5e5+1)
mod=10**9+7
tpa=[1 for i in range(cons)]
tpa[0]=1
for i in range(1,cons):
tpa[i]=(tpa[i-1]*2)%mod
if k>n:
print(tpa[n-1])
else:
il=[[]for i in range(k+1)]
for i in range(n):
if l[i]<=k:
il[l[i]].append(i)
for i in range(k+1):
if len(il[i])==0:
print(tpa[n-1])
break
else:
pi=-1
dp=[-1 for i in range(n)]
dp[0]=1
si=max(il,key=lambda x:x[0])[0]
s=1
for i in range(1,si):
dp[i]=tpa[i]
s=(s+dp[i])%mod
ci=[0 for i in range(k+1)]
j=si
i=0
while j<n:
if l[i]>k :
s=(s-dp[i])%mod
i+=1
elif ci[l[i]]+1<len(il[l[i]]) and il[l[i]][ci[l[i]]+1]<=j:
s=(s-dp[i])%mod
ci[l[i]]+=1
i+=1
else:
dp[j]=s
pi=i
s=(s+dp[j])%mod
j+=1
print(dp[n-1]) |
1d72370f2537792428674aa66240685f0ff08f8c | jk-aneirin/Scripts-practice | /pythonScripts/super.py | 518 | 3.578125 | 4 | #coding:UTF-8
class Base(object):
def __init__(self):
pass
def super_method(self,name):
self.name=name
print self.name
class A(Base):
def __init__(self):
Base.__init__(self)#因为调用类方法,所以要传self
class B(Base):
def __init__(self):
super(B,self).__init__()
def callsuper(self,name):
super(B,self).super_method(name)#因为调用实例方法,所以不要加self。super(B,self)返回Base类的实例
b=B()
b.callsuper('hello')
|
2cb0750a0b9ce1ec2e04ffeebd0c46efde64a5ad | hidiorienta/praxis-academy | /novice/01-03/kasus/kasuscrc.py | 1,586 | 3.59375 | 4 | class Gadget:
def __init__(self, gadgetlist, price):
self.gadgetlist = gadgetlist
self.price = price
print('(Gadget: {})'.format(self.gadgetlist))
def tell(self):
print('Gadget List:"{}", Price:"{}"'.format(self.gadgetlist, self.age), end=" ")
class Brand(Gadget):
def __init__(self, brandlist, type, price, releaseyear, g1):
Gadget.__init__(self, brandlist, type, price, releaseyear, g1)
self.brandlist = brandlist
self.type = type
self.releaseyear = releaseyear
self.gadget = g1
print('(Brand: {})'.format(self.gadgetlist))
def tell(self):
Gadget.tell(self)
print('Brand: "{}", Type: "{}", Release Year: "{}"'.format(self.brandlist, self.type, self.releaseyear))
class Specification(Gadget):
def __init__(self, processor, memory, storage):
Gadget.__init__(self, gadgetlist, price)
self.processor = processor
self.memory = memory
self.storage = storage
print('(Specification: {})'.format(self.gadgetlist))
def tell(self):
Gadget.tell(self)
print('Processor: "{}", Memory: "{}", Storage: "{}"'.format(self.processor, self.memory, self.storage))
g1 = Gadget('Laptop', 50000000)
g2 = Gadget('Handphone', 10000000)
b1 = Brand('Asus', 'ROG', 50000000, 2019, g1)
b2 = Brand('Samsung', 'S10', 10000000, 2018, g2)
s1 = Specification('Intel Core i7', '16GB', '1TB', b1)
s2 = Specification('Exynos', '8GB', '512GB', b2)
print()
members = [g1, g2, b1, b2, s1, s2]
for member in members:
member.tell() |
22f255d4e0a1f925435ad7c67ac80d9c92d4a72f | navill/advanced_python | /metaprogramming/type_example.py | 2,141 | 3.546875 | 4 | def method(self):
return 1
# 인자에 해당하는 클래스를 생성한다.
# 세번째 인자의 key: 생성될 method 이름, value: 기존의 method
MyClass = type('MyClass', (object,), {'method_': method, 'attr': None})
# 위 코드는 아래 클래스와 동일한 구문
# class MyClass(object):
# def method_(self):
# return 1
def func_test():
my = MyClass()
print(my.method_()) # <__main__.MyClass object at 0x103993c88>
print(type(my))
print(MyClass.__mro__)
# func_test()
# 일반적으로 metaclass는 함수형이 아닌 type을 상속하는 클래스로 사용된다.
class Metaclass(type):
def __new__(mcs, name, bases, namespace):
return super().__new__(mcs, name, bases, namespace)
@classmethod
def __prepare__(mcs, name, bases, **kwargs):
return super().__prepare__(name, bases, **kwargs)
def __init__(cls, name, bases, namespace, **kwargs):
super().__init__(name, bases, namespace)
def __call__(cls, *args, **kwargs):
return super().__call__(*args, **kwargs)
# metaclass example
class RevealingMeta(type):
def __new__(mcs, name, bases, namespace):
print(mcs, "__new__ called")
namespace['var'] = 0
return super().__new__(mcs, name, bases, namespace)
@classmethod
def __prepare__(mcs, name, bases, **kwargs):
print(mcs, "__prepare__ called")
# return super().__prepare__(name, bases, **kwargs)
return {'a': 10}
def __init__(cls, name, bases, namespace):
print(cls, "__init__ called")
super().__init__(name, bases, namespace)
def __call__(cls, *args, **kwargs):
print(cls, "__call__ called")
return super().__call__(*args, **kwargs)
class RevealingClass(metaclass=RevealingMeta):
def __new__(cls):
print(cls, "__new__ called")
return super().__new__(cls)
def __init__(self):
print(self, "__init__ called")
super().__init__()
class SameRevealingClass:
var = 0
def __init__(self):
self.a = 10
inst = RevealingClass()
print(dir(inst))
print(inst.a, inst.var)
|
a17801cfbb07adc5a0a07ce3e9e7d7d24d3f47c8 | LourdesOshiroIgarashi/algorithms-and-programming-1-ufms | /Lists/Estrutura_de_Repetições_Aninhadas/Cauê/01.py | 82 | 3.765625 | 4 | num = 7
x = 1
while num >= 1:
print("*" * x)
x = x + 1
num = num - 1
|
3926481567ada0322036dc0a8c14f4adffd5feee | laharrell20XX/rental_store_loganharrell | /core.py | 4,912 | 3.921875 | 4 | def process_inventory(unprocessed_inventory):
'''(list of str) -> list of dict
Returns a list of inventory items as a list of item dictionaries
'''
inventory_list = []
for item in unprocessed_inventory:
if item:
item = item.strip().split(',')
item_dict = dict(
item_name=item[0],
base_rental_price=int(item[1]),
replacement_cost=int(item[2]),
in_stock=int(item[3]),
initial_stock=int(item[4]))
inventory_list.append(item_dict)
return inventory_list
def convert_inventory(inventory_list):
'''(list of dict) -> list of str
Returns a list of item dictionaries as a list of item strings
'''
unprocessed_inventory = []
for item in inventory_list:
item_str = f'{item["item_name"]},{item["base_rental_price"]},{item["replacement_cost"]},{item["in_stock"]},{item["initial_stock"]}\n'
unprocessed_inventory.append(item_str)
return unprocessed_inventory
def rent_item(item):
'''(dict) -> NoneType
decreases the in-stock number of the item being asked for by 1
'''
item['in_stock'] -= 1
def return_item(item):
'''(dict) -> NoneType
increases the in_stock number of the item being asked for by 1
'''
item['in_stock'] += 1
def add_item_to_cart(cart, item, choice):
''' (list, dict, str) -> list of lists
Adds an item to the cart; can either be an item to rent or an item to return
'''
cart.append([item, choice])
return cart
def transaction_tax(cart):
''' (list of lists [dict, str]) -> float
Finds the tax of the rented items in the cart
'''
grand_total = 0
for item in cart:
if 'rent' in item:
grand_total += item[0]['base_rental_price']
return float(f'{grand_total * .07:.2f}')
def checkout(cart):
''' (list of lists [dict, str]) -> float
Items in the cart are totalled and the total and tax is returned
'''
grand_total = 0
replacement_deposit = 0
for item in cart:
if 'rent' in item:
grand_total += item[0]['base_rental_price']
replacement_deposit += (item[0]['replacement_cost'] * .1)
if 'return' in item:
replacement_deposit -= item[0]['replacement_cost'] * .1
return float(f'{(grand_total * 1.07) + replacement_deposit:.2f}')
def check_full_stock(inventory):
''' (list of dict) -> bool
Checks the inventory to see if the entire stock is full.
'''
full_stock = False
for item in inventory:
if item['in_stock'] == item['initial_stock']:
full_stock += True
return full_stock == len(inventory)
def can_return(customer, customer_manifesto):
''' (str, list of dict) -> bool,list, None
checks the manifesto to see if the person has rented anything already
'''
for user in customer_manifesto:
for username in user.keys(): #iterates over each username
if customer == username: #checks to see who the user is in relation to the manifesto
for item in user[username]:
if item: #checks to see if they had rented something before
return True
else:
return False
def change_rented_items(cart, customer, customer_manifesto):
''' (list of lists [dict, str], str, list of dict) -> list of dict
changes the customers list of rented items based on what was in their cart
'''
new_rented_items = []
returned_items = []
for item_mode in cart:
if 'rent' in item_mode:
new_rented_items.append(item_mode[0]['item_name'])
if 'return' in item_mode:
returned_items.append(item_mode[0]['item_name'])
for item in returned_items: #add condition to see if the customer doesn't have anything out
for user in customer_manifesto:
for username in user.keys():
if username == customer and item in user[customer]:
user[customer].remove(item)
for item in new_rented_items:
for user in customer_manifesto:
for username in user.keys():
if username == customer and not user[customer]: #user doesn't have anything out
user[customer] = []
user[customer].append(item)
elif username == customer and user[customer]: #user has something out
user[customer].append(item)
return customer_manifesto
def get_rented_items(customer, customer_manifesto):
''' (str, list of dict) -> list
gets the list of items that have been rented by the customer
'''
for user in customer_manifesto:
for username in user.keys():
if customer == username:
rented_items = user[username]
return rented_items |
9543951333b68aa2bafbf257a8bc86f148750d58 | Grisson/MyPractice | /82. Remove Duplicates from Sorted List II.py | 1,973 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
result = None
resultTail = None
currentNode = head
nextNode = head.next
isDuplicate = False
if nextNode is None:
return head
while nextNode is not None:
# find a duplicated val
if currentNode.val == nextNode.val:
isDuplicate = True
else:
# find a new val
# check if previous value is duplicated
if not isDuplicate:
# add currentNode to result list
if result is None:
result = currentNode
if resultTail is None:
resultTail = currentNode
else:
resultTail.next = currentNode
resultTail = resultTail.next
# update current Node
isDuplicate = False
currentNode = nextNode
# move nextNode
nextNode = nextNode.next
if not isDuplicate:
if result is None:
result = currentNode
if resultTail is None:
resultTail = currentNode
else:
resultTail.next = currentNode
resultTail = resultTail.next
if resultTail is not None:
resultTail.next = None
return result
|
20aabb4cfd76db3cb3c39bf72c1c5246852f29e5 | businessglitch/Data-Structures-in-Python | /linked_list/linked_list.py | 5,312 | 4.09375 | 4 | class LinkedList:
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
def toString(self):
return str(self.data)
def __init__(self):
self.__size = 0
self.__head = None
self.__tail = None
# O(1)
def size(self):
return self.__size
def peekFirst(self):
if self.isEmpty(): raise Exception ('Cannot perform peek on empty list')
return self.__head.data
def peekLast(self):
if self.isEmpty(): raise Exception ('Cannot perform peek on empty list')
return self.__tail.data
# Clears out the list in O(n) time
def clear(self):
trav = self.__head
while trav is not None:
next = trav.next
trav.data = None
trav.next = trav.prev = None
trav = next
self.__head = self.__tail = None
self.__size = 0
return True
# Adds to the back of the list FIFO O(n)
def add(self, item: object):
self.addLast(item)
# Add to the head of the linked list
def addFirst(self, item: object):
if self.isEmpty():
self.__head = self.__tail = self.Node(item)
else:
newNode = self.Node(item)
self.__head.prev = newNode
newNode.next = self.__head
self.__head = newNode
self.__size += 1
# Add to the back(Tail) of the linked list
def addLast(self, item: object):
if self.isEmpty():
self.__head = self.__tail = self.Node(item)
else:
newNode = self.Node(item)
newNode.prev = self.__tail
self.__tail.next = newNode
self.__tail = newNode
self.__size += 1
def addAt(self, item: object, index:int):
if index >= self.size() or index < 0: raise Exception ('Index:{} is out of bound'.format(index))
if index == 0:
self.addFirst(item)
return
if index == self.size():
self.addLast(item)
return
i = 0
trav = self.__head
while i is not index:
trav = trav.next
newNode = self.Node(item)
newNode.next = trav
newNode.prev = trav.prev
trav.prev.next = newNode
trav.prev = newNode
self.__size += 1
def removeFirst(self):
if self.isEmpty(): raise Exception('Cannot perform removeFirst on an empty list')
next = self.__head.next
data = self.__head.data
self.__head.data = self.__head.next = None
self.__head = next
self.__size -= 1
if self.isEmpty():
self.__tail = None
return data
def removeLast(self):
if self.isEmpty(): raise Exception('Cannot perform removeFirst on an empty list')
prev = self.__tail.prev
data = self.__tail.data
self.__tail.data = self.__tail.prev = None
self.__tail = prev
self.__size -= 1
if self.isEmpty():
self.__head = None
return data
def __remove(self, node: Node) -> Node:
node.next.prev = node.prev
node.prev.next = node.next
data = node.data
node.next = node.prev = None
node.data = None
self.__size -= 1
return data
# Remove item at index and return data. O(n)
def removeAt(self, index: int):
if index >= self.size() or index < 0: raise Exception ('Index:{} is out of bound'.format(index))
if index == 0: return self.removeFirst()
if index == self.size(): return self.removeLast()
i = 0
trav = self.__head
while i is not index:
trav = trav.next
i += 1
return self.__remove(trav)
# Remove head and return data
def pop(self):
if self.isEmpty(): raise Exception ('Cannot pop from an empty list')
next = self.__head.next
data = self.__head.data
self.__head.data = None
self.__head.next = None
self.__head = next
self.__size -= 1
return data
def get(self, index: int):
if index >= self.size() or index < 0: raise Exception ('Index:{} is out of bound'.format(index))
i = 0
trav = self.__head
while i is not index:
trav = trav.next
i += 1
return trav.data
def indexOf(self, item: object):
if self.isEmpty(): return -1
i = 0
trav= self.__head
while trav is not None:
if trav.data == item:
return i
trav = trav.next
i += 1
return -1
def contains(self, item: object):
return self.indexOf(item) is not -1
def isEmpty(self):
return self.size() == 0
def toString(self):
if self.isEmpty():
return 'None'
trav = self.__head
string = trav.toString()
while trav.next is not None:
trav = trav.next
string += '-->'
string += trav.toString()
string += '-->'
string += 'None'
return string |
169a2836517c64057a68794f051f2f9f4abc1f00 | devzgabriel/python-calculator | /calc_defs/calc_part0.py | 6,151 | 3.75 | 4 | import math
def part(opcao):
str(opcao)
if opcao == '1':
soma = 0
algoritimos = int(input('Quantos Números Somar?'))
for q in range(0, algoritimos):
soma += int(input('Quais: '))
print('O resultado da soma é: ', soma)
elif opcao == '2':
mult = 1
for q in range(0, int(input('Quantos Números Multiplicar?'))):
mult = mult * int(input('Quais: '))
print('O resultado da Multiplicação é: ', mult)
elif opcao == '3':
divisao = int(input('Dividendo: ')) / int(input('Divisor: '))
print('Resultado: ', divisao)
elif opcao == '4':
angulo = math.radians(float(input('Qual o ângulo: ')))
print('Seno:{:.2}, Cosseno:{:.2}, Tangente:{:.2}'.format(math.sin(angulo), math.cos(angulo), math.tan(angulo)))
elif opcao == '5':
qtd_lin_A = int(input('Quantas Linhas na Matriz A (máx 5):'))
qtd_col_A = int(input('Quantas Colunas na Matriz A (máx 5):'))
matrizA = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
for l in range(0, qtd_lin_A):
for c in range(0, qtd_col_A):
matrizA[l][c] = int(input(f'Digite um valor para A{l + 1}{c + 1}: '))
print('\n Matriz A: ')
for l in range(0, qtd_lin_A):
for c in range(0, qtd_col_A):
print(f'[{matrizA[l][c]}]', end='')
print()
qtd_lin_B = int(input('Quantas Linhas na Matriz B (máx 5):'))
qtd_col_B = int(input('Quantas Colunas na Matriz B (máx 5):'))
matrizB = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
for l in range(0, qtd_lin_B):
for c in range(0, qtd_col_B):
matrizB[l][c] = int(input(f'Digite um valor para B{l + 1}{c + 1}: '))
print('\n Matriz B: ')
for l in range(0, qtd_lin_B):
for c in range(0, qtd_col_B):
print(f'[{matrizB[l][c]}]', end='')
print()
print('A matriz resultante é:\n ')
matrizC = []
for l in range(max(qtd_lin_A, qtd_lin_B)):
matrizC.append([])
for c in range(max(qtd_col_A, qtd_col_B)):
matrizC[l].append([])
try:
matrizC[l][c] = matrizA[l][c] + matrizB[l][c]
except:
if matrizA[l][c] < 0 or matrizA[l][c] >= 0:
matrizC[l][c] = matrizA[l][c]
else:
matrizC[l][c] = matrizB[l][c]
for l in range(len(matrizC)):
for c in range(len(matrizC[0])):
print(f'[{matrizC[l][c]}]', end='')
print()
elif opcao == '6':
qtd_lin_A = int(input('Quantas Linhas na Matriz A (máx 5):'))
qtd_col_A = int(input('Quantas Colunas na Matriz A (máx 5):'))
matrizA = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
for l in range(0, qtd_lin_A):
for c in range(0, qtd_col_A):
matrizA[l][c] = int(input(f'Digite um valor para A{l + 1}{c + 1}: '))
print('\n Matriz A: ')
for l in range(0, qtd_lin_A):
for c in range(0, qtd_col_A):
print(f'[{matrizA[l][c]}]', end='')
print()
qtd_lin_B = int(input('Quantas Linhas na Matriz B (máx 5):'))
qtd_col_B = int(input('Quantas Colunas na Matriz B (máx 5):'))
matrizB = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
for l in range(0, qtd_lin_B):
for c in range(0, qtd_col_B):
matrizB[l][c] = int(input(f'Digite um valor para B{l + 1}{c + 1}: '))
print('\n Matriz B: ')
for l in range(0, qtd_lin_B):
for c in range(0, qtd_col_B):
print(f'[{matrizA[l][c]}]', end='')
print()
if qtd_lin_B == qtd_col_A:
print('A matriz resultante é:\n ')
matrizC = []
for linha in range(qtd_lin_A):
matrizC.append([])
for coluna in range(qtd_col_B):
matrizC[linha].append(0)
for k in range(qtd_col_A):
matrizC[linha][coluna] += matrizA[linha][k] * matrizB[k][coluna]
qtd_lin_C = len(matrizC)
qtd_col_C = len(matrizC[0])
for l in range(0, qtd_lin_C):
for c in range(0, qtd_col_C):
print(f'[{matrizC[l][c]}]', end='')
print()
else:
print('A quantidade de linhas e colunas das matrizes não possibilita a multiplicação!!!')
elif opcao == '7':
qtd_lin_matriz1 = int(input('Quantas Linhas(máx 5):'))
qtd_col_matriz1 = int(input('Quantas Colunas(máx 5):'))
matriz1 = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
for l in range(0, qtd_lin_matriz1):
for c in range(0, qtd_col_matriz1):
matriz1[l][c] = int(input(f'Digite um valor para A{l+1}{c+1}: '))
print('\n Matriz A: ')
for l in range(0, qtd_lin_matriz1):
for c in range(0, qtd_col_matriz1):
print(f'[{matriz1[l][c]}]', end='')
print()
mult = int(input('Por qual número multiplicar: '))
for l in range(0, qtd_lin_matriz1):
for c in range(0, qtd_col_matriz1):
print(f'[{matriz1[l][c] * mult}]', end='')
print()
elif opcao == '8':
num = float(input('Qual o número: '))
print('A raiz qudrada de {} é: {:.3}'.format(num, num ** (1 / 2)))
elif opcao == '9':
num = float(input('Qual o número: '))
print('A raiz cubica de {} é: {:.3}'.format(num, num ** (1 / 3)))
elif opcao == '10':
base = float(input('Qual a base:'))
logaritimando = float(input('Qual o logaritimando:'))
logaritimo = math.log(logaritimando, base)
print(f'O logaritimo de {logaritimando} é {logaritimo}')
|
9c059ecfc3485560583e8345f8ccf80fb814f505 | simranmahindrakar/DAA-things | /mergerrr.py | 459 | 3.875 | 4 | def merge(a,b):
(c,m,n)=([],len(a),len(b))
(i,j,k)=(0,0,0)
while(k<m+n):
if(j==n or a[i][1]*b[j][0]>a[i][0]*b[j][1]):
c.append(a[i])
i=i+1
k=k+1
elif(i==m or a[i][1]*b[j][0]<a[i][0]*b[j][1]):
c.append(b[j])
j=j+1
k=k+1
return c
def mergesort(l):
mid=len(l)//2
a=mergesort(l[:mid])
b=mergesort(l[mid:])
return merge(a,b)
|
5d0c5768dc5d038bd6287e49146bb7d4f9bbe271 | ficherfisher/leetcode | /SortList_1.py | 570 | 3.953125 | 4 |
def sort(nums):
if len(nums) <= 1: return nums
mid = len(nums) // 2
left = sort(nums[:mid])
right = sort(nums[mid:])
return merge(left, right)
def merge(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if left[0] > right[0]:
result.append(right.pop(0))
else:
result.append(left.pop(0))
result += left
result += right
return result
if __name__ == "__main__":
nums = [-1,5,3,4]
for j, i in zip(nums, reversed(nums)):
print(i, j)
print(sort(nums))
|
5d6ea491415c407dd6fd7bdc0f45ad354f3ce52c | Auralcat/poker-simulation-python | /poker.py | 632 | 4.09375 | 4 | #!usr/bin/python3
# -*- encoding: utf-8 -*-
"""Another shot at simulating a poker game"""
import random
import os
# Just the card values here
card_values = list(range(2, 11)) + ["J", "Q", "K", "A"]
# Now, the suits (clubs, diamonds, hearts, spades):
suits = ["C", "D", "S", "H"]
# Now we pack everything together WITH LIST COMPREHENSION!
deck = [str(card)+suit for card in card_values for suit in suits]
# Drawing a card:
random.seed(os.urandom(random.randint(0,1000)))
print("The drawn card is %s." % random.choice(deck))
# Drawing a hand:
for i in range(1, 10):
print("The drawn hand is %s." % random.sample(deck, 5))
|
8a195e057b4e9e5f6591c137b1d1b12322e19147 | neequole/my-python-programming-exercises | /unsorted_solutions/question55.py | 244 | 3.96875 | 4 | """ Question 55:
Write a function to compute 5/0 and use try/except to catch the exceptions.
Hints:
Use try/except to catch exceptions.
"""
def foo():
return 5/0
try:
foo()
except ZeroDivisionError:
print('Division by zero!')
|
5146a36e1917a4e0b73c2bfc4f925016bf97bea8 | elenamoglan/Instructiunea-IF | /Problema5_IF.py | 493 | 3.65625 | 4 | '''Cunoscând data curentă exprimată prin trei numere întregi reprezentând anul, luna, ziua precum şi data naşterii unei persoane,
exprimată la fel, să se facă un program care să calculeze vârsta persoanei respective în număr de ani împliniţi.'''
z, l, a = map(int, input("Data curenta este ").split('.'))
zn, ln, an = map(int, input("Data nasterii este ").split('.'))
ar = a - an
if (l<ln) or (l==ln and z<zn):
ar -= 1
print('Numarul de ani impliniti este ', ar)
|
2eb6adcd81a2c08eec8b073ba82ce571ecb38ec2 | lixiang2017/leetcode | /leetcode-cn/0882.0_Reachable_Nodes_In_Subdivided_Graph.py | 1,202 | 3.6875 | 4 | '''
dijkstra + heap
执行用时:168 ms, 在所有 Python3 提交中击败了81.94% 的用户
内存消耗:20.3 MB, 在所有 Python3 提交中击败了93.06% 的用户
通过测试用例:49 / 49
'''
class Solution:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
g = [[] for _ in range(n)]
for u, v, w in edges:
g[u].append([v, w + 1])
g[v].append([u, w + 1])
dist = self.dijkstra(g, 0)
ans = sum(d <= maxMoves for d in dist)
for u, v, w in edges:
a = max(maxMoves - dist[u], 0)
b = max(maxMoves - dist[v], 0)
ans += min(w, a + b)
return ans
def dijkstra(self, g: List[List[List[int]]], start: int) -> List[int]:
dist = [inf] * len(g)
dist[start] = 0
h = [(0, start)]
while h:
d, x = heappop(h)
if d > dist[x]:
continue
for y, w in g[x]:
new_d = dist[x] + w
if new_d < dist[y]:
dist[y] = new_d
heappush(h, (new_d, y))
return dist
|
68ab9d165300f7945e75c098452a559151b45837 | Baidaly/datacamp-samples | /7 - introduction to data visualization with python/pyplot/pseudocolor plot from image data.py | 1,069 | 3.765625 | 4 | '''
Image data comes in many forms and it is not always appropriate to display the available channels in RGB space. In many situations, an image may be processed and analysed in some way before it is visualized in pseudocolor, also known as 'false' color.
In this exercise, you will perform a simple analysis using the image showing an astronaut as viewed from space. Instead of simply displaying the image, you will compute the total intensity across the red, green and blue channels. The result is a single two dimensional array which you will display using plt.imshow() with the 'gray' colormap.
'''
# Load the image into an array: img
img = plt.imread('480px-Astronaut-EVA.jpg')
# Print the shape of the image
print(img.shape)
# Compute the sum of the red, green and blue channels: intensity
intensity = img.sum(axis=2)
# Print the shape of the intensity
print(intensity.shape)
# Display the intensity with a colormap of 'gray'
plt.imshow(intensity, cmap='gray')
# Add a colorbar
plt.colorbar()
# Hide the axes and show the figure
plt.axis('off')
plt.show()
|
45e78ad9c06827bed93446866762b088ba1796f4 | quento/encrypting-with-python | /client.py | 5,529 | 3.640625 | 4 | import socket
import helper
from helper import simpleCipher, randomString
class SimpleClient:
"Simple client that communicats with a socket server."
server_public_key = ""
# append a random string to client secret for each connection.
client_secret = "This is Client Secret - UniqueKey=" + randomString(10)
def __init__( self, host = '127.0.0.1', port = 9500 ):
self._server = host
self._port = port
def create_socket( self ):
try:
return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
print("socket creation failed with error")
def connect_to_server( self ):
# Initial communication with server
msg = input("Type in 'Hello' to get Hi response from server: ")
server_response = self.sendToServer("Sending msg: ",msg)
print( '1. Response received: ', server_response )
#Check if response has Certificate marker in msg.
if server_response.find("CA:") > -1 or server_response.find("DB:") > -1:
response_cert = server_response
print("Sending cert to CA server .....")
# Verify Cert. with CA
CA_status = self.checkWithCA('127.0.2.1', 9000, response_cert)
if CA_status == True:
print("Certificate is valid. You may proceed")
print("Recieved public key for CA server...")
print("Public Key = " + self.server_public_key)
# TODO: Send Secret using "server public key"
print("Sending Secret using server public key")
# Create Secret.
encrypt_client_secret = simpleCipher( self.server_public_key + "~" + self.client_secret,1,'e' )
# Send Secret
server_response = self.sendToServer("2. Encrypted Secret = " + encrypt_client_secret, encrypt_client_secret)
# Check if response uses secret
if server_response.find("VojrvfLfz") > -1:
print( '- Received secret response: ' + server_response )
print( "- Deciphered: '" + simpleCipher( server_response,1,'d') + "'" )
# Now communication can proceed in a secure manner
# Create a second enccrypted message
encrypt_client_msg = simpleCipher( "Here is a test message!! :)" + "~" + self.client_secret,1,'e' )
server_response = self.sendToServer("3. Test Secret Msg = " + encrypt_client_msg, encrypt_client_msg)
print( '- Server response to secret msg: ' + server_response)
print( '- Server response decrypted: ' + simpleCipher(server_response,1,'d') )
else:
print("Warning: Certificate is invalid!!!")
def sendToServer(self,announce,msg):
""" Creates a socket and send a message.
Parameters:
announce(str): Announcement to display before message sent.
msg (str): Message to send.
return (byte): Returns the response messaage received.
"""
response_msg = ""
try:
sock = self.create_socket()
sock.connect( (self._server, self._port) )
print( announce + "...." )
sock.sendall( msg.encode() )
result = sock.recv( 4096 )
response_msg = result.decode()
except Exception as err:
print("Msg Send Error:\n {0}".format(err))
return response_msg
def checkCA(self, cert):
""" Creates a socket and send a message to CA Server.
Parameters:
cert (str): certificate to send to CA server.
Return:
status (bool): If CA validates cert or not.
"""
status = False
try:
sock = self.create_socket()
sock.connect( (self._server, self._port) )
print( "Sending CA cert for verification...." )
sock.sendall( cert.encode() )
result = sock.recv( 4096 )
response_msg = result.decode()
print( 'Response received: ', response_msg )
if response_msg != 'INVALID':
status = True
self.server_public_key = response_msg
except Exception as err:
print("CheckCA() Connection Error:\n {0}".format(err))
return status
def checkWithCA(self, host, port, cert):
""" A certificate has been received, Check with CA if it's valid
Parameters:
host (str): server ip address.
port (int): Port number used by server.
cert (str): Server certificate.
Return:
ca_response (byte): Server response.
"""
ca_client = SimpleClient(host, port)
ca_response = ca_client.checkCA(cert)
# Bring public key over from CA server instance.
self.server_public_key = ca_client.server_public_key
return ca_response
def display_helper(msg):
print("****************** ", msg, "******************")
if __name__ == "__main__":
display_helper("Simple Client")
# Test Simple Client
simple_client = SimpleClient()
# Connect to server
simple_client.connect_to_server()
display_helper("End Simple Client") |
3d7a9332c6348fbf3c93a2303fcfb4e8bfe1d0a0 | shuowenwei/LeetCodePython | /Easy/LC409LongestPalindrome.py | 485 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/longest-palindrome/
"""
class Solution:
def longestPalindrome(self, s: str) -> int:
res = 0
single_Letter = False
counterS = collections.Counter(s)
for k, v in counterS.items():
res += (v // 2) * 2
if v % 2 != 0:
single_Letter = True
if single_Letter:
return res + 1
else:
return res
|
c5a7c303362f03ac003d40d5753346d152cc0966 | getstock/GETSTOCK | /getstock/accounts/friends.py | 11,308 | 3.75 | 4 | import csv
data = []
data2 = []
data1 = []
#accept, deny, write_to_somebody, print_friends, print_request_friends, print_conversation
#login = "", password = "", list_of_friends = [ [friend_login, [conversation]] ], list_of_requests = [login]
#[login, password] -> data
#[name1, name2, friend or requeste(1/0)] -> data1
#[conversation] -> data2
with open('conversation.csv') as file:
csv_reader2 = csv.reader(file, delimiter = ',')
for row in csv_reader2:
data2.append(row)
with open('friend.csv') as file:
csv_reader1 = csv.reader(file, delimiter = ',')
for row in csv_reader1:
data1.append(row)
with open('accounts.csv') as file:
csv_reader = csv.reader(file, delimiter = ',')
for row in csv_reader:
data.append(row)
def print_friends(username):
ok = 0
for row in data:
if row[0] == username:
ok = 1
if ok == 0:
print('!!!!FAILURE!!!!')
print('This login does not exist')
return
for row in data1:
if row[2] == '1':
if (row[0] == username):
print(row[1])
elif (row[1] == username):
print(row[0])
def print_request_friends(username):
ok = 0
for row in data:
if row[0] == username:
ok = 1
if ok == 0:
print('!!!!FAILURE!!!!')
print('This login does not exist')
return
for row in data1:
if row[2] == '0':
if (row[1] == username):
print(row[0])
def print_conversation(username, friend):
if (username == friend):
print("It's your account")
return
was = 0
was1 = 0
for row in data:
if row[0] == username:
was = 1
if row[0] == friend:
was1 = 1
if was == 0:
print('!!!!FAILURE!!!!')
print('This login does not exist')
return
if was1 == 0:
print('!!!!FAILURE!!!!')
print('This friend does not exist')
return
ok = 0
for row in data1:
if row[0] == username and row[1] == friend and row[2] == '1':
ok = 1
if row[1] == username and row[0] == friend and row[2] == '1':
ok = 1
if ok == 0:
print("You are not friends")
return
for i in range(len(data1)):
yes = 0
if data1[i][0] == username and data1[i][1] == friend and data1[i][2] == '1':
yes = 1
if data1[i][0] == friend and data1[i][1] == username and data1[i][2] == '1':
yes = 1
if (yes == 1):
print(*data2[i], sep = '\n')
break
def send_message(username, friend):
if (username == friend):
print("It's your account")
return
was = 0
was1 = 0
for row in data:
if row[0] == username:
was = 1
if row[0] == friend:
was1 = 1
if was == 0:
print('!!!!FAILURE!!!!')
print('This login does not exist')
return
if was1 == 0:
print('!!!!FAILURE!!!!')
print('This friend does not exist')
return
ok = 0
for row in data1:
if row[0] == username and row[1] == friend and row[2] == '1':
ok = 1
if row[1] == username and row[0] == friend and row[2] == '1':
ok = 1
if ok == 0:
print("You are not friends")
return
text = input('Type text: ')
with open('conversation.csv', 'w', newline='') as file:
csv_writer = csv.writer(file, delimiter = ',')
for i in range(len(data1)):
if data1[i][0] == username and data1[i][1] == friend and data1[i][2] == '1':
yes = 1
if data1[i][0] == friend and data1[i][1] == username and data1[i][2] == '1':
yes = 1
if (yes == 1):
data2[i].append(username + ': ' + text)
csv_writer.writerow(data2[i])
def send_request(username, friend):
if (username == friend):
print("It's your account")
return
#existing username and friends(done)
#not friends(done)
#before no requests between them(done)
was = 0
was1 = 0
for row in data:
if row[0] == username:
was = 1
if row[0] == friend:
was1 = 1
if was == 0:
print('!!!!FAILURE!!!!')
print('This login does not exist')
return
if was1 == 0:
print('!!!!FAILURE!!!!')
print('This friend does not exist')
return
ok = 0
ok2 = 0
for row in data1:
if row[0] == username and row[1] == friend and row[2] == '1':
ok = 1
if row[1] == username and row[0] == friend and row[2] == '1':
ok = 1
if row[0] == username and row[1] == friend and row[2] == '0':
ok2 = 1
if row[0] == friend and row[1] == username and row[2] == '0':
ok2 = 1
if ok == 1:
print("You are friends")
return
if ok2 == 1:
print("One of you already has sent the request")
return
with open('conversation.csv', 'w', newline='') as file:
csv_writer2 = csv.writer(file, delimiter = ',')
with open('friend.csv', 'w', newline='') as file:
csv_writer1 = csv.writer(file, delimiter = ',')
data1.append([username, friend, 0])
data2.append([])
for i in range(len(data1)):
csv_writer2.writerow(data2[i])
csv_writer1.writerow(data1[i])
def accept_request(username, friend):
if (username == friend):
print("It's your account")
return
#existing username and friends(done)
#not friends(done)
#before no requests between them(done)
was = 0
was1 = 0
for row in data:
if row[0] == username:
was = 1
if row[0] == friend:
was1 = 1
if was == 0:
print('!!!!FAILURE!!!!')
print('This login does not exist')
return
if was1 == 0:
print('!!!!FAILURE!!!!')
print('This friend does not exist')
return
ok = 0
ok2 = 0
for row in data1:
if row[0] == username and row[1] == friend and row[2] == '1':
ok = 1
if row[1] == username and row[0] == friend and row[2] == '1':
ok = 1
if row[0] == friend and row[1] == username and row[2] == '0':
ok2 = 1
if ok == 1:
print("You are friends")
return
if ok2 == 0:
print("You don't have this request")
return
with open('friend.csv', 'w', newline='') as file:
csv_writer1 = csv.writer(file, delimiter = ',')
for row in data1:
if row[0] == friend and row[1] == username and row[2] == '0':
row[2] = 1
csv_writer1.writerow(row)
def deny_request(username, friend):
if (username == friend):
print("It's your account")
return
#existing username and friends(done)
#not friends(done)
#before no requests between them(done)
was = 0
was1 = 0
for row in data:
if row[0] == username:
was = 1
if row[0] == friend:
was1 = 1
if was == 0:
print('!!!!FAILURE!!!!')
print('This login does not exist')
return
if was1 == 0:
print('!!!!FAILURE!!!!')
print('This friend does not exist')
return
ok = 0
ok2 = 0
for row in data1:
if row[0] == username and row[1] == friend and row[2] == '1':
ok = 1
if row[1] == username and row[0] == friend and row[2] == '1':
ok = 1
if row[0] == friend and row[1] == username and row[2] == '0':
ok2 = 1
if ok == 1:
print("You are friends")
return
if ok2 == 0:
print("You don't have this request")
return
with open('conversation.csv', 'w', newline='') as file:
csv_writer2 = csv.writer(file, delimiter = ',')
with open('friend.csv', 'w', newline='') as file:
csv_writer1 = csv.writer(file, delimiter = ',')
for i in range(len(data1)):
if data1[i][0] == friend and data1[i][1] == username and data1[i][2] == '0':
continue
csv_writer1.writerow(data1[i])
csv_writer2.writerow(data2[i])
|
62d248b0afbeda15b955a73ac29c652779a3ea14 | JakubKazimierski/PythonPortfolio | /Coderbyte_algorithms/Easy/SimpleAdding/SImpleAdding.py | 542 | 4.21875 | 4 | '''
SimpleAdding from Coderbyte
October 2020 Jakub Kazimierski
'''
def SimpleAdding(num):
'''
Have the function SimpleAdding(num)
add up all the numbers from 1 to num.
For example: if the input is 4 then
your program should return 10 because
1 + 2 + 3 + 4 = 10.
For the test cases, the parameter num will
be any number from 1 to 1000.
'''
try:
# below uses formula for arythmetic sum
output = int(((num + 1)*num)/2)
return output
except(ValueError, TypeError):
return -1
|
444960ab0c95947fa272a985b318c6c4f9d96e5a | TheQYD/think-complexity-examples | /graph.py | 1,146 | 3.765625 | 4 | #!/usr/bin/python
class graph(dict):
def __init__(self, verticies=[], edges=[]):
for vertex in verticies:
self.add_vertex(vertex)
for edge in edges:
self.add_edge(edge)
def add_vertex(self, vertex):
self[vertex] = {}
def add_edge(self, edge):
v,w = e
self[v][w] = e
self[w][v] = e
def get_edge(self, vertex1, vertex2, graph):
edges = None
for vertex_one in graph:
if vertex_one.label == vertex1:
graph_inner = graph[vertex_one]
for vertex_two in graph_inner:
if vertex_two.label == vertex2:
graph_value = graph_inner[vertex_two]
return edges
class vertex(object):
def __init__(self, label=''):
self.label = label
def __repr__(self):
return 'vertex(%s)' % repr(self.label)
__str__ = __repr__
class edge(tuple):
def __new__(cls, edge1, edge2):
return tuple.__new__(cls, (edge1, edge2))
def __repr__(self):
return 'edge(%s, %s)' % (repr(self[0]), repr(self[1]))
__str__ = __repr__
if __name__ == '__main__':
v = vertex('v')
w = vertex('w')
e = edge(v,w)
g = graph([v,w], [e])
print g.get_edge('v','w',g)
|
6fc03b697de7f4c572d356ffd0f8c5a77b9d78b5 | dcontant/checkio | /restricted_sum.py | 493 | 4.0625 | 4 | def checkio(data):
'''
Given a list of numbers, you should find the sum of these numbers.
Your solution should not contain any of the banned words, even as a part of another word.
The list of banned words are as follows:
sum
import
for
while
reduce
Input: A list of numbers.
Output: The sum of numbers.
'''
try:
last = data.pop()
return checkio(data) + last
except IndexError:
return 0
|
c091152030e77e96a66a9d8df2d0f32ddcc820cf | TechWriterLisa/My-Python | /Exercises/Beginner/Exercise4.py | 405 | 3.9375 | 4 | import math
# from math import pi
var=math.pi
'''
print('Enter Radius: ')
rad=input()
rad=float(rad)
'''
rad=float(input('Enter Radius: '))
area=var * (rad ** 2)
print('The area of a circle is ' + str(area) + ' with radius of ' + str(rad))
'''
#area=pir**2
import math
bigNum=math.pi
myRad=(input('Enter the radius:'))
newMyRad=float(myRad)
myArea=float(bigNum*(newMyRad**2))
print(str(myArea))
'''
|
00388e5974d1241887235db67674e5580b78ac6b | LeetCodeBreaker/LeetCode | /048.RotateImage/clywin123/rotate.py | 409 | 3.59375 | 4 | import copy
class Solution:
# @param {integer[][]} matrix
# @return {void} Do not return anything, modify matrix in-place instead.
def rotate(self, matrix):
n = len(matrix)
if(n<=1):
return
tmp = copy.deepcopy(matrix[::-1])
for i in range(n):
for j in range(n):
matrix[i][j] = tmp[j][i]
#print matrix
return
|
077f366ca5db11d3fb89f305848d9164999eaa5f | CyrillSchwyter/awd | /aufgabe4/taylorpoloynome.py | 3,374 | 3.546875 | 4 | import sympy as sym
import numpy as npy
import matplotlib.pyplot as plt
# Verwendetes Modul fuer die Erstellung von Lambda-Funktionen
# aus mathematischen Funktionen
module = 'numpy'
def taylor_1(f, x0, symbol: sym.Symbol):
"""
Berechnet T1 (Taylorpolynom ersten Grades)
Entspricht der Tangente durch Punkt x0 der Funktion f
:param f: funktion die angenaehert weden soll
:param x0: Entwicklungstelle
:param symbol: verwendetes Sympol z.B. x
:return: taylorpolynom ersten Grades als lambda-Funktion
"""
# f.subs(symbol, x0) ersetzt das symbol mit dem konkreten Wert
# sym.diff errechnet die ableitung der funktion
fx = f.subs(symbol, x0) + sym.diff(f, symbol).subs(symbol, x0) * (x - x0)
# wandelt die expression in einen Lambda-Ausdruck um x -> y
return sym.lambdify(symbol, fx, module)
# x als Symbol definieren fuer die Funktionsgleichungen
x = sym.symbols('x')
# Punkte auf der X-Achse (von -1 bis 5 in 0.1er Schritten
xs = npy.arange(-1, 8, 0.1)
# Definition der Funktion: f(x) = (x − 2)3 + 5
# f1 = sym.sin(x)
f1 = (x - 2) ** 3 + 5
# Funktion umwandeln in eine Lambda-Funktion
# (ermoeglicht das einfache berechnen des Funktionswertes)
f1_lambda = sym.lambdify(x, f1, 'numpy')
plt.plot(xs, f1_lambda(xs), label='f(x) = (x - 2)^3 + 5', color='green', linewidth=3)
plt.plot(xs, taylor_1(f1, 1, x)(xs), 'r--', label='Erstes Taylorpolynom')
plt.title('Beispielfunktion f(x) = (x - 2)^3 + 5')
plt.legend()
plt.show()
def taylor_n(f, x0, n: int, symbol: sym.Symbol):
"""
Berechnet Tn (Taylorpolynom n-ten Grades)
:param f: funktion die angenaehert weden soll
:param x0: Entwicklungstelle
:param n: n-Taylorpolynom
:param symbol: verwendetes Sympol z.B. x
:return: taylorpolynom ersten Grades als lambda-Funktion
"""
# f.subs(symbol, x0) ersetzt das symbol mit dem konkreten Wert
# sym.diff errechnet die ableitung der funktion
fx = f.subs(symbol, x0)
for k in range(1, n + 1):
fx = fx + sym.Rational(sym.diff(f, symbol, k).evalf(subs={symbol: x0}),
sym.factorial(k)) * (x - x0) ** k
# wandelt die expression in einen Lambda-Ausdruck um x -> y
return sym.lambdify(symbol, fx, module)
plt.plot(xs, f1_lambda(xs), label='f(x) = (x - 2)^3 + 5', color='blue', linewidth=3)
plt.plot(xs, taylor_n(f1, 1, 1, x)(xs), 'r--', label='Taylorpolynom 1ten Grades')
plt.plot(xs, taylor_n(f1, 1, 2, x)(xs), 'g--', label='Taylorpolynom 2ten Grades')
plt.plot(xs, taylor_n(f1, 1, 3, x)(xs), 'y--', label='Taylorpolynom 3ten Grades')
plt.title('Beispielfunktion f(x) = (x - 2)^3 + 5')
plt.legend()
plt.show()
f2 = sym.sin(x)
f2_lambda = sym.lambdify(x, f2, module)
plt.ylim(-1.5, 6)
plt.plot(xs, f2_lambda(xs), label='f(x) = sin(x)', color='blue', linewidth=3)
plt.plot(xs, taylor_n(f2, 1, 1, x)(xs), 'g--', label='Taylorpolynom 1ten Grades')
plt.plot(xs, taylor_n(f2, 1, 2, x)(xs), 'r--', label='Taylorpolynom 2ten Grades')
plt.plot(xs, taylor_n(f2, 1, 4, x)(xs), 'c--', label='Taylorpolynom 4ten Grades')
plt.plot(xs, taylor_n(f2, 1, 8, x)(xs), 'm--', label='Taylorpolynom 8ten Grades')
plt.plot(xs, taylor_n(f2, 1, 12, x)(xs), '--', color='#666633', label='Taylorpolynom 12ten Grades')
plt.plot(xs, taylor_n(f2, 1, 15, x)(xs), '--', label='Taylorpolynom 15ten Grades')
plt.title('Beispielfunktion sin(x)')
plt.legend()
plt.show()
|
e2cfdc09ccf7df1a6dc679ed65534862aa3efb24 | DongjunLim/algorithm_study | /프로그래머스/가장 큰 수.py | 1,160 | 3.703125 | 4 | def compare(x, y):
xy = str(x) + str(y)
yx = str(y) + str(x)
return x if xy > yx else y
def partition(start, mid, end, numbers):
temp = []
i, j, k = start, mid, end
while i < mid and j <= end:
if compare(numbers[i], numbers[j]) == numbers[i]:
temp.append(numbers[i])
i += 1
else:
temp.append(numbers[j])
j += 1
while i < mid:
temp.append(numbers[i])
i += 1
while j <= end:
temp.append(numbers[j])
j += 1
numbers[start:end+1] = temp
return
def merge_sort(start, end, numbers):
if end <= start:
return
mid = (start + end) // 2
merge_sort(start, mid, numbers)
merge_sort(mid + 1, end, numbers)
partition(start, mid + 1, end, numbers)
return
def solution(numbers):
start = 0
end = len(numbers) - 1
merge_sort(start, end, numbers)
answer = ''.join([str(n) for n in numbers])
return str(int(answer))
def main():
numbers = [998, 9, 992]
print(solution(numbers))
numbers = [1, 112]
print(solution(numbers))
if __name__ == '__main__':
main() |
0507e9f102d404c6f3246752600be757133f2faa | MaxKrog/KTH | /PRGOMED/Springaren/chessboard.py | 1,789 | 3.578125 | 4 | from tkinter import *
import random
from chesssquare import ChessSquare
class ChessBoard:
def __init__(self, parent,root):
self.parent = parent
self.container = Frame(root)
self.score = 0
self.chessBoard = []
self.createBoard()
self.moveList = []
self.row = random.randrange(0,8)
self.col = random.randrange(0,8)
self.endTurn(self.row,self.col)
self.startTurn()
def createBoard(self): #Creates the Chessboard
color = ["white","darkgrey"] #The 2 colors that make up the chessboard.
for i in range(8):
tempRow = []
for n in range(8):
tempRow.append( ChessSquare(self,self.container,color[(i+n)%2],30,i,n))
self.chessBoard.append(tempRow)
def endTurn(self,row,col): #Called from clicked chesssquare
self.chessBoard[row][col].setOccupied(self.score)
self.row = row
self.col = col
self.score +=1
for move in self.moveList:
self.chessBoard[move[0]][move[1]].removeAvailable()
self.moveList=[]
self.startTurn()
def startTurn(self):
self.availableMoves()
if len(self.moveList) > 0 :
for move in self.moveList:
self.chessBoard[move[0]][move[1]].setAvailable()
else:
self.parent.finished(self.score)
def availableMoves(self): #Sends all maybe-possible moves to self.testMove
row = self.row
col = self.col
self.testMove(row+2,col+1)
self.testMove(row+2,col-1)
self.testMove(row-2,col+1)
self.testMove(row-2,col-1)
self.testMove(row+1,col+2)
self.testMove(row+1,col-2)
self.testMove(row-1,col+2)
self.testMove(row-1,col-2)
def testMove(self,row,col): #If the move is available it pushes it to self.moveList
try:
if row <= 7 and row >=0 and col <= 7 and col >= 0:
if not self.chessBoard[row][col].occupied:
self.moveList.append([row,col])
except:
pass
|
936df9b8f034ab62035494ca22a04102228987ca | Brian-McHugh/algoPrep | /Python/nth_Fib/nth_Fib.py | 593 | 4.40625 | 4 | """Implement a function recursively to get the desired
Fibonacci sequence value.
Your code should have the same input/output as the
iterative code in the instructions."""
# recursive solution
def nth_Fib(n):
if n == 0 or n == 1:
return n
else:
return nth_Fib(n - 1) + nth_Fib(n - 2)
"""
# solution using memoization
def nth_Fib(n, memoize = {0: 0, 1: 1}):
if n in memoize:
return memoize[n]
else:
memoize[n] = nth_Fib(n - 1, memoize) + nth_Fib(n - 2, memoize)
return memoize[n]
"""
# Test cases
print(nth_Fib(9))
print(nth_Fib(11))
print(nth_Fib(0))
|
899642f2dd4465473cfff75b92df302b321e30af | mpencegithub/python | /pyds/8_4.py | 253 | 3.75 | 4 | fhandle=open('romeo.txt', 'r')
words=list()
for lines in fhandle :
line=lines.rstrip()
pieces=line.split()
for piece in pieces :
if piece not in words :
words.append(piece)
words.sort()
print(words)
|
f1684ae889b0f7399e7e4680f4ae8e4f69168400 | LennyBicknel/Python-Text-Adventure | /Application/main.py | 4,998 | 3.515625 | 4 | import txtadvlib, os
from iowrapper import *
# ---------main----------
# Xander Lewis - 21/07/14
# -----------------------
def cls():
"""Clears the screen."""
clearstr = ""
for i in range(100):
clearstr += "\n"
strOut(clearstr)
def intro(name):
"""Welcomes and introduces the player to the game."""
cls()
strOut("Welcome, {0}, to [Text Adventure]!".format(name))
strOut("--- How to play -----------------------------------------------------------")
strOut("Type the direction you would like to travel, or just use the first letter.")
strOut("There are four directions: left (l), right (r), forwards (f), and back (b).")
strOut("To pick up an item, type 'take <item name>'.")
strOut("To read about an item, type 'inspect <item name>'.")
strOut("To use an item, type 'use <item name>'.")
strOut("The '?' symbol indicates that you should type something.")
strOut("---------------------------------------------------------------------------")
strIn("Press enter to continue...")
def playerStatus(player, itemList):
"""Prints information about the player."""
cls()
strOut("----{0}----".format(player.getName()))
strOut("HP: {0}".format(player.getHP()))
if(player.getInv() == []):
strOut("You are carrying nothing.")
else:
strOut("Inventory:")
for i in range(len(player.getInv())):
strOut(itemList[i].getName())
def envDesc(envs, ID):
strOut("\nYou look around...")
# Print current envs description
strOut(envs[ID].getDesc())
# If there is an env in a given direction, print its description
if(envs[ID].getLeft().strip() != "NULL"):
strOut("\nTo your left, {0}".format(envs[int(envs[ID].getLeft())].getDesc().lower()))
if(envs[ID].getFront().strip() != "NULL"):
strOut("\nIn front of you, {0}".format(envs[int(envs[ID].getFront())].getDesc().lower()))
if(envs[ID].getRight().strip() != "NULL"):
strOut("\nTo your right, {0}".format(envs[int(envs[ID].getRight())].getDesc().lower()))
if(envs[ID].getBack().strip() != "NULL"):
strOut("\nBehind you, {0}".format(envs[int(envs[ID].getBack())].getDesc().lower()))
if(envs[ID].getItems() != []):
strOut("\nYou see the following items:")
for item in envs[ID].getItems():
strOut(item.getName())
def evalCmd(cmd, player, envs):
# Moving left?
if(cmd == "left" or cmd == "l"):
if(envs[player.getLoc()].getLeft().strip() != "NULL"):
strOut("You move left...")
player.setLoc(envs[player.getLoc()].getLeft())
else:
strIn("You cannot move left.")
# Moving forwards?
elif(cmd == "forwards" or cmd == "forward" or cmd == "f"):
if(envs[player.getLoc()].getFront().strip() != "NULL"):
strOut("You move forwards...")
player.setLoc(envs[player.getLoc()].getFront())
else:
strIn("You cannot move forwards.")
# Moving right?
elif(cmd == "right" or cmd == "r"):
if(envs[player.getLoc()].getRight().strip() != "NULL"):
strOut("You move right...")
player.setLoc(envs[player.getLoc()].getRight())
else:
strIn("You cannot move right.")
# Moving back?
elif(cmd == "back" or cmd == "b"):
if(envs[player.getLoc()].getBack().strip() != "NULL"):
strOut("You move back...")
player.setLoc(envs[player.getLoc()].getBack())
else:
strIn("You cannot move back.")
# Taking up an item?
elif(cmd[0:4] == "take"):
item = cmd[5:]
player.addToInv(envs[player.getLoc()].takeItem(item))
# Inspecting an item?
elif(cmd[0:7] == "inspect"):
item = cmd[8:]
itemNotFound = True
for i in range(len(player.getInv())):
if(player.getInv()[i].getName() == item):
strIn(player.getInv()[i].getDesc())
itemNotFound = False
if(itemNotFound):
strIn("You don't have that in your inventory.")
# Something else?
else:
strIn("'{0}' doesn't make any sense.".format(cmd))
# MAIN PROGRAM ------------------------------------------
cls()
# Load data from files
itemList = txtadvlib.loadItems("data/items.dat")
envList = txtadvlib.loadEnvs("data/environments.dat", itemList)
# Create player
player = txtadvlib.createPlayer(strIn("Please tell me your name. "))
# Welcome and introduce player to game
intro(player.getName())
# --Main loop--
playing = True
while(playing):
# Print player status
playerStatus(player, itemList)
# Print current and neighbouring env descriptions
envDesc(envList, player.getLoc())
# Evaluate command from user
evalCmd(strIn("\n? ").lower(), player, envList)
|
95faf0a7685fbbd3f72c300b85b6dc87541c6aa0 | gulan/jiyi-tty | /chinese.py | 4,624 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import sqlite3
class SQL(object):
""" Operations on a flashcard deck """
@property
def question(self):
(chinese,pinyin,english,live) = self._topcard()
if live == 1:
return [chinese]
if live == 2: # easy
return [chinese,pinyin]
@property
def answer(self):
(chinese,pinyin,english,live) = self._topcard()
if live == 1:
return [pinyin, english]
if live == 2:
return [english]
def _topcard(self):
# make single query
cur = self.cx.cursor()
q0 = "select save_id,live from deck limit 1;"
(card_id,live) = next(cur.execute(q0))[0:2]
q1 = """select chinese, pinyin, english
from hsk
where hsk_id = ?;"""
card = (chinese,pinyin,english) = next(cur.execute(q1,(card_id,)))
return card + (live,)
def toss(self):
"""Remove the card from the game. This operation is also known
as discard. For testing purposes only, the removed cards are
kept in the trash."""
cur = self.cx.cursor()
r = cur.execute('select * from deck limit 1;')
(key,live) = next(r)[0:2]
live -= 1
if live == 0:
cur.execute('insert into trash values (?);', (key,))
else:
cur.execute('insert into save values (?,?);', (key,live))
cur.execute('delete from deck where save_id = ?;', (key,))
self.cx.commit()
def keep(self):
"""Save the card to the retry deck. The user may put these
cards back into play with the redo()."""
cur = self.cx.cursor()
r = cur.execute('select * from deck limit 1;')
(key, live) = next(r)[0:2]
cur.execute('insert into save values (?,?);', (key,live))
cur.execute('delete from deck where save_id = ?;', (key,))
self.cx.commit()
def restack(self):
"""Shuffle and stack any saved cards on top of the play deck."""
# TBD: recently seen cards should come last
q = """
alter table deck rename to deck0;
create table deck as
select * from (select * from save order by random())
union all
select * from deck0;
delete from save;
drop table deck0;
"""
cur = self.cx.cursor()
cur.executescript(q)
self.cx.commit()
# select * from hsk order by random() limit (select count(*)/1000 from hsk);
@property
def more(self):
cur = self.cx.cursor()
count = next(cur.execute('select count(*) from deck;'))[0]
return count > 0
@property
def gameover(self):
if self.more:
return False
cur = self.cx.cursor()
count = next(cur.execute('select count(*) from save;'))[0]
return count == 0
def __init__(self,card_count=30,dbpath='hsk2009.db'):
q1 = """
delete from deck;
delete from save;
delete from trash;
"""
q2 = """
insert into save
select hsk_id,2
from hsk
where rank_id = ?
order by random()
limit ?;
"""
q3 = """
insert into game (tm, ccnt)
values (datetime('now'), ?);
"""
self.dbpath = dbpath
self.cx = sqlite3.connect(dbpath)
cur = self.cx.cursor()
cur.executescript(q1)
cur.execute(q3,(card_count,))
cur.execute(q2,(2,card_count))
self.cx.commit()
self.restack()
def _list_saved(self):
# not for use, just remember how to join with foreign key:
q = """select * from saved,hsk where save_id = hsk.rowid;"""
cur = self.cx.cursor()
for row in cur.execute(q):
print(row)
@property
def progress(self):
"""
provide "learned/count" string
"""
q = """
select ccnt from game
where game_id = (select max(game_id) from game);
"""
cur = self.cx.cursor()
count = next(cur.execute(q))[0]
unseen = next(cur.execute("select count(*) from deck;"))[0]
missed = next(cur.execute("select count(*) from save;"))[0]
## learned = next(cur.execute("select count(*) from trash;"))[0]
## assert count == unseen + missed + learned
learned = count - unseen - missed
return "%s/%s" % (learned, count)
|
dc4fa2e780a1f57ee289a68e7dbd24335cfbb9e5 | Saranya-sharvi/saranya-training-prgm | /test.py | 551 | 4.21875 | 4 | """print("Find biggest values amoung three values: ")
var1 = int(input("enter var1: "))
var2 = int(input("enter var2: "))
var3 = int(input("enter var3: "))
if((var1 >= var2 )and (var1 >= var3)):
print("The biggest is :", var1)
if(var2 >= var3):
print("The biggest is :", var2)
else:
print("The biggest is :", var3)"""
def count_substring(string, sub_string):
cnt = 0
len_ss = len(sub_string)
for i in range(len(string) - len_ss + 1):
if string[i:i+len_ss] == sub_string:
cnt += 1
return cnt
|
8dd6b0a0a6e167d0de2c4a82747fef48bac2f311 | steamedbunss/LEARN-PYTHON-THE-HARD-WAY | /03.py | 877 | 4.59375 | 5 | #+ plus
#- minus
#/ slash
#* asterisk
#% percent
#< less-than
#> greater-than
#<= less-than-equal
#>= greater-than-equal
print("I will now count my chickens:")
print("hens", 25 + 30 / 6)
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("Is it true that 3 + 2 < 5 - 7?")
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)
print("Oh, that's why it's False.")
print("How about some more.")
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
#SHOULD SEE
I will now count my chickens:
hens 30.0
Roosters 97
Now I will count the eggs:
6.75
Is it true that 3 + 2 < 5 - 7?
What is 3 + 2? 5
What is 5-7? -2
Oh, that's why it's False.
How about some more.
Is it greater? true
Is it greater or equal? true
Is it less or equal? False |
46bdf58bd0e43ac69cd076d65fe538ea3a327aa5 | mshekhar/random-algs | /epi_solutions/arrays/shortest-unsorted-continuous-subarray.py | 1,545 | 3.578125 | 4 | class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = None
i = 0
while i < len(nums) - 1 and nums[i] <= nums[i + 1]:
i += 1
if i == len(nums) - 1:
return 0
start = i
end = None
i = len(nums) - 1
while i > start and nums[i - 1] <= nums[i] and nums[i] >= nums[start]:
i -= 1
end = i
if start >= end:
return 0
i = start
max_in_window = float('-inf')
min_in_window = float('inf')
while i <= end:
max_in_window = max(max_in_window, nums[i])
min_in_window = min(min_in_window, nums[i])
i += 1
# print start, end, nums[start], nums[end], min_in_window, max_in_window
while start >= 0 and min_in_window < nums[start]:
# print 'smaller than ', min_in_window, nums[start]
start -= 1
while end < len(nums) and nums[end] < max_in_window:
# print 'greater than ', max_in_window, nums[end]
end += 1
# print start, end, nums[start], nums[end]
return end - 1 - (start + 1) + 1
print Solution().findUnsortedSubarray([2, 6, 4, 8, 10, 9, 15])
print Solution().findUnsortedSubarray([2, 4, 8, 15, 9, 10, 11, 12])
print Solution().findUnsortedSubarray([2, 6, 8, 10, 15])
print Solution().findUnsortedSubarray([2, 6, 8, 10, 9])
print Solution().findUnsortedSubarray([2, 3, 3, 2, 4])
|
ca3519355db8aa90c2c374fb7dd52aa45761bf64 | naveenv20/myseleniumpythonlearn | /packageandmethods/variablescope.py | 651 | 4.1875 | 4 | """
variable scope
"""
a=10
ab=15
def test_method(a):
print("inside method local value is old ",a)
a=a+2
print("inside method local value is new", a)
print("before calling method",a)
test_method(a)
print("after calling method ", a)
print("&"*20)
def test_method2():
global ab
print("inside method2 local value is old ",ab)
ab=ab+2
print("inside method 2local value is new", ab)
print("before calling2 method",ab)
test_method2()
print("after calling2 method ", ab)
def test_method3(*args):
"""
:param args: variable paramters
:return:
"""
return max(args)
print(test_method3(1,5,8,0,11,123)) |
c48d7e79335a4cc2b8d8a07b7a862a5edcfef089 | predavlad/projecteuler | /projecteuler.net/7.py | 514 | 3.59375 | 4 | import time
# 0.05 seconds
start_time = time.time()
def get_primes(n):
"""
Get all the primes smaller than n
"""
primes = [0] * n
for i in xrange(2, n):
if primes[i] == 0:
yield i
else:
continue
for j in xrange(1, n // i):
primes[j * i] = 1
counter = 0
for i in get_primes(200000):
counter += 1
if counter == 10001:
print "The 10001th primes is %d." % i
break
print time.time() - start_time, "seconds"
|
58d1f619c262661d8556671a39c90733764fb949 | measephemeral/Python | /polite.py | 118 | 3.671875 | 4 | hi = '안녕하세요!'
print(hi)
for i in range(0,10):
# 0 ~ 9까지의 반복을 실행합니다.
print(hi) |
315bebc7906e8f22e26ff36ea3a1669176c93bc1 | club-Programacion-UAEM-Ecatepec/Fundamentos-de-Python | /Practicas/11-Diccionarios.py | 1,006 | 4.09375 | 4 | diccionario = {"valor1" : "hola mundo",
2 : 20};
print(diccionario);
print(diccionario[2]);
unaString = "valor1";
print(diccionario[unaString]);
diccionario = {"Tamal": "platillo mexicano hecho de masa de maiz, salsa verde y pollo",
"Botanear": "verbo de comer alguna golocina",
"Escuencle": "Persona que está en el período de la niñez"};
diccionario.update({"Salsa":"Condimento proveniente de mexico hecho de chile con especias de sabor picoso "});
print(diccionario,"\n");
print(diccionario.copy())
print(diccionario.fromkeys(range(5)))
print(diccionario.get("tamal", "no encontrado"))
print(diccionario.items())
print(diccionario.keys())
print(diccionario.pop(0,"no encontrado"))
print(diccionario.popitem())
print(diccionario.setdefault("default", "no encontrado"))
print(diccionario.update({"Tamal": "platillo mexicano hecho de masa de maiz, salsa verde y pollo"}))
print(diccionario.values())
print(diccionario.clear(),"\n")
print(diccionario
|
184ce6a56ae2676bce969f4cce79e5afd1d000ac | jupiterhub/learn-python-the-hard-way | /lpthw-part3/ex24.py | 1,552 | 4.1875 | 4 | # return multiple variables, passing a list to .format() using *
print("Let's practice everthing.")
# not necessary to escape the single-quotes. just demo
print("You\'d need to know \'bout escapes with \\ that do:")
print("\n newlines addd \t tabs")
#printed with newlines as well
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehened passion from intuition
and requires an explanation
\n\t\ttwhere there is none
"""
print("---------------")
print(poem)
print("---------------")
five = 10 - 2 + 3 - 6
print(f"This should be five: {five}")
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates # note returning multiple values
start_point = 10000
# assigning multiple values to the variables
beans, jars, crates = secret_formula(start_point)
# remember that this is another way to format a string
print("With a starting point of: {}".format(start_point))
# It's just like with an f"" string
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")
# shorthand of start_point = start_point / 10
start_point /= 10
print("We can also do that this way:")
formula = secret_formula(start_point)
# this is an easy way to apply a list to a format string
print("We'd have {} beans. {} jars, and {} crates."
.format(*formula)) # notice the use of "*" in *formula
print("Formula", formula) # list
print("Formula", *formula) # iterated, this is what you want to use for prints
|
0e6f1a91b5bab3543708d41266995547d49b1180 | Pythones/MITx_6.00.1x | /L6P2_m.py | 375 | 3.984375 | 4 | def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
#setting variables
tplNew = ()
Count = 0
#setting the body
for oddElements in aTup:
Count += 1
if Count % 2 == 0:
tplNew += (oddElements,)
return tplNew
#end grader
print oddTuples('I', 'am', 'a', 'test', 'tuple') |
8abf2e1e33e5f7b58a839f566d04afb0513aec26 | epsalt/aoc2017 | /day19/day19.py | 1,130 | 3.796875 | 4 | from string import ascii_uppercase
def walk_path(dat):
y = 0
x = dat[0].index("|")
letters = []
dy, dx = 1, 0
steps = 0
while(True):
val = dat[y][x]
if val in ascii_uppercase:
letters.append(val)
if val == " ":
break
elif val == "+":
directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
directions.remove([-dy, -dx])
for test in directions:
ty, tx = test
try:
tval = dat[y + ty][x + tx]
if (tval != " "):
dy, dx = ty, tx
except IndexError:
pass
y, x = y + dy, x + dx
steps += 1
return letters, steps
def main(input_file):
with open(input_file) as f:
lines = [line.rstrip('\r\n') for line in f.readlines()]
dat = []
for line in lines:
l = []
for char in line:
l.append(char)
dat.append(l)
letters, steps = walk_path(dat)
letters = "".join(letters)
return {"part1": letters, "part2": steps}
|
9113ff3610ad19eeb88abeb2dabb59273922c339 | debojyoti-majumder/CompCoding | /pyWorspace/masmom/uniquePath.py | 3,424 | 3.5625 | 4 | # Problem URL : https://leetcode.com/problems/unique-paths/
# This should again get a TLE Error
# Sumission log: Accepted Used DP
# I tkink we can just use a map instead of a matrix because we would not
# be needing older values. The values of top row only
# Related problems: https://leetcode.com/problems/minimum-path-sum/
from typing import List
class Pathfinder:
def __init__(self,m:int, n:int) -> None:
self.numberOfRows = m
self.numberOfCols = n
self.destCount = 0
"""
This is the value from the DP table that needs to be retunred
"""
def getLastCellOutput(self) -> int:
return self.destCount
"""
The robot can only move in right and bottom making it not
able to create loops
"""
def getNextItems(self, x:int, y:int ) -> List[tuple[int,int]]:
retItems = []
lastRowIndex = self.numberOfRows - 1
lastColIndex = self.numberOfCols - 1
# This means we have reached our destination should update the value
# in this
if x == lastRowIndex and y == lastColIndex:
self.destCount += 1
return []
if x < lastRowIndex: retItems.append((x + 1, y))
if y < lastColIndex: retItems.append((x, y + 1))
return retItems
class Solution:
def __init__(self) -> None:
self.numberOfRows:int = 0
self.numberOfCols:int = 0
# Can we define a type for this
self.dpTable = None
"""
This method calculates the path by iterating it. The below method
which uses DP would only work the the robot moves to right and down
only. If it make other moves it would create a loop
"""
def iteratePath(self,m:int, n:int) -> int:
if m == 0 or n == 0: return 0
visitQueue:List[tuple[int,int]] = []
pathFinder = Pathfinder(m,n)
# Trying to go though the paths that leads to the destination
visitQueue.append((0,0))
while len(visitQueue) != 0:
currItem = visitQueue.pop(0)
nextItems = pathFinder.getNextItems(currItem[0], currItem[1])
for item in nextItems : visitQueue.append(item)
return pathFinder.getLastCellOutput()
"""
Uses values from cell top and from left
"""
def uniquePaths(self, m:int, n:int) -> int:
# Basic validity
if m == 0 or n == 0: return 0
# Will create a 2D array for the DP table
self.numberOfRows = m
self.numberOfCols = n
self.dpTable = [ [0] * n for _ in range(m)]
# If it is a 1/1 matrix then this value is 1
self.dpTable[0][0] = 1
# The runtime of the method is simply m*n
for i in range(0,self.numberOfRows):
for j in range(0,self.numberOfCols):
calculatedSum = self.dpTable[i][j]
# This is for the left cell
if i > 0: calculatedSum += self.dpTable[i-1][j]
# This is for the top cell
if j > 0: calculatedSum += self.dpTable[i][j-1]
self.dpTable[i][j] = calculatedSum
# Last cell is our target location to reach
lastCellx = self.numberOfRows - 1
lastCelly = self.numberOfCols - 1
return self.dpTable[lastCellx][lastCelly]
sol = Solution()
print(sol.uniquePaths(4,2))
print(sol.uniquePaths(20,7))
print(sol.uniquePaths(22,7))
|
6ddec1127a71d8bdfe5bb45ad400955322f3445b | ptaylor2018/AoC2020 | /day13/day13.py | 2,281 | 3.59375 | 4 | def part1():
input_raw = []
with open("input_day13.txt", "r") as reader:
# Read and print the entire file line by line
for line in reader:
input_raw.append(line)
input_cleaned = []
for item in input_raw:
input_cleaned.append(item.rstrip())
print(input_cleaned)
min_wait_time = int(input_cleaned[0])
bus_times = input_cleaned[1].split(",")
good_bus_times = []
for entry in bus_times:
if entry != 'x':
good_bus_times.append(int(entry))
best_diff = 1000000000000000000000
best_diff_line = 0
for time in good_bus_times:
nearest_time = (int(min_wait_time/time) + 1) * time
diff = nearest_time - min_wait_time
if diff < best_diff:
best_diff = diff
best_diff_line = time
return best_diff*best_diff_line
print(part1())
import time
def part2():
input_raw = []
with open("input_day13.txt", "r") as reader:
# Read and print the entire file line by line
for line in reader:
input_raw.append(line)
input_cleaned = []
for item in input_raw:
input_cleaned.append(item.rstrip())
print(input_cleaned)
bus_times = input_cleaned[1].split(",")
good_bus_times = []
for entry in bus_times:
if entry != 'x':
good_bus_times.append(int(entry))
gap_dict= {}
current_key = 0
for i in range(len(bus_times)):
time = bus_times[i]
if time != 'x':
gap_dict[int(time)] = i
t = 0
segment = 1
incomplete = True
while incomplete:
interval = 1
for time in good_bus_times[:segment - 1]:
interval *= time
not_matched = True
while not_matched:
if matches_condition(t, good_bus_times[:segment], gap_dict):
segment+=1
not_matched = False
else:
t+=interval
if segment == len(good_bus_times) + 1:
return t
def matches_condition(t, segment, gap_dict):
for entry in segment:
if (t + gap_dict[entry])%entry != 0:
return False
return True
tic = time.perf_counter()
print(part2())
toc = time.perf_counter()
print(f"Ran in {toc - tic:0.4f} seconds")
|
39d78a13a5f9ff1c7dd660c93dd9107a775ef49e | IamJenver/mytasksPython | /factorial.py | 251 | 3.953125 | 4 | # На вход программе подается натуральное число n.
# Напишите программу, которая вычисляет n!
n = int(input())
counter = 1
for i in range(1, n + 1):
counter *= i
print(counter) |
56dd8e3b2173f17d4195c6ba3b4f5f6a3776b555 | pymft/py-mft1 | /S11/with_context/main.py | 140 | 3.65625 | 4 | f = open('file.txt', mode='r')
text = f.read()
f.close()
print(text)
with open('file.txt', mode='r') as f:
text = f.read()
print(text) |
b5e79146302aeb281c1ecd52dea76b5fe4dbf379 | xiang525/leetcode_2018 | /python/house_robber_ii.py | 1,926 | 3.5625 | 4 | class Solution:
# @param {integer[]} nums
# @return {integer}
def rob(self, nums):
if len(nums) == 1:
return nums[0]
return max(self.robLinear(nums[1:]), self.robLinear(nums[:-1])) # rob the first room or rob the
# last room. If 1st room is chosen then cannot choose the last room.
# @param num, a list of integer
# @return an integer
def robLinear(self, num):
size = len(num)
odd, even = 0, 0
for i in range(size):
if i % 2: # the odd case
odd = max(odd + num[i], even)
else: # the even case
even = max(even + num[i], odd)
return max(odd, even)
# typical example of circle DP--break the circle into two linear DPs
# ******** The Second Time **********
"""
# House Robber I的升级版. 因为第一个element 和最后一个element不能同时出现. 则分两次
# call House Robber I. case 1: 不包括最后一个element. case 2: 不包括第一个element.
# 两者的最大值即为全局最大值
"""
"""
解法二:将环形DP问题转化为两趟线性DP问题,可以复用House Robber的代码。另外需要特判一下只有一件房屋的情形。
"""
class Solution:
# @param {integer[]} nums
# @return {integer}
def rob(self, nums):
if len(nums) == 1:
return nums[0]
return max(self.robLinear(nums[1:]),self.robLinear(nums[:-1])) # 头和尾只能取其一
def robLinear(self,nums):
n = len(nums)
odd, even = 0,0
for i in range(n):
if i % 2 :
odd = max(odd+nums[i],even) # 到第i家时的最大值;两种情况, 偷还是不偷, 偷的话是odd + nums[i],
# 不偷的话是even
else:
even = max(even+nums[i],odd)
return max(odd,even)
|
4f5bcfff48f170260be1fedb7a169ded5b584f80 | pranavgurditta/data-structures-MCA-201 | /linked_list_pranav.py | 6,143 | 4.28125 | 4 | class Node:
'''
Objective: To represent a linked list node
'''
def __init__(self,value):
'''
Objective: To instantiate a class object
Input:
self: Implicit object of class Node
value: Value at the node
Return Value: None
'''
self.data = value
self.next = None
def __str__(self):
'''
Objective: To override the string function
Input:
self: Implicit object of class Node
Return Value: String
'''
return str(self.data)
class LinkedList:
'''
Objective: To represent a linked list
'''
def __init__(self):
'''
Objective: To instantiate a class object
Input:
self: Implicit object of class LinkedList
Return Value: None
'''
self.head = None
def insertAtBeg(self,value):
'''
Objective: To add a node at the begining of a linked list
Input:
self: Implicit object of class LinkedList
value: Value to be inserted
Return Value: None
'''
temp = Node(value)
temp.next = self.head
self.head = temp
def insertAtEnd(self,temp,value):
'''
Objective: To add a node at the begining of a linked list
Input:
self: Implicit object of class LinkedList
value: Value to be inserted
temp : Current node
Return Value: None
'''
#Approach: Recurssively
if temp == None:
self.head = Node(value)
elif temp.next == None:
temp.next = Node(value)
else:
return self.insertAtEnd(temp.next,value)
def insertSorted(self,temp,value):
'''
Objective: To add a node in a sorted linked list
Input:
self: Implicit object of class LinkedList
value: Value to be inserted
temp : Current node
Return Value: None
'''
#Approach: Recurssively
if temp == None:
self.head = Node(value)
elif temp == self.head and value < temp.data:
newNode = Node(value)
newNode.next = temp
self.head = newNode
elif temp.next == None:
if temp.data < value:
temp.next = Node(value)
else:
self.insertAtBeg(value)
elif temp.next.data > value:
node = Node(value)
node.next = temp.next
temp.next = node
else:
return self.insertSorted(temp.next,value)
def deleteFromBeg(self):
'''
Objective: To delete a node from the begining of a linked list
Input:
self: Implicit object of class LinkedList
Return Value: Value of node deleted
'''
if self.head == None:
print("List is already empty")
else:
temp = self.head
self.head = self.head.next
temp.next = None
return temp.data
def deleteValue(self,value):
'''
Objective: To delete a node from a linked list
Input:
self: Implicit object of class LinkedList
value: Value to be deleted
Return Value: None
'''
if self.head == None:
print("Value not found")
elif self.head.data == value:
print("Deleted successfully")
self.deleteFromBeg()
else:
parent = self.head
temp = parent.next
while temp != None:
if temp.data == value:
parent.next = temp.next
temp.next = None
print("Deleted successfully")
return
else:
parent = temp
temp = temp.next
print("Value not found")
def __str__(self):
'''
Objective: To override the string function
Input:
self: Implicit object of class LinkedList
Return Value: String
'''
if self.head == None:
return "List is empty"
else:
temp = self.head
msg = "List is: "
while temp != None:
msg += str(temp.data)+" "
temp = temp.next
return msg
if __name__ == "__main__":
lst=LinkedList()
while True:
print("Press 1 to insert at the beginning")
print("Press 2 to Insert at the end")
print("Press 3 to Insert in a sorted linked list")
print("Pres 4 to Delete from beginning")
print("Press 5 to Delete a value")
print("Press 6 to Print linked list")
print("Press 7 to Exit")
print("Enter your choice:",end="")
ch = input()
if ch.isdigit()== False:
print("Invalid input")
break
ch =int(ch)
if ch==1:
print("\nEnter the value to be inserted:",end="")
lst.insertAtBeg(int(input()))
elif ch==2:
print("\nEnter the value to be inserted:",end="")
lst.insertAtEnd(lst.head,int(input()))
elif ch==3:
print("\nEnter the value to be inserted:",end="")
lst.insertSorted(lst.head,int(input()))
elif ch==4:
elt = lst.deleteFromBeg()
if elt != None:
print("Element deleted:",elt)
elif ch==5:
print("\nEnter the value to be deleted:",end="")
lst.deleteValue(int(input()))
elif ch==6:
print(lst)
else:
if ch!=7:
print("Invalid input")
break
print("**********************************************************\n")
|
ea2c4560c8c9fb2d08b0a6360afaa33dbfc4ff8a | WesternUSC/USC_Timeline | /createuser.py | 1,557 | 3.625 | 4 | """Script for creating a new user account.
The script can be executed by typing in: `python createuser.py` (assuming your
current directory is `USC_Timeline`).
Upon executing the script, you will be prompted to enter a username, email and
password. Using this information a new User will be instantiated and stored in
the database.
"""
import sys
import json
from getpass import getpass
from usctimeline import create_app, db, bcrypt
from usctimeline.models import User
def create_user(username, email, password):
"""Creates a new user account.
Takes in a given username, email and password. Password is hashed. Creates
a new instance of User and stores in database.
Args:
username: Username
email: Email
password: Password
Returns:
None
"""
new_user = User(
username=username,
email=email,
password=bcrypt.generate_password_hash(password).decode('utf-8')
)
db.session.add(new_user)
db.session.commit()
def main():
"""Prompts user for username, email, password, then calls create_user().
Returns:
None
"""
username = input("Username: ")
email = input("Email: ")
password = getpass("Password: ")
password_verification = getpass("Confirm Password: ")
if password == password_verification:
create_user(username, email, password)
else:
print("Error: Passwords did not match. Please try again.")
if __name__ == '__main__':
app = create_app()
with app.app_context():
main()
|
606320eb874a961d7e9a26540574ec2fd65dbf84 | Obdolbacca/PyDA | /hw/hw1.py | 1,935 | 3.609375 | 4 | # Copyright by Oleg Bobok (c) 2019. For educational purpose
from math import sin, pi
import re
from typing import Tuple
def check_long_is_longer(long_str: str, short_str: str) -> bool:
return len(long_str) > len(short_str)
def greatest_by_letter_inclusions_count(string: str) -> str:
string = re.sub(r'[^аи]', '', string)
ai_len = len(string)
i_count = len(re.sub(r'[а]', '', string))
a_count = ai_len - i_count
return 'а' if a_count > i_count else 'и'
def bytes_to_megabytes(volume: int) -> float:
megabytes: float = float(volume) / (1024*1024)
return round(megabytes, 2)
def swap(param_a: int, param_b: int) -> Tuple[int, int]:
return param_b, param_a
def bin_to_dec(value: int) -> int:
result_value: int = 0
string_to_parse: str = ''.join(reversed(str(value)))
for i in range(len(string_to_parse)):
if string_to_parse[i] == '1':
result_value += pow(2, i)
return result_value
if __name__ == '__main__':
long_phrase: str = 'Насколько проще было бы писать программы, если бы не заказчики'
short_phrase: str = '640Кб должно хватить для любых задач. Билл Гейтс (по легенде)'
result: bool = check_long_is_longer(short_str=short_phrase, long_str=long_phrase)
print('{0}'.format(result))
text: str = 'Если программист в 9-00 утра на работе, значит, он там и ночевал'
print('{0}'.format(greatest_by_letter_inclusions_count(text)))
print('Объем файла равен {0}Mb'.format(bytes_to_megabytes(217000000)))
print('{0}'.format(sin(pi/6)))
print('{0}'.format(0.1 + 0.2))
a: int = 1
b: int = 3
print('{0} -> {1}'.format(a, b))
a, b = swap(a, b)
print('{0} -> {1}'.format(a, b))
print('{0}'.format(bin_to_dec(110111)))
print('done')
|
39270412a42d1ef91f813bc34790d6e7e7c6fa06 | pcampolucci/SVV-Group-A13-TUDelft | /src/loads/distributed_load.py | 7,178 | 3.515625 | 4 | """
Title: Functions for aerodynamic distributed load discretization
"""
import numpy as np
from src.input.input import Input
# =================== Global inputs to generate arrays =========================
la = 2.661
stepsize = 0.1 # [m] set the distance between points in trapezoidal rule
load = Input('A').aero_input()
# ====================== 8 Functions ======================================
""" The get_discrete_xxxx functions make discrete functions for the respective xxxxx feature.
The xxxxx_resultants use these discrete functions/arrays then to derrive the approximated value at an exact input
location.
NOTE: The input of the get_discrete_xxx functions should always be the total length of the aileron, i.e. length
aileron (la) """
def trapezoidal_rule(row, step):
""" Just trapezoidal rule between set of points"""
resultant = 0
for i in range(len(row)-1):
r_i = (row[i-1] + row[i])*step*0.5
resultant += r_i
return resultant
# --------------- Discrete Load -----------------------
def get_discrete_load(x, cont_load, step):
""" Given a continous load function q(x), this will make an array of the load at different
locations with a set interval. For the trapezoidal rule"""
discrete_load = np.empty_like(np.arange(0, x+step, step))
for i in np.arange(0, x+step, step):
discrete_load[int(round(i/step))] = cont_load.get_q(-i)
return discrete_load
# --------------- Discrete resultant -----------------------
def get_discrete_resultant(la, discrete_load, step):
""" Make discrete resultant function """
discrete_resultant = np.zeros_like(np.arange(0, la+step, step))
for i in np.arange(step, la+step, step):
discrete_resultant[int(round(i/step))] = trapezoidal_rule(discrete_load[0:int(i/step)+1], step)
return discrete_resultant
def magnitude_resultant(x, discrete_resultant, step):
""" Finds resultant force of distribution from 0 till x_end according to given span distr.
First it takes points from that distr and then uses trapezoidal rule. """
if int((x+step)/step) >= len(discrete_resultant):
return discrete_resultant[int(x/step)]
return 0.5*(discrete_resultant[int((x+step)/step)]+discrete_resultant[int(x/step)])
# --------------- Discrete locations -----------------------
def get_discrete_location_resultant(la, discrete_resultant, discrete_load, step):
""" Finds location of application resultant force. With formula:
xbar = integral(x*q(x))/integral(q(x)) """
discrete_location = np.zeros_like(np.arange(0, la+step, step))
discrete_resultant_x = discrete_load*np.arange(0, la+step, step)
for i in np.arange(step, la, step):
discrete_location[int(round(i/step))] = trapezoidal_rule(discrete_resultant_x[1:int(round(i/step))+2], step) / magnitude_resultant(i, discrete_resultant, step)
return discrete_location
def location_resultant(x, discrete_location, step):
""" Finds resultant force of distribution from 0 till x_end according to given span distr.
First it takes points from that distr and then uses trapezoidal rule. """
if int((x+step)/step) >= len(discrete_location):
return discrete_location[int(x/step)]
return 0.5*(discrete_location[int((x+step)/step)]+discrete_location[int(x/step)])
# --------------- Discrete moments -----------------------
def get_discrete_moment(discrete_resultant, discrete_location):
""" Finds moment with respect to end point """
return discrete_resultant*discrete_location
def moment_resultant(x, discrete_moment, step):
""" Finds resultant force of distribution from 0 till x_end according to given span distr.
First it takes points from that distr and then uses trapezoidal rule. """
if int((x+step)/step) >= len(discrete_moment):
return discrete_moment[int(x/step)]
return 0.5*(discrete_moment[int((x+step)/step)]+discrete_moment[int(x/step)])
# --------------- Discrete angles -----------------------
def get_discrete_angle(la, discrete_moment, step):
""" Make discrete resultant function """
discrete_angle = np.zeros_like(np.arange(0, la+step, step))
for i in np.arange(step, la+step, step):
discrete_angle[int(round(i/step))] = trapezoidal_rule(discrete_moment[0:int(i/step)+1], step)
return discrete_angle
def angle_resultant(x, discrete_angle, step):
""" Finds resultant force of distribution from 0 till x_end according to given span distr.
First it takes points from that distr and then uses trapezoidal rule. """
if int((x+step)/step) >= len(discrete_angle):
return discrete_angle[int(x/step)]
return 0.5*(discrete_angle[int((x+step)/step)]+discrete_angle[int(x/step)])
# --------------- Discrete deflections -----------------------
def get_discrete_deflection(la, discrete_angle, step):
""" Make discrete deflection function """
discrete_deflection = np.zeros_like(np.arange(0, la+step, step))
for i in np.arange(step, la+step, step):
discrete_deflection[int(round(i/step))] = trapezoidal_rule(discrete_angle[0:int(i/step)+1], step)
return discrete_deflection
def deflection_resultant(x, discrete_deflection, step):
""" Finds resultant force of distribution from 0 till x_end according to given span distr.
First it takes points from that distr and then uses trapezoidal rule. """
if int((x+step)/step) > len(discrete_deflection):
return discrete_deflection[int(x/step)]
return 0.5*(discrete_deflection[int((x+step)/step)]+discrete_deflection[int(x/step)])
# ========================= Arrays ===========================
""" The discrete functions for the respective features. """
discrete_loads = get_discrete_load(la, load, stepsize)
discrete_resultants = get_discrete_resultant(la, discrete_loads, stepsize)
discrete_locations = get_discrete_location_resultant(la, discrete_resultants, discrete_loads, stepsize)
discrete_moments = get_discrete_moment(discrete_resultants, discrete_locations)
discrete_angles = get_discrete_angle(la, discrete_moments, stepsize)
discrete_deflections = get_discrete_deflection(la, discrete_angles, stepsize)
# ===============================================================================
""" Checks for constant load -55.7 N/m (The load case of the B737) """
DEBUG = False
if DEBUG:
# inputs
x_end = 2.661 # [m] end point, set calc will be done for distr from 0 till this point
stepsize = 0.001 # [m] set the distance between points in trapezoidal rule
load = Input('B').aero_input()
# test
res1 = magnitude_resultant(1, discrete_resultants, stepsize)
print('Resultant should be -55.7 = ', res1)
loc1 = location_resultant(1, discrete_locations, stepsize)
print('location should be 0.5 = ', loc1)
mom1 = moment_resultant(1, discrete_moments, stepsize)
print('moment should be ', -55.7/2, ' = ', mom1)
ang1 = angle_resultant(1, discrete_angles, stepsize)
print('Angle should be ', -55.7/2/3, ' = ', ang1)
def1 = deflection_resultant(1, discrete_deflections, stepsize)
print('Deflection should be ', -55.7/2/3/4, ' = ', def1) |
c4e6feafed6f1400210698344f97bd986a724ab9 | Matheusrma/problem-solving | /spoj/PRIME1/PRIME1.py | 1,733 | 3.75 | 4 | # SPOJ Classical Problems
# Url: http://www.spoj.com/problems/PRIME1/
# Author: matheusrma
# -*- coding: UTF-8 -*-
import sys
import unittest
# Adds problem-solving folder to module searching path
# to enable code modularization
sys.path.append('../../')
from util.python.printer import Printer
from util.python.reader import Reader
from math import sqrt
class Tests(unittest.TestCase):
def setUp(self):
self.testSubject = ProblemSolver()
def testExample1(self):
self.assertEqual(self.testSubject.run([1,10]), [2,3,5,7])
def testExample2(self):
self.assertEqual(self.testSubject.run([3,5]), [3,5])
def testSamePrime(self):
self.assertEqual(self.testSubject.run([17,17]), [17])
class ProblemSolver():
def isPrime(self, num):
if num == 1:
return False
for i in range(2, num):
# There are no divisors after the square root of a given number
if i > sqrt(num):
break
if num % i == 0:
return False
return True
def run(self, input):
solution = []
start = input[0]
end = input[1]
for i in range(start, end + 1):
if self.isPrime(i):
solution.append(i);
return solution
# MAIN
def runTests():
suite = unittest.TestLoader().loadTestsFromTestCase(Tests)
unittest.TextTestRunner(verbosity = 2).run(suite)
if len(sys.argv) > 1 and sys.argv[1] == 'test':
runTests();
else:
reader = Reader(hasTestCount = True);
solver = ProblemSolver();
printer = Printer(hasLineBetweenPrints = True);
inputArray = reader.readIntegersFromConsole()
while inputArray != []:
solution = solver.run(inputArray)
printer.printToConsole(solution)
inputArray = reader.readFromConsole()
|
28ccab0dea15d693093f57d7a12f5522d4395166 | riyadhswe/Python_Javatpoint | /10 Python break statement/Example 3.py | 115 | 3.796875 | 4 | i = 0;
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
print("came out of while loop"); |
803acd7a405e60a8eff655e00065c14ea0e6e06c | nabilhassein/project-euler | /p6.py | 704 | 3.84375 | 4 | # 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(n):
return sum([i**2 for i in range(1, n+1)])
def squareOfSum(n):
return sum([i for i in range(1, n+1)]) ** 2
def problem6(n):
return squareOfSum(n) - sumOfSquares(n)
print problem6(100) |
f948d0da08acca53849c65fc04282f4f08672893 | RomaelP/Proyecto2s22017 | /Phyton/ListaDoble.py | 5,830 | 3.515625 | 4 | from NodoListaDoble import NodoListaDoble
class ListaDoble():
def __init__(self):
self.inicio = None
self.ultimo = None
self.grafica = "digraph G{\n"
def insertarListaDoble(self, usuario, contrasenia, direccion, telefono, edad):
if self.inicio != None:
temporal = self.inicio
temporal2 = self.ultimo
while temporal.siguiente != None:
temporal = temporal.siguiente
self.ultimo.siguiente = NodoListaDoble(usuario, contrasenia, direccion, telefono, edad)
self.ultimo.siguiente.anterior = self.ultimo
self.ultimo = self.ultimo.siguiente
else:
self.inicio = self.ultimo = NodoListaDoble(usuario, contrasenia, direccion, telefono, edad)
def verificarUsuario(self, usuario, contrasenia):
if self.inicio != None:
temporal = self.inicio
while True:
if temporal.usuario == usuario:
if temporal.contrasenia == contrasenia:
return "True"
else:
temporal = temporal.siguiente
if temporal == self.inicio:
return "Datos erroneos"
else:
return "False"
def modificarNombre(self, usuario, nombreNuevo):
valor = ""
if self.inicio != None:
temporal = self.inicio
while temporal != None:
if temporal.usuario == usuario:
if self.verificarUsuario1(nombreNuevo) == "False":
temporal.usuario = nombreNuevo
valor = "Usuario modificado"
return valor
else:
valor = "El nombre de Usuario ya existe"
return valor
else:
temporal = temporal.siguiente
return valor
def modificarContrasenia(self, usuario, contraNueva):
if self.inicio != None:
temporal = self.inicio
while temporal != None:
if temporal.usuario == usuario:
temporal.contrasenia = contraNueva
return "Contrasenia modificada"
else:
temporal = temporal.siguiente
return "Usuario no existe"
def modificarDireccion(self, usuario, direccionNueva):
if self.inicio != None:
temporal = self.inicio
while temporal != None:
if temporal.usuario == usuario:
temporal.direccion == direccionNueva
return "Direccion Modificada: "+direccionNueva
else:
temporal = temporal.siguiente
return "Usuario no Existe"
def modificarTelefono(self, usuario, telefonoNuevo):
if self.inicio != None:
temporal = self.inicio
while temporal != None:
if temporal.usuario == usuario:
temporal.telefono == telefonoNuevo
return "Telefono Modificado: "+telefonoNuevo +" de usuario: "+usuario
else:
temporal = temporal.siguiente
return "Usuario no Existe"
def modificarEdad(self, usuario, edadNueva):
if self.inicio != None:
temporal = self.inicio
while temporal != None:
if temporal.usuario == usuario:
temporal.edad = edadNueva
return "Edad Modificada: "+edadNueva+" del usuario: "+usuario
else:
temporal = temporal.siguiente
return "Usuario no Existe"
def verificarUsuario1(self, usuario):
if self.inicio != None:
temporal = self.inicio
while temporal != None:
if temporal.usuario == usuario:
return "True"
else:
temporal = temporal.siguiente
return "False"
def eliminarUsuario(self, usuario):
if self.inicio != None:
temporal = self.inicio
while temporal != None:
if temporal.usuario == usuario:
temporalA = temporal.anterior
temporalS = temporal.siguiente
temporalA.siguiente = temporalS
temporalS.anterior = temporalA
return "Usuario eliminado"
else:
temporal = temporal.siguiente
return "No se elimino el usuario"
def grabarArchivoListaDoble(self):
cont1 = 0
temporal = self.inicio
archivo = open('C:\\Users\\USuario1\\Desktop\\ListaDoble.txt','w')
archivo.write('digraph G{\n')
archivo.write("node [shape = record];\n")
archivo.write("rankdir = LR;\n")
while temporal != None:
#if temporal.siguiente != None:
archivo.write(str(temporal.usuario)+"_Nodo [label="+str(temporal.usuario)+"]\n")
cont1 = cont1 + 1
temporal = temporal.siguiente
contadorUltimo = cont1
cont2 = cont1 - 1
temporal = self.inicio
while temporal != None:
if temporal.siguiente != None:
archivo.write(str(temporal.usuario)+"_Nodo ->"+str(temporal.siguiente.usuario)+"_Nodo \n")
archivo.write(str(temporal.siguiente.usuario)+"_Nodo ->"+str(temporal.usuario)+"_Nodo \n")
temporal = temporal.siguiente
archivo.write('}')
archivo.close()
|
edca5c447590799c06a580aa64cc8e8358e1e4c2 | junghyun4425/myleetcode | /medium/Peeking_Iterator.py | 2,316 | 3.953125 | 4 | # Problem Link: https://leetcode.com/problems/peeking-iterator/
'''
문제 요약: iterator 객체를 이용해서 peek기능이 있는 iterator를 구현하는 문제. (peek는 다음 값만 보여주고 실제로 다음 포인터로 넘어가지 않는 기능)
ask:
["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
[[[1, 2, 3]], [], [], [], [], []]
answer:
[null, 1, 2, 2, 3, false]
해석:
iterator를 그대로 가져와서 시간복잡도 O(1)에 모든게 해결가능함.
다음값을 val에 미리 저장해 놓는다는 점을 제외한 나머지는 iterator와 유사함.
단, val에 값을 불러올때마다 hasNext()로 검사하고 불러와야함. 값이 없다면 None을 가지게 하면 끝.
굉장히 간단해서 medium보다는 easy같은 느낌.
'''
# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator:
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self):
# """
# Returns true if the iteration has more elements.
# :rtype: bool
# """
#
# def next(self):
# """
# Returns the next element in the iteration.
# :rtype: int
# """
class PeekingIterator:
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self.val = self.iterator.next() if self.iterator.hasNext() else None
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self.val
def next(self):
"""
:rtype: int
"""
tmp = self.val
self.val = self.iterator.next() if self.iterator.hasNext() else None
return tmp
def hasNext(self):
"""
:rtype: bool
"""
return self.val != None
# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
# val = iter.peek() # Get the next element but not advance the iterator.
# iter.next() # Should return the same value as [val]. |
b69a58ff28cf1f85a7438efd50d3f0c62100db97 | drahmuty/Algorithm-Design-Manual | /05_02_playing_with_wheels.py | 4,207 | 3.5625 | 4 | from collections import defaultdict, deque
# Adjacency list graph representation
class Graph:
def __init__(self, directed=False):
self.graph = defaultdict(list)
self.degree = defaultdict(int)
self.directed = directed
self.n = 0 # Number of vertices
self.m = 0 # Number of edges
def add_edge(self, x, y, stop=False):
self.graph[x].append(y)
self.degree[x] += 1
self.n += 1
if not self.directed and not stop:
self.add_edge(y, x, True)
else:
self.m += 1
def print_graph(self):
for i in self.graph:
print(i, self.graph[i])
def initialize_search(self):
self.discovered = defaultdict(bool)
self.processed = defaultdict(bool)
self.parent = defaultdict(int)
self.entry_time = defaultdict(int)
self.exit_time = defaultdict(int)
self.time = 0
self.finished = False
self.path = []
# Breadth-first search
def bfs(self, v, pve=None, pe=None, pvl=None):
self.initialize_search()
q = deque()
q.append(v)
self.discovered[v] = True
while(q):
v = q.popleft()
# print('process vertex early', v)
if pve:
pve(v)
self.processed[v] = True
for y in self.graph[v]:
if not self.processed[y] or self.directed:
# print('process edge', v, y)
if pe:
pe(v, y)
if not self.discovered[y]:
q.append(y)
self.discovered[y] = True
self.parent[y] = v
# print('process vertex late', v)
if pvl:
pvl(v)
# Find path
def find_path(self, start, end):
if start == end:
print('Start')
print(end)
if not self.finished:
self.path.append(end)
elif end == 0:
self.finished = True
else:
self.find_path(start, self.parent[end])
print(end)
if not self.finished:
self.path.append(end)
# Create a string representation of integers
def int_to_str(a, b, c, d):
return str(a) + str(b) + str(c) + str(d)
# Main program
# Return smallest number of wheel turns required to reach the
# target result or return None if there is no path.
def wheels(start, end, forbidden_vertices):
g = Graph()
a = b = c = d = 0
# Create dictionary of forbidden vertices for faster lookup time
forbidden_vertices_dict = defaultdict(str)
for f in forbidden_vertices:
forbidden_vertices_dict[f] = True
# Create graph, skipping forbidden vertices
while True:
v = int_to_str(a, b, c, d)
if forbidden_vertices_dict[v]:
print('Forbidden:', v)
else:
w = int_to_str(((a + 1) % 10), b, c, d)
x = int_to_str(a, ((b + 1) % 10), c, d)
y = int_to_str(a, b, ((c + 1) % 10), d)
z = int_to_str(a, b, c, ((d + 1) % 10))
if not forbidden_vertices_dict[w]:
g.add_edge(v, w)
if not forbidden_vertices_dict[x]:
g.add_edge(v, x)
if not forbidden_vertices_dict[y]:
g.add_edge(v, y)
if not forbidden_vertices_dict[z]:
g.add_edge(v, z)
# Increment vertex
d += 1
if d > 9:
d = 0
c += 1
if c > 9:
c = 0
b += 1
if b > 9:
b = 0
a += 1
if a > 9:
break
# Run BFS and find shortest path, if one exists
g.bfs(start)
g.find_path(start, end)
# Return path length, if one exists
if g.path:
return len(g.path)-1
else:
return None
# Driver code
print(wheels('8056', '6508', ['8057', '8047', '5508', '7508', '6408']))
print(wheels('0000', '5317', ['0001', '0009', '0010', '0090', '0100', '0900', '1000', '9000']))
|
3c8c899c197e937f6f225d840e63377f4cdceb45 | Sanket-Mathur/CodeChef-Practice | /CHEFSTUD.py | 280 | 3.625 | 4 | try:
for _ in range(int(input())):
S = list(input())
for i in range(len(S)):
if S[i] == '<':
S[i] = '>'
elif S[i] == '>':
S[i] = '<'
c = (''.join(S)).count('><')
print(c)
except:
pass
|
03df11fbd88001b9476307c5e2b2b3a4bc728e2a | vadivisuvalingam/courseraPythonCode | /Assignment1/test_stock_price_summary.py | 2,663 | 3.734375 | 4 | import a1
import unittest
class TestStockPriceSummary(unittest.TestCase):
""" Test class for function a1.stock_price_summary. """
# Add your test methods for a1.stock_price_summary here.
def test_stock_price_summary_empty_list(self):
"""Test empty list."""
actual = a1.stock_price_summary([])
expected = (0, 0)
self.assertEqual(expected, actual)
def test_stock_price_summary_list_one_item_price_increase(self):
"""Test list of size one with just price increase."""
actual = a1.stock_price_summary([0.02])
expected = (0.02, 0)
self.assertEqual(expected, actual)
def test_stock_price_summary_list_one_item_price_decrease(self):
"""Test list of size one with just price decrease."""
actual = a1.stock_price_summary([-0.02])
expected = (0, -0.02)
self.assertEqual(expected, actual)
def test_stock_price_summary_list_multiple_item_price_increase(self):
"""Test list of muliple numbers with just price increase."""
actual = a1.stock_price_summary([0.01, 1.03, 0.05])
expected = (1.09, 0)
self.assertEqual(expected, actual)
def test_stock_price_summary_list_multiple_item_price_decrease(self):
"""Test list of muliple numbers with just price decrease."""
actual = a1.stock_price_summary([-0.01, -1.03, -0.05])
expected = (0, -1.09)
self.assertEqual(expected, actual)
def test_stock_price_summary_list_multiple_item_increase_first(self):
"""Test list of multiple numbers with both price increase
and decrease, however with price increase order first and
the price decrease last."""
actual = a1.stock_price_summary([-0.01, -1.03, -0.05, 0.01, 1.03, 0.05])
expected = (1.09, -1.09)
self.assertEqual(expected, actual)
def test_stock_price_summary_list_multiple_item_decrease_first(self):
"""Test list of multiple numbers with both price increase
and decrease, however with price decrease order first and
the price increase last."""
actual = a1.stock_price_summary([-0.01, -1.03, -0.05, 0.01, 1.03, 0.05])
expected = (1.09, -1.09)
self.assertEqual(expected, actual)
def test_stock_price_summary_list_multiple_item_no_order(self):
"""Test list of multiple numbers with both price increase
and decrease with no particular order."""
actual = a1.stock_price_summary([-0.01, 1.03, -0.05, 0.01, -1.03, 0.05])
expected = (1.09, -1.09)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main(exit=False)
|
f257501c614d70a285f85859af09b88d90b27b4d | skdonepudi/100DaysOfCode | /Day 82/WhatIsYourMobileNumber.py | 1,035 | 3.953125 | 4 | '''
These days Bechan Chacha is depressed because his crush gave him list of mobile number some of them are valid and some of them are invalid. Bechan Chacha has special power that he can pick his crush number only if he has valid set of mobile numbers. Help him to determine the valid numbers.
You are given a string "S" and you have to determine whether it is Valid mobile number or not. Mobile number is valid only if it is of length 10 , consists of numeric values and it shouldn't have prefix zeroes.
Input:
First line of input is T representing total number of test cases.
Next T line each representing "S" as described in in problem statement.
Output:
Print "YES" if it is valid mobile number else print "NO".
Note: Quotes are for clarity.
Constraints:
1<= T <= 103
sum of string length <= 105
SAMPLE INPUT
3
1234567890
0123456789
0123456.87
SAMPLE OUTPUT
YES
NO
NO
'''
T=int(input())
for i in range(T):
S=input()
if S.isdecimal() and S[0]!='0' and len(S)==10:
print("YES")
else:
print("NO") |
a16d24ab7966787c8fe524e7ce7be2d28ababbc9 | unlimitediw/CheckCode | /0.算法/103_zigzag_BST_LOT.py | 835 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
l = [root]
result = []
turn = 0
while any(l):
result_l = []
for _ in range(len(l)):
r = l.pop(0)
result_l.append(r.val)
if r.left:
l.append(r.left)
if r.right:
l.append(r.right)
if turn%2 == 1:
result_l = result_l[::-1]
result.append(result_l)
turn += 1
return result
|
d60db74fcff9792e422f8d10b8d710958907f077 | dheeraj1010/Hackerrank_problem_solving | /Codechef/composite_sub.py | 860 | 3.796875 | 4 | def reverse_ascii(x):
x = x-65
return x
def ascii(x):
x = x+65
return x
cipher_text = list(input().strip())
k1 = int(input())
k2 = int(input())
cipher_text = list(map(ord, cipher_text))
cipher_text = list(map(reverse_ascii, cipher_text))
#print(cipher_text)
#print(k1)
#print(k2)
k2_inverse = 1
while ((k2_inverse*k2)%26)!=1:
k2_inverse +=1
#print(k2_inverse)
plain_text = []
for c in cipher_text:
p = ((c-k1)*k2_inverse)%26
#print("p {}".format(p))
#print("C = {}, K1 = {}, C-K1 = {}".format(c,k1,c-k1))
#print("(c-k1)*k2_inverse = {} ".format((c-k1)*k2_inverse))
#print("(c%26 = {}".format(((c-k1)*k2_inverse)%26))
plain_text.append(p)
#print(plain_text)
plain_text = list(map(ascii, plain_text))
#print(plain_text)
plain_text = list(map(chr, plain_text))
plain_text = "".join(plain_text)
print(plain_text)
|
72a6f791738dec1c72a5cd59c9941adba8958111 | ShiJingChao/Python- | /PythonStart/0722Python/0731task/objori.py | 3,250 | 3.75 | 4 | # class Person(object):
# """保卫者"""
# def __init__(self,name):
# self.name = name
# def install_bullet(self,magazineclib,bullet):
# '''将子弹安装到弹夹中'''
# magazineclib.save_bullet(bullet)
# def install_clib_2_gun(self,gun,clib):
# '''6.1将弹夹安装到枪中'''
# gun.insall_clib(clib)
#
# class Gun(object):
# '''枪类'''
# def __init__(self,name):
# self.name = name
# # 6.3用来记录弹夹的引用
# self.clib = None
# def install_clib(self,clib):
# '''6.2将弹夹安装到枪中'''
# self.clib = clib
#
# #8.2 显示枪和弹夹的信息
# def __str__(self):
# if self.clib:
# return "枪的信息:%s,%s"%(self.name,self.clib)
# else:
# return "枪的信息为%s,并且这把枪没有弹夹"%(self.name)
# class Magazineclib(object):
# '''弹夹'''
# def __init__(self,max_num):
# self.max_num = max_num #盛放子弹的最大容量
# # 用来保存子弹
# self.bullet_list=[]
#
# def save_bullet(self,bullet):
# '''将子弹装入弹夹中'''
# self.bullet_list.append(bullet)
#
# #7.1 打印 弹夹信息
# def __str__(self):
# return "弹夹的信息:%d%d"%(len(self.bullet_list),self.max_num)
# class Bullet(object):
# '''子弹'''
# def __init__(self,lethality):
# self.lethality = lethality #子弹的杀伤力
#
# def main():
# '''用来控制整个程序的流程'''
# # 保卫者对象
# bwz = Person("老王")
# # AK-47 枪 对象
# gun = Gun("AK-47")
# # 弹夹对象
# clib = Magazineclib(200)
# # 7.2 创建一些子弹
# for i in range(100):
# # 子弹对象
# bullet = Bullet(10) #打一枪掉10滴血
# # 保卫者将自动那安装到弹夹中
# bwz.install_bullet(clib,bullet)
# # 保卫者将弹夹安装到枪中
# bwz.install_clib_2_gun(gun,clib)
#
# #7.测试弹夹信息
# print(clib)
# #8.测试枪的信息
# print(gun)
# #保卫者拿起枪
# #侵略者对象
# #保卫者开枪打敌人
#
# if __name__ == '__main__':
# main()
class Gun:
def __init__(self, model):
self.model = model
self.bullet_count = 0
def add_bullet(self, count):
self.bullet_count += count
def shoot(self):
if self.bullet_count <= 0:
print('没有子弹了')
return
self.bullet_count -= 20
print("%s发射子弹[%d]..." % (self.model, self.bullet_count))
def pick(self):
print("你捡起了枪")
self.bullet_count = 100
print("子弹剩余%d"% self.bullet_count)
m99 = Gun('m99')
m99.pick()
m99.add_bullet(50)
m99.shoot()
class Sniper:
def __init__(self, name):
self.name = name
self.gun = None
def fire(self):
if self.gun is None:
print('[%s] 还没有枪...' % self.name)
return
print('冲啊...[%s]' % self.name)
self.gun.add_bullet(50)
self.gun.shoot()
# m99 = Gun('m99')
sniper = Sniper('麦克')
sniper.gun = None
m99.pick()
sniper.gun = m99
sniper.fire()
|
26512ab5196720a3656e5bb735ec4bd229fa7a7c | shloang/RPCgame | /rps/game.py | 2,313 | 3.859375 | 4 | import random
class RPCGame:
def __init__(self):
self.rule_dict = {"rock": 0, "paper": 1, "scissors": 2}
self.rule_list = list(self.rule_dict.keys())
self.score = 0
def build_rule_dict(self, rule_string=""):
if rule_string != "":
rule_list = rule_string.split(",")
rule_dict = dict((rule_list[i], i) for i in range(len(rule_list)))
self.rule_dict = rule_dict
self.rule_list = rule_list
def check_input(self, string):
if string == "!rating":
print(f"Your rating: {self.score}")
return False
elif self.rule_dict.get(string, -1) == -1:
print("Invalid input")
return False
return True
def find_winner(self, input_string):
input_choice = self.rule_dict[input_string]
computer_choice = random.randrange(0, len(self.rule_dict))
n = len(self.rule_list)
k = input_choice
p = computer_choice
beater_switch = k - (n + 1) / 2
if input_choice == computer_choice:
print(f"There is a draw ({self.rule_list[computer_choice]})")
self.score += 50
elif (beater_switch < 0 and k < p <= n + beater_switch) or \
(beater_switch >= 0 and not beater_switch < p < k):
print(f"Sorry, but computer chose {self.rule_list[computer_choice]}")
else:
print(f"Well done. Computer chose {self.rule_list[computer_choice]} and failed")
self.score += 100
def get_score(self, name):
scoreboard = open("rating.txt", "r")
for line in scoreboard:
row = line.split(" ")
if row[0] == name:
self.score = int(row[1])
scoreboard.close()
def run(self):
user_input = input("Enter your name: ")
if user_input != "!exit":
print(f"Hello, {user_input}")
self.get_score(user_input)
self.build_rule_dict(input())
print("Okay, let's start")
user_input = input()
while user_input != "!exit":
if self.check_input(user_input) is True:
self.find_winner(user_input)
user_input = input()
print("Bye!")
game = RPCGame()
game.run()
|
ba66782ba04eec189ed1da859d05e016b05b6fdd | atomextranova/leetcode-python | /High_Frequency/two_pointers/同向双指针/Sliding Windows/Minimum Window Substring/Sliding Window Template.py | 1,417 | 3.875 | 4 | class Solution:
"""
@param source : A string
@param target: A string
@return: A string denote the minimum window, return "" if there is no such a string
"""
def minWindow(self, source , target):
# write your code here
if not source or not target:
return ""
target_to_count = {}
for char in target:
target_to_count[char] = target_to_count.get(char, 0) + 1
char_to_count = {}
matched = 0
source_length = len(source)
target_length = len(target_to_count)
right = 0
min_length = float('inf')
answer = ""
for left in range(len(source)):
while right < source_length and matched < target_length:
char = source[right]
char_to_count[char] = char_to_count.get(char, 0) + 1
if char in target_to_count and char_to_count[char] == target_to_count[char]:
matched += 1
right += 1
if matched == target_length:
if min_length > right - left:
min_length = right - left
answer = source[left:right]
char = source[left]
char_to_count[char] = char_to_count[char] - 1
if char in target_to_count and char_to_count[char] < target_to_count[char]:
matched -= 1
return answer |
622abeceea1d71ed6769ec093d4e0c5121b794b0 | riunixnix/pytest-simple-examples | /test_2.py | 777 | 3.765625 | 4 | import pytest
""" Create Method to calculate formula below with input `number`
( number + 1) * ( number - 1)
"""
def plus_1(number):
""" number+1 """
return number+1
def minus_1(number):
""" number-1 """
return number-1
def multiply(number_1, number_2):
""" number_1 x number_2 """
return number_1 * number_2
def formula(number):
""" (number+1) x (number-1) """
return multiply(
plus_1(number),
minus_1(number)
)
# --- testing code --
@pytest.mark.unit
def test_plus_1():
assert plus_1(1) == 2
@pytest.mark.unit
def test_minus_1():
assert minus_1(1) == 0
@pytest.mark.unit
def test_multiply():
assert multiply(2, 5) == 10
@pytest.mark.integration
def test_formula():
assert formula(10) == 99
|
0de38892813b619cb9a3507623be2a37c8274ba8 | RicardoATB/connect-dots | /connect-dots.py | 1,594 | 3.609375 | 4 | #!/usr/bin/python3.8
# Description: Program that connects dots from a list of coordinate points
# Author: Ricardo Augusto Teixeira Barbosa
import argparse
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
from matplotlib.backend_bases import MouseButton
show_dots = False
data = []
def plot_graph(show_dots):
global data
plt.close()
plt.figure(figsize=(20,20)) # must set figsize before plotting it
x, y = data.T
if (show_dots):
plt.plot(*data.T, marker=".", linewidth=3, markersize=30, markerfacecolor='red', color='blue')
else:
plt.plot(*data.T, linewidth=3)
plt.gca().invert_yaxis()
plt.axis('equal')
plt.connect('button_press_event', on_click)
plt.show()
def on_click(event):
global show_dots
if event.button is MouseButton.LEFT:
show_dots = not show_dots # toggle
plot_graph(show_dots)
def parse_args():
parser = argparse.ArgumentParser(description = "Connect dots from 'X Y' coordinate list", \
epilog = "Usage: python connect_dots.py --input <filename>")
parser.add_argument("--input", required=True, metavar="<input_file>",
type=str, help="file with coordinate list")
args = parser.parse_args()
if not os.path.exists(args.input):
raise Exception ("Error: input file does not exist")
return args
def main():
global data
args = parse_args()
try:
data = np.loadtxt(args.input)
except:
print("Unexpected error while file with coordinates")
plot_graph(show_dots)
if __name__ == "__main__":
sys.exit(main())
|
8cfe53df58492712ae5dba169c01a19fa7abfa0f | VolodymyrKM/km_test2 | /restaurant.py | 1,500 | 3.765625 | 4 | class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(f'The name of the restaurant is {self.restaurant_name}.')
print(f'The cuisine of the restaurant is {self.cuisine_type}.')
def open_restaurant(self):
print(f'The restaurant {self.restaurant_name} is open!')
def set_number_served(self, number_served):
self.number_served = number_served
def increment_number_served(self, set_number):
self.number_served += set_number
# resto = Restaurant('Vizit', 'Ukraine')
#
# resto.set_number_served(5)
# resto.set_number_served(5)
#
# resto.increment_number_served(5)
# resto.increment_number_served(60)
#
# print(resto.number_served)
#
# #
# wite_rabbit = Restaurant('Rabbit', 'Traditional American')
#
# print(wite_rabbit.restaurant_name)
# print(wite_rabbit.cuisine_type)
#
# wite_rabbit.open_restaurant()
# wite_rabbit.describe_restaurant()
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.flavors = []
def flavors_list(self):
print(self.flavors)
ice_cream = IceCreamStand('Sweet Ice Cream', 'Sweety')
# ice_cream.flavors = ['chokolate', 'milk', 'banana']
ice_cream.flavors_list()
|
7fb77f6cad1c60f14b2f05210e0dcc197c3a5de5 | srinidp/dplearn-python | /_modules/mycsv_file1.py | 14,902 | 3.84375 | 4 | #-------------------------------------------------------------------------------
# Name: mycsv_file1
# Purpose:
#
# Author: srini_000
#
# Created: 24/03/2018
# Copyright: (c) srini_000 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
import csv
def mycsvread():
print("***mycsvread***")
with open("names.csv", 'r') as datafile:
inputdata = csv.reader(datafile)
#print(inputdata)
for line in inputdata:
print(line)
print(line[1])
def mycsvreadwrite():
print("***mycsvreadwrite***")
with open("names.csv", 'r') as datafile:
inputdata = csv.reader(datafile)
#print(inputdata)
with open("names1.csv", 'w') as outputfile:
outputdata = csv.writer(outputfile, delimiter = '-')
#print(outputdata)
# skips 1 line
next(inputdata)
for line in inputdata:
outputdata.writerow(line)
def mycsvread1():
print("***mycsvread1***")
with open("names.csv", 'r') as datafile:
inputdata = csv.DictReader(datafile)
#print(inputdata)
for line in inputdata:
print(line)
print(line['lname'])
def mycsvreadwrite1():
print("***mycsvreadwrite1***")
with open("names.csv", 'r') as datafile:
inputdata = csv.DictReader(datafile)
#print(inputdata)
header = ["email"]
with open("names1_email.csv", 'w') as outputfile:
outputdata = csv.DictWriter(outputfile, fieldnames = header)
#print(outputdata)
outputdata.writeheader()
for line in inputdata:
del line['fname']
del line['lname']
outputdata.writerow(line)
def csvmain():
print("csv")
print()
mycsvread()
print()
mycsvread1()
print()
mycsvreadwrite()
print()
mycsvreadwrite1()
print()
print("csv end")
csvmain()
##NAME
## csv - CSV parsing and writing.
##
##DESCRIPTION
## This module provides classes that assist in the reading and writing
## of Comma Separated Value (CSV) files, and implements the interface
## described by PEP 305. Although many CSV files are simple to parse,
## the format is not formally defined by a stable specification and
## is subtle enough that parsing lines of a CSV file with something
## like line.split(",") is bound to fail. The module supports three
## basic APIs: reading, writing, and registration of dialects.
##
##
## DIALECT REGISTRATION:
##
## Readers and writers support a dialect argument, which is a convenient
## handle on a group of settings. When the dialect argument is a string,
## it identifies one of the dialects previously registered with the module.
## If it is a class or instance, the attributes of the argument are used as
## the settings for the reader or writer:
##
## class excel:
## delimiter = ','
## quotechar = '"'
## escapechar = None
## doublequote = True
## skipinitialspace = False
## lineterminator = '\r\n'
## quoting = QUOTE_MINIMAL
##
## SETTINGS:
##
## * quotechar - specifies a one-character string to use as the
## quoting character. It defaults to '"'.
## * delimiter - specifies a one-character string to use as the
## field separator. It defaults to ','.
## * skipinitialspace - specifies how to interpret whitespace which
## immediately follows a delimiter. It defaults to False, which
## means that whitespace immediately following a delimiter is part
## of the following field.
## * lineterminator - specifies the character sequence which should
## terminate rows.
## * quoting - controls when quotes should be generated by the writer.
## It can take on any of the following module constants:
##
## csv.QUOTE_MINIMAL means only when required, for example, when a
## field contains either the quotechar or the delimiter
## csv.QUOTE_ALL means that quotes are always placed around fields.
## csv.QUOTE_NONNUMERIC means that quotes are always placed around
## fields which do not parse as integers or floating point
## numbers.
## csv.QUOTE_NONE means that quotes are never placed around fields.
## * escapechar - specifies a one-character string used to escape
## the delimiter when quoting is set to QUOTE_NONE.
## * doublequote - controls the handling of quotes inside fields. When
## True, two consecutive quotes are interpreted as one during read,
## and when writing, each quote character embedded in the data is
## written as two quotes
##
##CLASSES
## builtins.Exception(builtins.BaseException)
## _csv.Error
## builtins.object
## Dialect
## excel
## excel_tab
## DictReader
## DictWriter
## Sniffer
##
## class Dialect(builtins.object)
## | Describe a CSV dialect.
## |
## | This must be subclassed (see csv.excel). Valid attributes are:
## | delimiter, quotechar, escapechar, doublequote, skipinitialspace,
## | lineterminator, quoting.
## |
## | Methods defined here:
## |
## | __init__(self)
## |
## | ----------------------------------------------------------------------
## | Data descriptors defined here:
## |
## | __dict__
## | dictionary for instance variables (if defined)
## |
## | __weakref__
## | list of weak references to the object (if defined)
## |
## | ----------------------------------------------------------------------
## | Data and other attributes defined here:
## |
## | delimiter = None
## |
## | doublequote = None
## |
## | escapechar = None
## |
## | lineterminator = None
## |
## | quotechar = None
## |
## | quoting = None
## |
## | skipinitialspace = None
##
## class DictReader(builtins.object)
## | Methods defined here:
## |
## | __init__(self, f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
## |
## | __iter__(self)
## |
## | __next__(self)
## |
## | ----------------------------------------------------------------------
## | Data descriptors defined here:
## |
## | __dict__
## | dictionary for instance variables (if defined)
## |
## | __weakref__
## | list of weak references to the object (if defined)
## |
## | fieldnames
##
## class DictWriter(builtins.object)
## | Methods defined here:
## |
## | __init__(self, f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
## |
## | writeheader(self)
## |
## | writerow(self, rowdict)
## |
## | writerows(self, rowdicts)
## |
## | ----------------------------------------------------------------------
## | Data descriptors defined here:
## |
## | __dict__
## | dictionary for instance variables (if defined)
## |
## | __weakref__
## | list of weak references to the object (if defined)
##
## class Error(builtins.Exception)
## | Method resolution order:
## | Error
## | builtins.Exception
## | builtins.BaseException
## | builtins.object
## |
## | Data descriptors defined here:
## |
## | __weakref__
## | list of weak references to the object (if defined)
## |
## | ----------------------------------------------------------------------
## | Methods inherited from builtins.Exception:
## |
## | __init__(self, /, *args, **kwargs)
## | Initialize self. See help(type(self)) for accurate signature.
## |
## | __new__(*args, **kwargs) from builtins.type
## | Create and return a new object. See help(type) for accurate signature.
## |
## | ----------------------------------------------------------------------
## | Methods inherited from builtins.BaseException:
## |
## | __delattr__(self, name, /)
## | Implement delattr(self, name).
## |
## | __getattribute__(self, name, /)
## | Return getattr(self, name).
## |
## | __reduce__(...)
## |
## | __repr__(self, /)
## | Return repr(self).
## |
## | __setattr__(self, name, value, /)
## | Implement setattr(self, name, value).
## |
## | __setstate__(...)
## |
## | __str__(self, /)
## | Return str(self).
## |
## | with_traceback(...)
## | Exception.with_traceback(tb) --
## | set self.__traceback__ to tb and return self.
## |
## | ----------------------------------------------------------------------
## | Data descriptors inherited from builtins.BaseException:
## |
## | __cause__
## | exception cause
## |
## | __context__
## | exception context
## |
## | __dict__
## |
## | __suppress_context__
## |
## | __traceback__
## |
## | args
##
## class Sniffer(builtins.object)
## | "Sniffs" the format of a CSV file (i.e. delimiter, quotechar)
## | Returns a Dialect object.
## |
## | Methods defined here:
## |
## | __init__(self)
## |
## | has_header(self, sample)
## |
## | sniff(self, sample, delimiters=None)
## | Returns a dialect (or None) corresponding to the sample
## |
## | ----------------------------------------------------------------------
## | Data descriptors defined here:
## |
## | __dict__
## | dictionary for instance variables (if defined)
## |
## | __weakref__
## | list of weak references to the object (if defined)
##
## class excel(Dialect)
## | Describe the usual properties of Excel-generated CSV files.
## |
## | Method resolution order:
## | excel
## | Dialect
## | builtins.object
## |
## | Data and other attributes defined here:
## |
## | delimiter = ','
## |
## | doublequote = True
## |
## | lineterminator = '\r\n'
## |
## | quotechar = '"'
## |
## | quoting = 0
## |
## | skipinitialspace = False
## |
## | ----------------------------------------------------------------------
## | Methods inherited from Dialect:
## |
## | __init__(self)
## |
## | ----------------------------------------------------------------------
## | Data descriptors inherited from Dialect:
## |
## | __dict__
## | dictionary for instance variables (if defined)
## |
## | __weakref__
## | list of weak references to the object (if defined)
## |
## | ----------------------------------------------------------------------
## | Data and other attributes inherited from Dialect:
## |
## | escapechar = None
##
## class excel_tab(excel)
## | Describe the usual properties of Excel-generated TAB-delimited files.
## |
## | Method resolution order:
## | excel_tab
## | excel
## | Dialect
## | builtins.object
## |
## | Data and other attributes defined here:
## |
## | delimiter = '\t'
## |
## | ----------------------------------------------------------------------
## | Data and other attributes inherited from excel:
## |
## | doublequote = True
## |
## | lineterminator = '\r\n'
## |
## | quotechar = '"'
## |
## | quoting = 0
## |
## | skipinitialspace = False
## |
## | ----------------------------------------------------------------------
## | Methods inherited from Dialect:
## |
## | __init__(self)
## |
## | ----------------------------------------------------------------------
## | Data descriptors inherited from Dialect:
## |
## | __dict__
## | dictionary for instance variables (if defined)
## |
## | __weakref__
## | list of weak references to the object (if defined)
## |
## | ----------------------------------------------------------------------
## | Data and other attributes inherited from Dialect:
## |
## | escapechar = None
##
##FUNCTIONS
## field_size_limit(...)
## Sets an upper limit on parsed fields.
## csv.field_size_limit([limit])
##
## Returns old limit. If limit is not given, no new limit is set and
## the old limit is returned
##
## get_dialect(...)
## Return the dialect instance associated with name.
## dialect = csv.get_dialect(name)
##
## list_dialects(...)
## Return a list of all know dialect names.
## names = csv.list_dialects()
##
## reader(...)
## csv_reader = reader(iterable [, dialect='excel']
## [optional keyword args])
## for row in csv_reader:
## process(row)
##
## The "iterable" argument can be any object that returns a line
## of input for each iteration, such as a file object or a list. The
## optional "dialect" parameter is discussed below. The function
## also accepts optional keyword arguments which override settings
## provided by the dialect.
##
## The returned object is an iterator. Each iteration returns a row
## of the CSV file (which can span multiple input lines):
##
## register_dialect(...)
## Create a mapping from a string name to a dialect class.
## dialect = csv.register_dialect(name, dialect)
##
## unregister_dialect(...)
## Delete the name/dialect mapping associated with a string name.
## csv.unregister_dialect(name)
##
## writer(...)
## csv_writer = csv.writer(fileobj [, dialect='excel']
## [optional keyword args])
## for row in sequence:
## csv_writer.writerow(row)
##
## [or]
##
## csv_writer = csv.writer(fileobj [, dialect='excel']
## [optional keyword args])
## csv_writer.writerows(rows)
##
## The "fileobj" argument can be any object that supports the file API.
##
##DATA
## QUOTE_ALL = 1
## QUOTE_MINIMAL = 0
## QUOTE_NONE = 3
## QUOTE_NONNUMERIC = 2
## __all__ = ['QUOTE_MINIMAL', 'QUOTE_ALL', 'QUOTE_NONNUMERIC', 'QUOTE_NO...
##
##VERSION
## 1.0
##
##FILE
## c:\python34\lib\csv.py |
39d82267f966ca106ee384e540c31a3e5e433318 | fershady19/Algorithmic-Design-and-Techniques | /2_3_greatest_common_divisor.py | 408 | 3.75 | 4 | """
Task. Given two integers a and b, find their greatest common divisor.
Input Format. The two integers a, b are given in the same line separated by space.
Constraints. 1<=a,b<=2·109.
Output Format. Output GCD(a, b).
"""
def EuclidGCD(a, b):
if b == 0:
return a
else:
a = a%b
return EuclidGCD(b, a)
in_ = [int(n) for n in input().split()]
print(EuclidGCD(in_[0], in_[1]))
|
9cd5b925c3c170236a735000485d4f33ee2c7f1e | JohanEdenfjord/PythonSchoolProjects | /Lab2/racer2.py | 1,461 | 3.625 | 4 | from graphics import *
class racer:
def __init__(self, win, speedLimit):
self.circle = Circle(Point(0, 0), 10)
self.circle.setFill('red')
self.circle.draw(win)
self.letter = Text(Point(0, 0), 'R')
self.letter.setTextColor('white')
self.letter.draw(win)
self.xVelocity = 0
self.yVelocity = 0
self.speedLimit = speedLimit
def accelerate(self, xVel, yVel):
self.xVelocity += xVel
self.yVelocity += yVel
# tvingar hastighetsbegränsning
self.xVelocity = min(self.speedLimit, self.xVelocity)
self.xVelocity = max(-self.speedLimit, self.xVelocity)
self.yVelocity = min(self.speedLimit, self.yVelocity)
self.yVelocity = max(-self.speedLimit, self.yVelocity)
def slowDown(self):
self.xVelocity *= 0.85
self.yVelocity *= 0.85
def drive(self):
self._moveRelative(self.xVelocity, self.yVelocity)
def getX(self):
return self.circle.getCenter().getX()
def getY(self):
return self.circle.getCenter().getY()
def reset(self):
self._moveAbsolute(0,0)
self.xVelocity = 0
self.yVelocity = 0
def _moveAbsolute(self, x, y):
self._moveRelative(x-self.getX(), y-self.getY())
def _moveRelative(self, xDiff, yDiff):
self.circle.move(xDiff, yDiff)
self.letter.move(xDiff, yDiff)
def checkBorders(self):
pass
|
1f02810f111cda32bca48f2bc8d301f170617f05 | easyas123l1/Data-Structures | /lru_cache/lru_cache.py | 2,644 | 3.84375 | 4 | from doubly_linked_list import ListNode, DoublyLinkedList
class LRUCache:
"""
Our LRUCache class keeps track of the max number of nodes it
can hold, the current number of nodes it is holding, a doubly-
linked list that holds the key-value entries in the correct
order, as well as a storage dict that provides fast access
to every node stored in the cache.
"""
def __init__(self, limit=10):
self.limit = limit
self.size = 0
self.list = DoublyLinkedList()
self.cache = dict()
"""
Retrieves the value associated with the given key. Also
needs to move the key-value pair to the end of the order
such that the pair is considered most-recently used.
Returns the value associated with the key or None if the
key-value pair doesn't exist in the cache.
"""
def get(self, key):
# check if key is in cache
if key in self.cache.keys():
# cache is holding reference to node
node = self.cache[key]
# move the node to the head because its being accessed
self.list.move_to_front(node)
# return value of node
return node.value[1]
else:
# key doesn't exist return None
return None
"""
Adds the given key-value pair to the cache. The newly-
added pair should be considered the most-recently used
entry in the cache. If the cache is already at max capacity
before this entry is added, then the oldest entry in the
cache needs to be removed to make room. Additionally, in the
case that the key already exists in the cache, we simply
want to overwrite the old value associated with the key with
the newly-specified value.
"""
def set(self, key, value):
# check if key is in cache
if key in self.cache.keys():
# the cache is holding a reference to the node
node = self.cache[key]
# update the exisitng node's value
node.value = (key, value)
# move the node to the head because its being accessed
self.list.move_to_front(node)
else:
# check to see if the limit is reached
if self.size == self.limit:
# delete the oldest from the cache
del self.cache[self.list.remove_from_tail()[0]]
self.size -= 1
# Add the new node to the head
node = (key, value)
self.list.add_to_head(node)
# set the cache to reference the node
self.cache[key] = self.list.head
self.size += 1
|
abc1cac2448842153a6c635a4ba6ea29240ff5ea | dujodujo/lemur | /Programiranje/vaja3/skalarni_produkt.py | 147 | 3.578125 | 4 | b = (1, 2, 3)
a = (4, 5, 6)
prod = 0
for x,y in zip(a,b):
prod += x*y
print(prod)
print(' + '.join('%d * %d' % (x, y) for x, y in zip(a, b))) |
eb1e4b9d04d1f2a779a45f294fa67b36171c403d | rishabh-16/Machine_Learning | /Decision Tree/decision_tree.py | 6,164 | 3.71875 | 4 | import numpy as np
"""=====================================MODULE FOR IMPLEMENTING DECISION TREE CLASSIFICATION=========================================="""
class Decision_Tree:
def fit(self,X,y):
try:
self.X=X.tolist()
self.y=y.tolist() #THIS CONVERTS X AND y TO LIST IF IT IS NOT
except:
self.X=X
self.y=y
self.m=len(X)
self.n=len(X[0])
self.Node=self.build_tree(self.X,self.y) #THIS NODE IS ROOT NODE OF THE TREE
def shuffle_in_unison(self,a, b):
"""
this function simply takes two arrays and shuffle them
in such a way that their corressponding values remain same
"""
rng_state = np.random.get_state()
np.random.shuffle(a)
np.random.set_state(rng_state)
np.random.shuffle(b)
def class_counts(self,y):
"""
THIS FUNCTION COUNTS THE OCCURANCES OF LABELS
AND RETURNS THE DICTIONARY
"""
counts={}
for label in y:
if label not in counts:
counts[label]=0
counts[label]+=1
return counts
def gini(self,X,y):
"""
THIS FUNCTION RETURNS THE GINI IMPURITY IN THE GIVEN BRANCH OF TREE
"""
counts = self.class_counts(y)
impurity = 1
for lbl in counts:
prob_of_lbl = counts[lbl] / float(len(X))
impurity -= prob_of_lbl**2
return impurity
def info_gain(self, true_X, true_y, false_X, false_y, current_uncertainty):
"""
IT RETURNS THE AMOUNT OF INFORMATION GAINED ACROSS A NODE
"""
p = float(len(true_X)) / (len(true_X) + len(false_X))
return current_uncertainty - p * self.gini(true_X, true_y) - (1 - p) * self.gini(false_X, false_y)
class Question:
def __init__(self,column,value):
self.column=column
self.value=value
def match(self,example):
val=example[self.column]
if isinstance(val,int) or isinstance(val,float):
return val>=self.value
else:
return val==self.value
def partition(self,X,y,question):
"""
THIS FUNCTION PARTITIONS THE DATA INTO TWO BRANCHS ACCORDING TO A GIVEN CONDITION
AND RETURNS THE BRANCHES
"""
true_X,true_y,false_X,false_y=[],[],[],[]
for i in range(len(X)):
if question.match(X[i]):
true_X.append(X[i])
true_y.append(y[i])
else:
false_X.append(X[i])
false_y.append(y[i])
return true_X,true_y,false_X,false_y
def find_best_split(self,X,y):
"""
IT FINDS THE BEST QUESTION TO BE ASKED TO HAVE MAXIMUM INFORMATION GAIN
"""
best_gain = 0
best_question = None
current_uncertainty = self.gini(X,y)
for col in range(self.n):
values = set([row[col] for row in X])
for val in values:
question = self.Question(col, val)
true_X, true_y, false_X, false_y = self.partition(X, y, question)
if (len(true_X) == 0 or len(false_X) == 0):
continue
gain = self.info_gain(true_X, true_y, false_X, false_y, current_uncertainty)
if gain >= best_gain:
best_gain, best_question = gain, question
return best_gain, best_question
class Leaf:
"""
IT IS THE LEAF NODE THAT CONTAINS THE MOST CLASSIFIED INFO
"""
def __init__(self,X,y):
counts=Decision_Tree().class_counts(y)
total=sum(counts.values())
for label in counts.keys():
counts[label]=str(counts[label]/total * 100)+"%"
self.predictions=counts
class Decision_Node:
"""
IT IS THE NODE FROM WHICH BRANCHING OCCURS
"""
def __init__(self,question,true_branch,false_branch):
self.true_branch=true_branch
self.false_branch=false_branch
self.question=question
def build_tree(self, X, y):
"""
THIS FUNCTIONS DO THE BRANCHING RECURSIVELY AND RETURNS THE RESPECTIVE NODES
"""
gain, question=self.find_best_split(X,y)
if gain == 0:
return self.Leaf(X,y)
true_X,true_y,false_X,false_y=self.partition(X,y,question)
true_branch=self.build_tree(true_X,true_y)
false_branch=self.build_tree(false_X,false_y)
return self.Decision_Node(question,true_branch,false_branch)
def classify(self,Node,example):
"""
IT IS USED TO CLASSIFY AN EXAMPLE BY USIND THE TREE
"""
if isinstance(Node,self.Leaf):
return Node.predictions
else:
if(Node.question.match(example)):
return self.classify(Node.true_branch,example)
else:
return self.classify(Node.false_branch,example)
def predict(self,X_test): #_________PREDICTS THE OUTPUT________#
y_pred=[]
for example in X_test:
d=self.classify(self.Node,example)
v=list(d.values())
k=list(d.keys())
y_pred.append(k[v.index(max(v))])
return np.array(y_pred)
def accuracy(self,X_test,y_test): #_________TESTS THE ACCURACY OF THE MODEL______#
y_pred=self.predict(X_test)
a=np.array(y_pred==y_test)
acc=np.mean(a)*100
return acc
def predict_prob(self,X_test): #__________PREDICTS THE PROBABILITY________#
y_pred=[]
for example in X_test:
y_pred.append(self.classify(self.Node,example))
return y_pred
"""==================================================XXX======================================================================="""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.