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
|
---|---|---|---|---|---|---|
8e65e9c2183bec0cbddbd250605204fd6a28bf0d | phibzy/InterviewQPractice | /Solutions/RemoveElement/removeElement.py | 485 | 3.5 | 4 | #!/usr/bin/python3
"""
@author : Chris Phibbs
@created : Wednesday Sep 02, 2020 10:42:57 AEST
@file : removeElement
"""
class Solution:
def removeElement(self, nums, val):
if not nums: return 0
nums.sort()
i = 0
while i < len(nums):
if nums[i] == val:
del nums[i]
elif nums[i] > val:
break
else:
i += 1
return len(nums)
|
d5656aea38fb85f2cc8fbbe4532fa89fcfbd0de1 | briann-paull/DATA-SCIENCE-PROJECTS_3 | /kMeans.salary.ore/K Means.py | 1,990 | 3.890625 | 4 | #importing packages
from sklearn.cluster import KMeans
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from matplotlib import pyplot as plt
#iporting data
df = pd.read_csv("income.csv")
df.head()
#cisualizing data
plt.scatter(df.Age,df['Income($)'])
plt.xlabel('Age')
plt.ylabel('Income($)')
#kmean clustering
km = KMeans(n_clusters=3)
y_predicted = km.fit_predict(df[['Age','Income($)']])
y_predicted
#k_mean prediction
df['cluster']=y_predicted
df.head()
km.cluster_centers_
#visualizzing kmeans prediction
df1 = df[df.cluster==0]
df2 = df[df.cluster==1]
df3 = df[df.cluster==2]
plt.scatter(df1.Age,df1['Income($)'],color='green')
plt.scatter(df2.Age,df2['Income($)'],color='red')
plt.scatter(df3.Age,df3['Income($)'],color='black')
plt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1],color='purple',marker='*',label='centroid')
plt.xlabel('Age')
plt.ylabel('Income ($)')
plt.legend()
plt.show()
#applying minmaxscaler to increase accuracy
scaler = MinMaxScaler()
scaler.fit(df[['Income($)']])
df['Income($)'] = scaler.transform(df[['Income($)']])
scaler.fit(df[['Age']])
df['Age'] = scaler.transform(df[['Age']])
plt.scatter(df.Age,df['Income($)'])
km = KMeans(n_clusters=3)
y_predicted = km.fit_predict(df[['Age','Income($)']])
y_predicted
df['cluster']=y_predicted
df.head()
#visuallzing new predicted data with minmaxscaler
df1 = df[df.cluster==0]
df2 = df[df.cluster==1]
df3 = df[df.cluster==2]
plt.scatter(df1.Age,df1['Income($)'],color='green')
plt.scatter(df2.Age,df2['Income($)'],color='red')
plt.scatter(df3.Age,df3['Income($)'],color='black')
plt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1],color='purple',marker='*',label='centroid')
plt.legend()
plt.show()
#elbow method to see k value
sse = []
k_rng = range(1,10)
for k in k_rng:
km = KMeans(n_clusters=k)
km.fit(df[['Age','Income($)']])
sse.append(km.inertia_)
plt.xlabel('K')
plt.ylabel('Sum of squared error')
plt.plot(k_rng,sse)
plt.show()
|
ffa506b90bee59239e1d9a499e615ed94fde07b7 | noors312/ex.py | /ex.py | 485 | 3.609375 | 4 | from random import *
list_ = ['up','down','left','right']
random_list = [choice(list_) for i in range(20)]
def step(list):
str_ = ''.join(list)
if str_.count('left') == str_.count('right') and str_.count('up') == str_.count('down'):
print(str_.count('right'), str_.count('left'), str_.count('up'). str_.count('down'))
return True
print(str_.count('right'), str_.count('left'), str_.count('up'), str_.count('down'))
return False
print(step(random_list)) |
8d8ab8150896f6ddbd2e311b30718ea719cab10a | DomomLLL/newpy | /jiaoben/yxwd/yxwd.py | 526 | 3.5 | 4 | from HERO import Hero
from HERO import monster
import unittest
class TestHero(unittest.TestCase):
def test_init_hero(self):
lisy = Hero(name = 'lisy', hp =100, ack = 10)
self.assertEqual(lisy.hp, 100)
self.assertEqual(lisy.ack, 10)
def test_hero_ack(self):
if lisy.ack > monster().ack:
t = monster/(self.ack - monster().ack)
return "击杀时间为{}".format(t)
else:
print(Hero().ack)
d = TestHero()
print(d.test_hero_ack())
unittest.main()
|
83b4baf77bc53e42fb4e2b5d87acb0ec7441f58b | snebotcifpfbmoll/ED | /P06E14.py | 1,270 | 4.0625 | 4 | # P06E14:
# Desarrolla un programa junto con tu compañero, apoyándote en la “metodología pair programming” que tenga las siguientes características:
# While
print("Calculadora Fibonacci")
iteraciones = int(input("Introduce el numero de valores que quieres: "))
num_1 = 0
num_2 = 1
print("%d, %d, " % (num_1, num_2), end="")
while iteraciones > 2:
resultado = num_1 + num_2
print(resultado, end="")
if iteraciones > 3:
print(end=", ")
num_1 = num_2
num_2 = resultado
iteraciones -= 1
print("")
# For
iteraciones = int(input("Introduce el numero de valores que quieres: "))
num_1 = 0
num_2 = 1
print("%d, %d, " % (num_1, num_2), end="")
for i in range(iteraciones - 2):
resultado = num_1 + num_2
print(resultado, end="")
if i < iteraciones - 3:
print(end=", ")
num_1 = num_2
num_2 = resultado
print("")
# Reflexion:
# En adecuacion, el for es mas apropiado para este caso puesto que es una secuencia a la que el usuario fija la cantidad de veces que se repetira la misma, si bien el while puede utilizarse para la misma funcion agregando una variable auxiliar, este es mas apropiado para un entorno en el que se desconozca la cantidad de veces que se repetira la secuencia.
# Don Serafin Nebot Ginard y Don Daniel Alfredo Apesteguia Timoner ©
|
91c9a1d7e3c26281ea45eb13339a707b9bc76cd5 | huangqingyi-code/ai | /代码/PythonStudy/tuple操作.py | 267 | 3.9375 | 4 | print(" ============ tuple 操作 ============")
a = (1, 2, 3, 4)
print(len(a)) # 计算包含元素的个数
print(a[2]) # 获取集合第2个元素
# 查看元素4的索引
print(a.index(4))
# tuple不能修改,所以任何修改性操作都会报错
#a[2]=5
|
0ab07f8a9ccd99a37fbb8a05a4c13d8564d686f4 | MauGarrido/hyperblog | /codigo Python/alan.py | 815 | 3.78125 | 4 | import pandas as pd
# Aquí va el código para confirmar si quiere visualizar la información, y en ese caso si quiere cambiarla o simplemente guardarla
def run():
mi_info = {
'tarea': input("Hola, bienvenido, guardaremos la tarea quieres registrar, cuál es el nombre de la tarea:"),
'descripción': input("Genial, danos una breve descripción de ella: "),
'prioridad': int(input("""Muy bien, ahora ¿cuál es su prioriodad?
1. Baja
2. Media
3. Alta""")),
'responsable': input("Genial, ya casi terminamos, compártenos un nombre para identificarte dentro de nuestra base de datos: "),
}
df = pd.DataFrame(data, columns = ['tarea', 'descripcion', 'prioridad', 'responsable'])
df.to_excel('datos.xlsx', sheet_name='datos')
if __name__ == '__main__':
run() |
3355a14fc2596e5a8135571cb6ff17ab42835c72 | emmaliden/thePythonWorkbook | /E23.py | 363 | 4.46875 | 4 |
# Calculate and display the area of a polygon with length of side is s and number of sides is n
from math import tan, pi
n = int(input("How many sides does the polygon have?: "))
s = float(input("What is the length of each side in centimeters?: "))
area = round(((n*s**2)/(4*tan(pi/n))),2)
print("The area of the polygon is %r square centimeters" % (area))
|
b1201874749db182097bc203e4c6f053daedaa64 | ivoryspren/basic_data_structures | /binary_tree_recursive.py | 1,680 | 3.828125 | 4 | class Node(object):
def __init__(self, d, n = None):
self.data = d
self.next_node = n
def get_next (self):
return self.next_node
def set_next (self, n):
self.next_node = n
def get_data (self):
return self.data
def set_data (self, d):
self.data = d
class BinaryTree (object):
def __init__(self, r=None):
self.root = r
self.size = 0
def get_size (self):
return self.size
def add (self, d):
new_node = Node (d, self.root)
self.root = new_node
self.size += 1
def remove (self, this_node, d):
#this_node = self.root
prev_node = None
if this_node.get_data() == d:
print("d is equal to: " + str(d))
if prev_node:
prev_node.set_next(this_node.get_next())
else:
self.root = this_node
self.size -= 1
print("d removed")
return True
else:
if this_node.get_next() == None:
return None
else:
return self.remove(this_node.get_next(),d)
def find (self, this_node, d):
if this_node.get_data() == d:
print("d is equal to: " + str(d))
return d
else:
if this_node.get_next() == None:
return None
else:
return self.find(this_node.get_next(),d)
myList = BinaryTree()
myList.add(5)
myList.add(17)
myList.add(23)
#x = myList.find(myList.root,5)
y = myList.remove(myList.root,5)
#print(x)
print(y)
x = myList.find(myList.root,5)
print(x)
#print(myList.root.get_next().get_data())
|
ec2795019fe974000648ad2542e4dea12e3f270f | manne05/Konzepte | /scope.py | 421 | 3.765625 | 4 | # Zugriff auf die globale Variable x in der Funktion foo1() muss mit
# global x erfolgen.
x = 5
def foo1():
global x
x += 1
print(x)
print("global x")
foo1()
# Zugriff auf die lokale Variable x der Funktion foo2() in der lokalen Funktion
# bar() muss mit nonlocal x erfolgen.
def foo2():
x = 5
def bar():
nonlocal x
x += 1
print(x)
bar()
print("nonlocal x")
foo2()
|
455467d7f5a67ee58d377d2804a9514e68c81d6b | wyaadarsh/LeetCode-Solutions | /Python3/0211-Add-and-Search-Word-Data-Structure-Design/soln-1.py | 1,555 | 3.9375 | 4 | class TrieNode:
def __init__(self):
self.is_word = False
self.children = collections.defaultdict(TrieNode)
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
cur = self.root
for ch in word:
cur = cur.children[ch]
cur.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
return self.dfs(word, 0, self.root)
def dfs(self, word, idx, cur):
if idx == len(word):
if cur and cur.is_word:
return True
else:
return False
else:
if cur is None:
return False
if word[idx] == '.':
for nxt in cur.children.values():
if self.dfs(word, idx + 1, nxt):
return True
return False
else:
if self.dfs(word, idx + 1, cur.children.get(word[idx], None)):
return True
else:
return False
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
|
d44147469464185ce57f90868a3eb02bbeac0b75 | rohithprem/Python-Lessons | /HomeWork/HW9.py | 3,224 | 3.671875 | 4 | class Vehicle():
def __init__(self, make, model, year, weight, needsMaintenance = False, tripSinceMaintenance = 0):
self.make = make
self.model = model
self.year = year
self.weight = weight
self.needsMaintenance = needsMaintenance
self.tripSinceMaintenance = tripSinceMaintenance
def setMake(self, make):
self.make = make
def getMake(self):
return self.make
def setModel(self, model):
self.model = model
def getModel(self):
return self.model
def getYear(self):
return self.year
def setYear(self, year):
self.year = year
def getWeight(self):
return self.weight
def setWeight(self, weight):
self.weight = weight
def setNeedsMaintenance(self, needsMaintenance):
self.needsMaintenance = needsMaintenance
def getNeedsMaintenance(self):
return self.needsMaintenance
def setTripSinceMaintenance(self, tripSinceMaintenance):
self.tripSinceMaintenance = tripSinceMaintenance
def getTripSinceMaintenance(self):
return self.tripSinceMaintenance
def repair(self):
self.needsMaintenance = False
self.tripSinceMaintenance = 0
def __str__(self):
return "\nMake: " + self.make + "\nModel: " + self.model + " \nYear: " + str(self.year) + "\nWeight: " + self.weight + "\nNeeds Maintenance: " + str(self.needsMaintenance) + "\nTrips Since Maintenance: " + str(self.tripSinceMaintenance)
class Cars(Vehicle):
def __init__(self, make, model, year, weight, needsMaintenance = False, tripSinceMaintenance = 0, isDriving = False):
Vehicle.__init__(self, make, model, year, weight, needsMaintenance, tripSinceMaintenance)
self.isDriving = isDriving
def drive(self):
self.isDriving = True
def stop(self):
self.isDriving = False
self.tripSinceMaintenance += 1
if self.tripSinceMaintenance > 100:
self.needsMaintenance = True
class Planes(Vehicle):
def __init__(self, make, model, year, weight, needsMaintenance = False, tripSinceMaintenance = 0, isFlying = False):
Vehicle.__init__(self, make, model, year, weight, needsMaintenance, tripSinceMaintenance)
self.isFlying = isFlying
def fly(self):
if self.needsMaintenance:
print("Plane cannot fly until it is repaired")
self.isFlying = False
else:
self.isFlying = True
return self.isFlying
def land(self):
self.isFlying = False
self.tripSinceMaintenance += 1
if self.tripSinceMaintenance > 100:
self.needsMaintenance = True
car1 = Cars("Honda", "Civic", 2020, "800kg")
car2 = Cars("Toyota", "Camry", 1995, "9500kg")
car3 = Cars("Jeep", "Cherokee", 2000, "1050kg")
for i in range(101):
car1.drive()
car1.stop()
for i in range(50):
car2.drive()
car2.stop()
for i in range(200):
car3.drive()
car3.stop()
print(car1)
print(car2)
print(car3)
plane1 = Planes("Airbus", "A380", 2020, "10000kg")
plane2 = Planes("Boeing", "777", 1995, "10500kg")
plane3 = Planes("Airbus", "A320", 2000, "9000kg")
for i in range(101):
if not plane1.fly():
break;
plane1.land()
for i in range(50):
if not plane2.fly():
break;
plane2.land()
for i in range(200):
if not plane3.fly():
break;
plane3.land()
print(plane1)
print(plane2)
print(plane3)
|
26e6982d518244c16418a290f1f49586667cace3 | BilalMubarakIdris/Nanos | /projects/capstone/thecrew_full_stack/thecrew-app-backend-api-python/app/date.py | 1,335 | 3.671875 | 4 | """Utilities for using date objects.
now(): the main function exported by this module.
"""
__author__ = "Filipe Bezerra de Sousa"
from datetime import datetime, timezone
from flask import current_app
def date_to_str(date):
"""Convert a date object to a string representation using the application
date format.
:param date: The :class:`datetime.datetime` object.
:return: The date string or `None` if can't convert it.
"""
try:
date_string = date.strftime(current_app.config['THECREW_DATE_FORMAT'])
except (TypeError, AttributeError):
return None
return date_string
def str_to_date(date_string):
"""Convert back string representation of a date to the date object using
the application date format.
:param date_string: The string representation of a :class:`datetime.datetime`
object.
:return: A instance of a :class:`datetime.datetime` object or `None` if
can't convert it.
"""
try:
date = datetime.strptime(
date_string, current_app.config['THECREW_DATE_FORMAT'])
except ValueError:
return None
return date
def now():
"""A instance of :class:`datetime.datetime` object with utc time zone info.
:return: A instance of a :class:`datetime.datetime` object.
"""
return datetime.now(tz=timezone.utc)
|
96b9bb5987559351a0233cfa54db607085b562ee | RyanCoplien/Dijkstras-Algorithm-in-Python | /LinkState.py | 3,044 | 3.921875 | 4 | #-----------------------------------------------------------------------
# Name: Ryan Coplien
# Project: LinkState Dijkstra Algorithm
# Course: 3830 Data Communications and Computer Networking
#-----------------------------------------------------------------------
import csv
import sys
import heapq as hq
from collections import defaultdict
results = []
nodes = 0
distanceList = []
costList = []
# Implementation of the Dijkstra's algorithm taking in the edges, the starting node
# and which node you want to go to
# returns: cost and path to the to_node
def dijkstra(edges, from_node, to_node):
graph = defaultdict(list)
# f = from node
# t = to node
# c = the cost between the nodes
for f, t, c in edges:
graph[f].append((c, t))
graph[t].append((c, f))
# pushes the first node to the queue
queue = [(0.0, from_node, ())]
# creates the visited and distance arrays to zero
visited = set()
distance = {from_node: 0}
while queue:
# Pops the node
(cost, node1, path) = hq.heappop(queue)
# if we have already been here then skip
if node1 in visited:
continue
visited.add(node1)
# Saving the path
path += (node1,)
for c, node2 in graph.get(node1, ()):
c = float(c)
# if we have already been here then skip
if node2 in visited:
continue
# if no distance is found or a cheaper cost is found then it replaces it
if node2 not in distance or cost + c < distance[node2]:
distance[node2] = cost + c
# Pushes the next node to the heap
hq.heappush(queue, (float(cost + c), node2, path))
# The end case of the loop returning the path and cost
if node1 == to_node:
return cost, path
return -1
# This opens the file and formats it in order to be read properly
with open(str(sys.argv[1]), newline='') as f:
reader = csv.reader(f, delimiter=' ')
firstLine = True
for row in reader:
if firstLine:
firstLine = False
nodes = row
else:
# converts to a tuple from an array
results.append(tuple(row))
# Takes start node from the parameters
start_node = str(sys.argv[2])
# Loops through each of the nodes from the one node
for i in [x for x in range(int(nodes[0])) if x != int(start_node)]:
# runs the algorithm and takes the results to be formatted
costs, paths = dijkstra(results, start_node, str(i))
if costs >= 0:
output = ""
for p in paths:
output += str(p) + '->'
output = output[:-2] # removes the bonus arrow because I was lazy
else:
# If the path is not found
costs = "N/A"
paths = "N/A"
print("shortest path to node " + str(i) + " is " + str(output) + " with cost: " + str(costs))
|
77c6d78f63c76c6dc8e449df5acbad5c091a7e73 | scvalencia/algorist | /03. Arrays and ADT's/examples/CreditCard.py | 1,285 | 4 | 4 | class CreditCard(object):
def __init__(self, customer, bank, acnt, limit):
''' Creates a new credit card instance.
The initial balance is zero
args:
customer (string): name of the customer (e.g. 'John Lynch')
bank (string) : name of thr bank (e.g 'Bank of San Serriffe')
acnt (strign) : account identifier (e.g '12321 343534 454545 43434')
limit (float) : credit limit measured in dollars
'''
self.customer = customer
self.bank = bank
self.acnt = acnt
self.limit = limit
self.balance = 0
def charge(self, price):
''' Charge given price to the card, assumming sufficient credit limit
args:
price (float) : price to be charged
returns:
boolean : a flag indicating if the charge was processed
'''
new_balance = price + self.balance
if new_balance > self.limit:
return False
else:
self.balance = new_balance
return True
def make_payment(self, amount):
''' Processes customer payment that reduces balance
args:
amount (float) : the amount of dollars to be removed from
the balance
returns:
boolean : a flag showing if the transaction was successful
'''
new_balance = self.balance - amount
if new_balance < 0:
return False
else:
self.balance = new_balance
return True
|
afdbdd370f09ae63aa0360fc629bbfe929b94995 | fishedee/PythonSample | /basic/control.py | 548 | 3.515625 | 4 | #if 控制
age = int(input("请输入你家狗狗的年龄: "))
if age == 1:
print("相当于 14 岁的人。")
elif age == 2:
print("相当于 22 岁的人。")
elif age > 2:
human = 22 + (age -2)*5
print("对应人类年龄: ", human)
else:
print("你是在逗我吧!")
# while控制
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和为: %d" % (n,sum))
# for控制
languages = ["C", "C++", "Perl", "Python"]
for x in languages:
print (x)
for i in range(5,9) :
print(i) |
dde6f5886f6992c15f1e0810a7e220956a5ba6d4 | dustinvo17/DS-Algo | /divide_and_conquer/sorted_arr_frequency_counter.py | 979 | 3.5 | 4 | # Given a sorted array and a number, write a function that counts the occurences of the number in the array
def count_num(arr,num):
start = 0
end = len(arr) - 1
i = None
j = None
while True:
if arr[start] == num:
start +=1
if arr[start+1] != num:
return start + 1
break
if arr[end] == num:
end -=1
if arr[end-1] != num:
return len(arr) - end
break
mid = int((start+end)//2)
if start > end:
return -1
break
if num < arr[mid]:
end = mid - 1
if num > arr[mid]:
start = mid + 1
if arr[mid] == num:
i = i if i is not None else mid -1
j = j if j is not None else mid +1
if arr[i] == num :
i -=1
if arr[j] == num :
j +=1
if arr[i] != num and arr[j] != num:
return j - (i+1)
break
print(count_num([1,1,1,3,3,3,3,4,4,4,4,5,5,5,5],5))
assert(count_num([1,1,1,3,3,3,3,4,4,4,4,5,5,5,5],5)) == 4 |
9ad1501004df57c55fcb69645dccd4bc4f6d0823 | lshinkuro/praxis-academy | /novice/minggu_1/hari-1/kasus algoritma sorting/shellsort.py | 765 | 3.953125 | 4 | def shellsort(alist):
sublistcount = len(alist)//2
while sublistcount >0:
for star_position in range(sublistcount):
gap_insertionsort(alist,star_position,sublistcount)
print ("after increment of size",sublistcount,"the list is",nlist)
sublistcount = sublistcount//2
def gap_insertionsort(nlist,start,gap):
for i in range(start+gap,len(nlist),gap):
current_value = nlist[i]
position =1
while position>= gap and nlist[position-gap]>current_value:
nlist[position]=nlist[position-gap]
position = position-gap
nlist[position]=current_value
nlist =[15,98,7,65,46,34,25,13,8]
shellsort(nlist)
print(nlist) |
eb6d86e3066c0193276948004f7486454e310a07 | rkoch7/Learning-Python | /chaining_and_teeing.py | 1,166 | 3.921875 | 4 | l1 = (i**2 for i in range(4))
l2 = (i**2 for i in range(4, 8))
l3 = (i**2 for i in range(8, 12))
# for gen in l1, l2, l3:
# for item in gen:
# print(item)
def chain_iterables(*l):
for iterable in l:
yield from iterable
l1 = (i**2 for i in range(4))
l2 = (i**2 for i in range(4, 8))
l3 = (i**2 for i in range(8, 12))
for item in chain_iterables(l1, l2, l3):
print(item)
from itertools import chain
l1 = (i**2 for i in range(4))
l2 = (i**2 for i in range(4, 8))
l3 = (i**2 for i in range(8, 12))
l = [l1, l2, l3]
for item in chain(*l):
print(item)
def squares():
print("yielding 1st item")
yield (i**2 for i in range(4))
print("yielding 2nd item")
yield (i**2 for i in range(4, 8))
print("yielding 3rd item")
yield (i**2 for i in range(8, 12))
# for item in chain(*squares()):
# print(item)
#unpacking is always eager, if there is heavy lifting done between yields
print("using chain.from_iterable")
for item in chain.from_iterable(squares()):
print(item)
from itertools import tee
def squares_(n):
for i in range(n):
yield i**2
gen = squares_(5)
iters = tee(gen, 3)
print(iters) |
f16484a84f4f1a172d1a26e675b8da8a9918291b | bharathmanvas/codes | /prefix.py | 219 | 3.71875 | 4 | def common(s1, s2):
out = ''
for i, j in zip(s1, s2):
if i != j:
break
out += i
return out
s1=input("enter")
s2=input("enter")
common(s1,s2)
print(common)
|
0fddd7ee03356083b9f3006cc730cd818b489676 | Subramanian11/word-game | /wordgame.py | 853 | 3.921875 | 4 | import random
system=['laptop','desktop','smart TV','Mobile']
print("Guess the word: {}".format(system))
store=random.choice(system)
# print(store)answer
j=2
def chance():
global j
if j>=1:
print("Still %d chances" %j)
else:
print("Game Over................")
j-=1
#let check with user:
i=0
while i<3:
get=input("Enter the Word: ")
if get not in system:
print("Cannot match item")
if get==store:
print("Your answer is matched")
print("Game Over.................")
play=input("If you like to play again [y or n]: ")
if play=='y':
j=2
i=0
store=random.choice(system)
continue
else:
break
# break
else:
print("Failed")
chance()
i+=1
|
f730e69f3c38129b18b22ad7df790a11f819f6e9 | jxvo/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 128 | 3.625 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
return list(list(map(lambda num: num ** 2, row)) for row in matrix)
|
f9a3bd589bc5ab2ac51507a0a6c7e923734b49a8 | Arsentiiiii/prac3 | /prac3.py | 1,454 | 3.703125 | 4 | """
#1. whitespace before '('
def f ():
print("Hello")
f()
#2. missing whitespace arount operator
print(5+ 4)
#3. missing whitespace after ','
print([2,3,4])
#4. unexpected spaces around keyword / parameter equals
def f(arg=0):
return 2**arg
f(arg = 2)
#5. expected 2 blank lines, found 1
def f1():
return "Hello"
def f2():
return "World"
#6. multiple statements on one line (color)
if True: print("hello")
#7. multiple statements on one line (semicolon)
print("hello"); print("world")
#8. comparison to None should be 'if cond is None:'
def f(x):
if x % 2 == 0:
return True
r = f(x)
if r == None:
print("odd")
#9. comparison to True should be 'if cond is True:' or 'if cond:'
def f(x):
if x % 2 == 0:
return True
r = f(x)
if r == True:
print("even")
"""
from printermodule import *
try:
hello() # hello
world() # world
except:
pass
import helloworldpkg.hello
import helloworldpkg.world
helloworldpkg.hello.printh()
helloworldpkg.world.printw()
import logging
import traceback
logging.basicConfig(filename='logfile.log', filemode='w', level=logging.INFO)
logging.raiseExceptions = True
def div(a, b):
try:
return a/b, None
except Exception as e:
return e, traceback.format_exc()
def run_with_log(func, a, b):
out, trace = div(a,b)
if trace is not None:
return logging.exception(f'{out}\n{trace}')
run_with_log(div, 6, 3)
run_with_log(div, 6, 0)
run_with_log(div, "5", 2) |
021ebe910d2ca68fe55d4517b5fea8d9eee0a887 | Barnsa/python-Instructional-Code | /welcomeChat.py | 3,438 | 4.0625 | 4 | ##################################################################################################################################
## Written by: Adam Barns ##
## Contact: [email protected] ##
## Created as part of an instructional series into Python programming ##
## ##
## Title: input / output ##
## ##
## Program something that can take input from a user and have a short conversation with a user. Run the test code included to ##
## see an example. The task is outlined as: ##
## - Use 'input' to gather and store a bunch of user supplied information. ##
## - Find a way to test that the code is working using 'try' statements. ##
## - Talk back to a user and try to have a realistic speaking experience (if a little basic). ##
## Advanced: ##
## - Store all of the variables in a file to recall them later. ##
## - Search through the user supplied text to find conversation topics (start of interactivity) ##
## - Program it using object orientated programming (use classes) to create a bot for multiple users. ##
## ##
##################################################################################################################################
import time
def testCode():
affirmative = ['YEAH', 'YES', 'OK', 'MAYBE', 'SORT OF', 'KIND OF', 'A BIT']
try:
name = str( input("What's your name?\n") )
age = int( input(f"It's lovely to meet you {name}, I wonder if I might trouble you for your age?\n") )
if age < 50:
print(f"{age} isn't very old is it?!\n")
elif age == 50:
print("Half a century old!! With age comes wisdom, with wisdom comes enlightenment.\n")
else:
print(f"It's a good job people are like a fine wine, cause you are approaching becoming the finest at {age} years old!!.\n")
except:
print("A conversation can't be had if you won't take this seriously!!\n")
try:
wait(3)
playSports = str( input("So do you play any sports?\n") )
playSportsFlag = 0
for i in range( len(affirmative) ):
if playSports.upper == affirmative[i]:
playSportsFlag = 1
if playSportsFlag == 1:
except:
if __name__ == "__main__":
testCode() |
bb4c2dd02b9cf38fc1e290835e8d30ca5118ac79 | JoshTheBlack/Project-Euler-Solutions | /060.py | 1,781 | 3.765625 | 4 | # coding=utf-8
# The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime.
# For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four
# primes with this property.
# Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
from operator import concat
from comm import *
from sympy import primerange, isprime
def catPrimeCheck(a,b):
if isprime(int(str(a)+str(b))) and isprime(int(str(b)+str(a))):
return True
return False
@timed
def p60(range=10000):
primes = list(primerange(1,range))
for a in primes:
if a == 2: continue
for b in primes:
if b <= a: continue
if not catPrimeCheck(a,b): continue
for c in primes:
if c <= b or c <= a: continue
if not catPrimeCheck(a,c): continue
if not catPrimeCheck(b,c): continue
for d in primes:
if d <= c or d <= b or d <= a: continue
if not catPrimeCheck(a,d): continue
if not catPrimeCheck(b,d): continue
if not catPrimeCheck(c,d): continue
for e in primes:
if e <= d or e <= c or e <= b or e <= a: continue
if not catPrimeCheck(a,e): continue
if not catPrimeCheck(b,e): continue
if not catPrimeCheck(c,e): continue
if not catPrimeCheck(d,e): continue
return f"{a+b+c+d+e} = {a} + {b} + {c} + {d} + {e}"
p60(range*10)
p60() |
5b38c66512eadbe6185363bc188e1a53da6d837c | Luorinz/courses | /NEU/cs5001/lab/lab01_Anda_Luo/name.py | 83 | 3.703125 | 4 | print("Please input your name:\t")
name = input()
print("Hello, there, %s!"%(name)) |
8aecc9e1e16bd83a8e36f01d1f85906b00cd5477 | timsergor/StillPython | /324.py | 1,077 | 3.59375 | 4 | # 788. Rotated Digits. Easy. 55.6%.
# X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.
# A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.
# Now given a positive number N, how many numbers X from 1 to N are good?
class Solution:
def rotatedDigits(self, N: int) -> int:
def isGood(k):
digits = []
while k > 1:
digits.append(k % 10)
k //= 10
Flag = False
for i in digits:
if i in [3,4,7]:
return False
elif i in [2,5,6,9]:
Flag = True
return Flag
answer = 0
for i in range(1,N + 1):
answer += int(isGood(i))
return answer
|
e8a0a6bebd27e308d09b206b6f29828be08b9316 | xiepfgit/PythonLearn | /MyFunctools.py | 564 | 3.953125 | 4 | # -*- coding: utf-8 -*-
'''
Created on 2019年7月13号
偏函数
@author: XPF
'''
def int2(x, base1=2):
return int(x, base1)
import functools
if __name__ == '__main__':
#以十进制转换为int
i= int('12345')
print(i)
#以8进制转换为int
i = int('12345', base=8)
print(i)
#以2进制转换为int
i = int2('10010', base1=2)
print(i)
int3 = functools.partial(int, base=2)
i = int3('10010')
print(i)
max2 = functools.partial(max, 10)
i = max2(5,6,7)
print(i)
pass |
79aec694dbb473c5e7d708704c6cc93dabfad411 | puneet29/algos | /GeeksForGeeks/SortingElementsOfAnArrayByFreq.py | 551 | 3.90625 | 4 | # Problem Description: https://practice.geeksforgeeks.org/problems/sorting-elements-of-an-array-by-frequency/
t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
freq = {}
for num in a:
if(num in freq):
freq[num] += 1
else:
freq[num] = 1
d = []
for key, val in freq.items():
d.append([key, val])
d.sort(key=lambda x: x[1], reverse=True)
for i in d:
for j in range(i[1]):
print(i[0], end=" ")
print()
|
bb5a0e5d76b420620364b1d0af30e437e63483c4 | xiashuo/tedu_execises | /month01/day13/homework1.py | 1,305 | 4.1875 | 4 | '''
内置可重写函数练习1
(1). 创建父子类,添加实例变量
创建父类:人(姓名,年龄)
创建子类:学生(成绩)
(2). 创建父子对象,直接打印.
格式: 我是xx,今年xx.
我是xx,今年xx,成绩是xx.
(3). 通过eval + __repr__拷贝对象,体会修改拷贝前的对象名称,不影响拷贝后的对象.
'''
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"我是{self.name},今年{self.age}."
def __repr__(self) -> str:
return f"Person('{self.name}',{self.age})"
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def __str__(self) -> str:
# return f"我是{self.name},今年{self.age},成绩是{self.grade}."
return super().__str__() + f",{self.grade}"
def __repr__(self) -> str:
return f"Student('{self.name}',{self.age},{self.grade})"
person1 = Person("大明", 35)
print(person1)
student1 = Student("小明", 10, 90)
print(student1)
person2 = eval(person1.__repr__())
person1.age = 37
print(person2.age)
student2 = eval(student1.__repr__())
student1.grade = 100
print(student2.grade)
|
e846de9341a0fbd85a5b91be1b81c4ab25b83951 | adubois85/python_projects | /head_first/chapter2/marvin.py | 170 | 4.25 | 4 |
# You can iterate over a list as-is (and other data structures?)
paranoid_android = 'Marvin'
letters = list(paranoid_android)
for char in letters:
print('\t', char)
|
e7db56e6891fdee536f1523b991ae00ee63eabfc | ManojKrishnaAK/python-codes | /FUNCTIONS/aop.py | 524 | 3.6875 | 4 | #aop.py
def operations():
x1=float(input("Enter First Value:"))
x2=float(input("Enter Second Value:"))
sum=x1+x2
sub=x1-x2
mul=x1*x2
div=x1/x2
fdiv=x1//x2
mod=x1%x2
print("sum of {0} and {1} = {2}".format(x1,x2,sum))
print("sub of {0} and {1} = {2}".format(x1,x2,sub))
print("mul of {0} and {1} = {2}".format(x1,x2,mul))
print("div of {0} and {1} = {2}".format(x1,x2,div))
print("floor div of {0} and {1}= {2}".format(x1,x2,fdiv))
print("mod of {0} and {1} = {2}".format(x1,x2,mod))
#main program
operations()
|
4466f1366b91499b6a1573b045b57aceb43d95ba | hurtnotbad/pythonStudy | /studyNotes/method/keywordTest.py | 768 | 4.0625 | 4 | import keyword
"""
关键字是python内置的、具有特殊意义的标识符,可通过print(keyword.kwlist) 查看所有关键字有如下:
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
关键字在使用时不需要括号,例:
a = ["a", "b", "c"]
del a[0]
就可以删除a列表中第一个元素
"""
def show_keyword_test(test):
"""
查看所有关键字
:param test:
:return:
"""
if not test:
return
print("keyword:")
print(keyword.kwlist)
show_keyword_test(True) |
5ea1421668175b183465d929afe2cf0352f02f6c | DanielSwags/erp | /interview 3.py | 609 | 3.921875 | 4 | def palindrome_chain_length(n):
num = str(n)
rev_num = ""
x = len(num) - 1
for i in range(x, -1, -1):
digit = num[i]
rev_num = rev_num + digit
return rev_num
def is_palindrome(n):
num = str(n)
rev_num = palindrome_chain_length(n)
return num == rev_num
numb = input("Please enter a number")
number = int(numb)
step = 0
limit = 5000
while (not is_palindrome(number) and step < limit):
step = step +1
rev_num = palindrome_chain_length(number)
print('step', step, ':',number, '+', rev_num, '=')
number = number + int(rev_num)
print(number)
|
fdb89e86595f0685d3223f782b0b11ca558225b1 | velicu92/python-basics | /03_Import&Export.py | 2,437 | 3.734375 | 4 |
### Data import without Pandas can be difficult
### You would need to use Excel before that, to format the tables.
### Only numbers can be imported. Dates should be transformed to specific formats
##############################################################################
### Import data using Pandas
##############################################################################
import pandas as pd
import os
print(os.getcwd())
### you should import each function from pandas
### importing csv file
from pandas import read_csv
data1 = read_csv('lunch.csv')
print(data1)
### importing Excel file. can do both xls and xlsx
from pandas import read_excel
data2 = read_excel('lunch.xlsx', 'Sheet1')
print(data2)
##############################################################################
### Some basic operations
##############################################################################
print(data2.year) ## print one variable
the_variable = data2.total_served
print(the_variable)
d = sum(data2.total_served)
print(d)
print('The sum of Sales for this lunch dataset is', d)
mimimum = min(the_variable)
maximum = max(the_variable)
print('The mimimum total served value is', mimimum, 'and the maximum is', maximum)
diff = the_variable - data2.avg_free
print(diff)
diff2 = data2.total_served - data2.avg_free
print(diff2)
### creating a new calculated column. just for testing (no economical sense)
data2['diff3'] = data2['total_served'] - data2['avg_free']
print(data2)
### creating an adjusted price (with the discount from perc_free_red)
data2['total_price'] = (data2['total_served']) - ((data2['perc_free_red'] /
100) * data2['total_served'])
print(data2)
### another way to add a column. Be carefull with the index. it would be a better
### idea to make these calculations inside the dataframe.
data3 = data2
data3['sum'] = diff
print(data3[['year','diff3','sum']])
print(data3)
### Please note: use 1 bracket '[' to specify 1 column and 2 brackets '[[' for
### multiple columns. The number of brackets it's not equal to number of fields
##############################################################################
################## Data export ################################
##############################################################################
data3.to_excel('04_import&export.xlsx')
|
094dfcbda3d43e09fb3c1b50660b9db2bb9cf29d | MinnowBoard-Projects/max-opencv-demos | /screens/mazegame/gameplay.py | 7,574 | 4.25 | 4 | from .include import *
import random
# The maze generation is an implementation of the unmodified randomized Prim's
# algorithm from http://en.wikipedia.org/wiki/Maze_generation_algorithm
class Maze:
def __init__ (self, w, h, seed = None):
self.w, self.h = w, h
self.area = w * h
self.scale_w = float (util.input.cfg_h) / (self.w + 2.0)
self.scale_h = float (util.input.cfg_h) / (self.h + 2.0)
self.wall_list = []
self.visited = set ()
self.passages = set ()
random.seed (seed)
self.randstate = random.getstate ()
self.generate ()
def wall_num_between_cells (self, cell1_num, cell2_num):
if cell2_num < cell1_num:
# cell 2 is either East or North of cell 1
return self.wall_num_between_cells (cell2_num, cell1_num)
ret = 2 * cell1_num
if cell2_num == cell1_num + 1 and cell2_num % self.w != 0:
return ret # cell 2 is cell 1's neighbor to the West
elif cell2_num == cell1_num + self.w:
return ret + 1 # cell 2 is cell 1's neighbor to the South
assert False
def add_wall (self, wall_num):
if wall_num not in self.wall_list:
assert wall_num not in self.passages
self.wall_list += [wall_num]
def add_wall_between_cells (self, cell1_num, cell2_num, from_wall):
wall_num = self.wall_num_between_cells (cell1_num, cell2_num)
if wall_num != from_wall:
self.add_wall (wall_num)
def visit_cell (self, cell_num, from_wall):
self.visited.add (cell_num)
if cell_num % self.w:
self.add_wall_between_cells (cell_num, cell_num - 1, from_wall)
if (cell_num + 1) % self.w:
self.add_wall_between_cells (cell_num, cell_num + 1, from_wall)
if cell_num >= self.w:
self.add_wall_between_cells (cell_num, cell_num - self.w, from_wall)
if cell_num + self.w < self.area:
self.add_wall_between_cells (cell_num, cell_num + self.w, from_wall)
def handle_wall (self, wall_list_num):
wall_num = self.wall_list [wall_list_num]
cell1_num = wall_num / 2
if wall_num % 2:
cell2_num = cell1_num + self.w
else:
cell2_num = cell1_num + 1
cell1_visited = cell1_num in self.visited
cell2_visited = cell2_num in self.visited
if cell2_visited:
cell1_visited, cell2_visited = cell2_visited, cell1_visited
cell1_num, cell2_num = cell2_num, cell1_num
assert cell1_visited # neither visited
if cell2_visited:
# both visited, make a passage between them
last_wall_num = self.wall_list.pop ()
if wall_list_num != len (self.wall_list):
self.wall_list[wall_list_num] = last_wall_num
else:
# one visited, time to visit the other one
self.passages.add (wall_num)
self.visit_cell (cell2_num, wall_num)
def repeatable_randrange (self, stop):
random.setstate (self.randstate)
ret = random.randrange (stop)
self.randstate = random.getstate ()
return ret
def generate (self):
self.visit_cell (self.repeatable_randrange (self.area), -1)
while len (self.wall_list):
self.handle_wall (self.repeatable_randrange (len (self.wall_list)))
self.generate_lines ()
def vertline (self, x, y1, y2):
x, y1, y2 = (x + 1) * self.scale_w, (y1 + 1) * self.scale_h, (y2 + 1) * self.scale_h
return numpy.array (((x, y1), (x, y2)))
def horizline (self, y, x1, x2):
y, x1, x2 = (y + 1) * self.scale_h, (x1 + 1) * self.scale_w, (x2 + 1) * self.scale_w
return numpy.array (((x1, y), (x2, y)))
def line_between_cells (self, cell1_num, cell2_num):
if cell2_num < cell1_num:
return self.line_between_cells (cell2_num, cell1_num)
row = cell1_num // self.w
col = cell1_num % self.w
if cell1_num + 1 == cell2_num:
return self.horizline (row + 0.5, col + 0.5, col + 1.5)
assert cell1_num + self.w == cell2_num
return self.vertline (col + 0.5, row + 0.5, row + 1.5)
def generate_lines (self):
def lines_for_cell (cell_num):
row = cell_num // self.w
col = cell_num % self.w
if row < self.h - 1 and 2 * cell_num + 1 not in self.passages:
yield self.horizline (row + 1, col, col + 1)
if 2 * cell_num not in self.passages:
yield self.vertline (col + 1, row, row + 1)
self.maze_lines = [
self.horizline (0, 1, self.w), # upper border
self.vertline (0, 0, self.h), # left border
self.horizline (self.h, 0, self.w - 1), # lower border
# Draw a small square indicating the goal point
self.horizline (self.h - 0.75, self.w - 0.75, self.w - 0.25),
self.horizline (self.h - 0.25, self.w - 0.75, self.w - 0.25),
self.vertline (self.w - 0.75, self.h - 0.75, self.h - 0.25),
self.vertline (self.w - 0.25, self.h - 0.75, self.h - 0.25),
]
for cell_num in xrange (self.area):
for line in lines_for_cell (cell_num):
self.maze_lines += [line]
# Check whether the maze is solved by the directions given
def trace (self, arrows):
self.trace_lines = [
# Draw a small square indicating the start point
self.horizline (0.25, 0.25, 0.75),
self.horizline (0.75, 0.25, 0.75),
self.vertline (0.25, 0.25, 0.75),
self.vertline (0.75, 0.25, 0.75)
]
lastcell = 0
for arrow in arrows:
if arrow.dir is arrow_left and lastcell % self.w:
nextcell = lastcell - 1
elif arrow.dir is arrow_right and (lastcell + 1) % self.w:
nextcell = lastcell + 1
elif arrow.dir is arrow_up and lastcell >= self.w:
nextcell = lastcell - self.w
elif arrow.dir is arrow_down and lastcell + self.w < self.area:
nextcell = lastcell + self.w
else:
continue
if self.wall_num_between_cells (lastcell, nextcell) in self.passages:
self.trace_lines += [self.line_between_cells (lastcell, nextcell)]
lastcell = nextcell
self.solved = lastcell + 1 == self.area
def visualize (self, ui):
visualization = util.ui.SizedCanvas (ui.game_display)
for line in self.maze_lines:
visualization.scaledLine (line[0], line[1], (0, 255, 0), 2, cv2.CV_AA)
for line in self.trace_lines:
visualization.scaledLine (line[0], line[1], (255, 0, 0), 2, cv2.CV_AA)
if self.solved:
visualization.scaledPutText ("MAZE SOLVED (\"New\" button to generate another)", numpy.array ((self.scale_w, self.scale_h * 0.5)), 0, util.input.scale_len * visualization.scale, (255, 255, 0))
|
69038065d926af82722cd28be4f5dddec59ee0a2 | Fantendo2001/FORKERD---University-Stuffs | /CSC1001/hw/hw_2/q3.py | 3,160 | 3.78125 | 4 | # !/bin/env python
# -*- coding:utf-8 -*-
import random
size = 139
fishes = 20
bears = 5
rounds = 100
class Ecosystem:
def __init__(self, size, fishes, bears):
creatures = fishes + bears
creatureLocs = random.sample(
range(size), creatures
)
fishLoc = random.sample(creatureLocs, fishes)
self.size = size
self.river = [None] * size
self.vacancy = []
for loc in range(size):
if loc in creatureLocs:
self.river[loc] = (
Fish() if loc in fishLoc else Bear()
)
else:
self.vacancy.append(loc)
def simulation(self, N):
for rd in range(1, N + 1):
# round started
print('round{}:'.format(rd))
spHere = None
for i in range(self.size):
nxt = self.river[i]
if spHere == nxt: # skip if next sp just moved
continue
spHere = nxt # otherwise sp takes movement
if spHere is not None:
if i == 0:
step = random.randint(0, 1)
elif i == self.size - 1:
step = random.randint(0, 1) - 1
else:
step = random.randint(0, 2) - 1
if step == 0: # next sp if step == 0
continue
there = i + step
spThere = self.river[there]
if spThere is None: # free to move to
self.river[i] = None
self.vacancy.append(i)
self.river[there] = spHere
self.vacancy.remove(there)
elif type(spHere) == type(spThere): # multiply
try:
someWhere = random.choice(self.vacancy)
except: # pass if no vacancy
pass
else: # otherwise multiply somewhere
self.river[someWhere] = spHere.multiply()
self.vacancy.remove(someWhere)
else: # different spp, hunting
self.river[i] = None
self.vacancy.append(i)
if (
type(spThere) is Fish
):
self.river[there] = spHere
# round completed
self.show()
def show(self):
for sp in self.river:
if sp is None:
print('N', end='')
else:
print(
'F' if type(sp) is Fish else 'B', end=''
)
print()
class Bear:
def __init__(self):
pass
def multiply(self):
return Bear()
class Fish:
def __init__(self):
pass
def multiply(self):
return Fish()
def main():
e = Ecosystem(size, fishes, bears)
e.simulation(rounds)
if __name__ == "__main__":
main()
|
4970125bab36291185457216732961f66556bbef | marti157/codewars | /2019/Problem2/Problem2.py | 95 | 3.703125 | 4 | num = input()
append = "s" if num != "1" else ""
print("{} lemonade jar{}".format(num, append)) |
56a4615b31b72d0babf238540c9dc18424962c5b | SophieGarden/cs_algorithm-structure | /15_3sum.py | 3,458 | 3.5625 | 4 | 15. 3Sum
Medium
5790
706
Add to List
Share
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
list_3sum = []
nums.sort()
d = {n:i for i, n in enumerate(nums)}
seen = set()
for i, m in enumerate(nums):
for j in range(i+1, len(nums)):
n = nums[j]
if -(m+n) in d and d[-(m+n)]>j:
seen.add((m, n, -(m+n)))
return list(seen)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
list_3sum = []
nums.sort()
d = {n:i for i, n in enumerate(nums)}
for i, m in enumerate(nums):
if i>0 and m==nums[i-1]:
continue
for j in range(i+1, len(nums)):
n = nums[j]
if j>i+1 and nums[j-1]==n:
continue
if -(m+n) in d and d[-(m+n)]>j:
list_3sum.append([m, n, -(m+n)])
# print(m, d2, list_3sum)
return list_3sum
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
list_3sum = []
nums.sort()
# d = {n:i for i, n in enumerate(nums)}
d = {}
for i, n in enumerate(nums):
d[n] = i
for i, m in enumerate(nums):
if i>0 and m==nums[i-1]:
continue
for j in range(i+1, len(nums)):
n = nums[j]
if j>i+1 and nums[j-1]==n:
continue
if -(m+n) in d and d[-(m+n)]>j:
list_3sum.append([m, n, -(m+n)])
# print(m, d2, list_3sum)
return list_3sum
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
seen = []
for i, n in enumerate(nums):
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i+1, len(nums)-1
while l < r:
if l > i+1 and nums[l] == nums[l-1]:
l += 1
continue
if r < len(nums)-1 and nums[r] == nums[r+1]:
r -= 1
continue
if nums[l] + nums[r] == - n:
seen.append([n, nums[l], nums[r]])
l += 1
r -= 1
elif nums[l] + nums[r] < - n:
l += 1
else:
r -= 1
return seen
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
seen = set()
for i, n in enumerate(nums):
l, r = i+1, len(nums)-1
while l < r:
if nums[l] + nums[r] == - n:
seen.add((n, nums[l], nums[r]))
l += 1
r -= 1
elif nums[l] + nums[r] < - n:
l += 1
else:
r -= 1
return seen
|
81fe1bcef0e0e908befa995d2a8e5509427dfb9b | SheetanshKumar/smart-interviews-problems | /Contest/B/Range of Primes.py | 614 | 3.703125 | 4 | '''
https://www.hackerrank.com/contests/smart-interviews-16b/challenges/si-range-of-primes
Given a range A to B, both inclusive, you have to find the number of prime numbers in the given range.
Input Format
First line of input contains T - number of test cases. Its followed by T lines, each line contains 2 numbers - A and B.
Constraints
30 points
1 <= T <= 1000
1 <= A <= B <= 104
70 points
1 <= T <= 106
1 <= A <= B <= 106
Output Format
For each test case, print the number of primes in the given range, separated by newline.
Sample Input 0
4
1 10
5 11
232 542
54 6421
Sample Output 0
4
3
50
819
''' |
e64006c4eabae45aa356d7a1a6767577908d085b | ApexMaister/Python-2k18 | /ejercicio-mayor.py | 301 | 4.09375 | 4 | #coding: utf8
numero1= input("Introduce numero1: ")
numero2= input("Introduce numero2: ")
if (numero1 == numero2 ):
print "Son iguales"
else:
if (numero1 > numero2):
print numero1 , "Es mes gran que" , numero2
else:
print numero2 , " Es mes gran que " , numero1
|
701ff2f4b3a116233b9c5fed85946f770fa5c1de | RIMPOFUNK/FirstLyceumCourse | /Lesson 32 (Введение в ООП)/Homework/2. Самые короткие и самые длинные слова.py | 603 | 3.53125 | 4 | class MinMaxWordFinder:
def __init__(self):
self.sentence = []
def shortest_words(self):
if not self.sentence:
return []
mmin = min([len(i) for i in self.sentence])
return sorted([i for i in self.sentence if len(i) <= mmin])
def longest_words(self):
if not self.sentence:
return []
mmax = max([len(i) for i in self.sentence])
return sorted(set([i for i in self.sentence if len(i) >= mmax]))
def add_sentence(self, val):
self.sentence += val.split() |
2b1f23bde2dba152fac95b4bd800240733a8acdf | pavstar619/HackerRank | /Python/Python Functionals/Map and Lambda Function.py | 250 | 4.03125 | 4 | cube = lambda x: x ** 3
def fibonacci(n):
List = [0, 1]
for i in range(2, n):
List.append(List[i-1] + List[i-2])
return(List[0:n])
if __name__ == '__main__':
n = int(raw_input())
print map(cube, fibonacci(n))
|
2ecdb840c85be34844476304d5235576dccf7beb | DonalMcGahon/Problems---Python | /Sorted list.Q8/SortedList.py | 497 | 4.125 | 4 | # Adapted from - https://stackoverflow.com/questions/29615274/user-input-integer-list
# Ask user to enter a list of numbers
list1 = input("Please enter a list of numbers separated by a single space only: ")
list1 = list1.split(' ')
# Ask user to enter a list of numbers
list2 = input("Please enter a list of numbers separated by a single space only: ")
list2 = list2.split(' ')
# .extend allows for the two lists to join together
list1.extend(list2)
# sorted sorts the list
print(sorted(list1)) |
6365dda38eafc54c8ebedf87c0ef921d6ca3a752 | Adomkay/python-object-oriented-cash-register-lab-nyc-career-ds-062518 | /shopping_cart.py | 2,536 | 3.609375 | 4 | class ShoppingCart:
def __init__(self, employee_discount = None):
self._total = 0
self._items = []
self._employee_discount = employee_discount
def mean_item_price_list(self):
price_list = []
for item in self._items:
price_list.append(item['price'])
return price_list
@property
def total(self):
return self._total
@total.setter
def total(self, total):
self._total = total
@property
def items(self):
return self._items
@items.setter
def items(self, items):
self._items = items
@property
def employee_discount(self):
return self._employee_discount
@employee_discount.setter
def employee_discount(self, employee_discount):
self._employee_discount = employee_discount
def add_item(self, name, price, quantity = 1):
self._total += price * quantity
num = 1
while num <= quantity:
self._item_dict = {'name': name, 'price': price}
self._items.append(self._item_dict)
num += 1
return self._total
def mean_item_price(self):
mean_item_price_list = self.mean_item_price_list()
mean_price = sum(mean_item_price_list)/len(mean_item_price_list)
return mean_price
def median_item_price(self):
price_list = self.mean_item_price_list()
median_price_list = sorted(price_list)
list_length = len(median_price_list)
if list_length % 2 != 0:
median_price = median_price_list[(list_length // 2 )]
return median_price
else:
lower_median = median_price_list[int((list_length//2) - 1)]
upper_median = median_price_list[int(list_length//2)]
median_price = (lower_median + upper_median) / 2
return median_price
def apply_discount(self):
discount = self._employee_discount
if discount == None:
return 'Sorry, there is no discount to apply to your cart :('
else:
return self._total * (1 - (discount/100))
def item_names(self):
item_list = []
for item in self._items:
item_list.append(item['name'])
return item_list
def void_last_item(self):
items = self._items
if items == []:
return 'There are no items in your cart!'
else:
popped_item = items.pop()
self._total -= popped_item['price']
return self._total
|
919198161bf8b4c66fbf8d67bd3da8aa0d07b890 | sw30637/assignment8 | /tl1759/distribution.py | 1,584 | 4.03125 | 4 | ####Liwen Tian
#####Assignment8
import pandas as pd
import numpy as np
from pandas import DataFrame as Df
import matplotlib.pyplot as plt
import math
import sys
def distributionpcincome():
"this function is to explore the per person distribution"
incomevalue = []
countries = pd.read_csv('countries.csv')
income = pd.read_excel('indicator gapminder gdp_per_capita_ppp.xlsx',header = False)
income.index = income[income.columns[0]]
transIncome = income.drop(income.columns[0],axis = 1)
transIncome = transIncome.T
i = 0
m = True
while m:
i += 1
try:
year = int(raw_input('Please choose a year between 1800 and 2012:'))
k = Df(transIncome.ix[year])
incomevalue = [ele for ele in k[year] if (math.isnan(ele) == False)]
plt.figure(i)
plt.subplot(111)
plt.hist((np.log10(incomevalue)),bins = 20)
plt.title(str(year) + ' Per person Income Distribution of the World')
plt.ylabel('Per Person Income \n'+'(log10)')
title = str(year) +" Income Distribution.pdf"
plt.savefig(title)
plt.show(block = False)
except ValueError:
print 'You have entered wrong type!'
except KeyError:
print 'Make sure the year is between 1800 and 2012!'
except KeyboardInterrupt:
print "You have touch the keyboard"
printstr = raw_input('Go on? (yes or no or finish)')
if printstr == "y" or printstr == 'yes'or printstr == 'Y' or printstr =='Yes':
continue
elif printstr == "n" or printstr =='no':
print "Quit the first step."
m = False
elif printstr == 'finish':
print "See the results in the folder."
m = False
return None |
93fb32ce0864da5e02aaf44c76ddf10942048ebe | Chandan-CV/school-lab-programs | /Program22.py | 619 | 4.21875 | 4 | #Program 22
#Write a program to create a tuple of Fibonacci series
#Name : Adeesh Devanand
#Date of Execution: September 16, 2020
#Class 11
n = int(input("Enter the length of the Fibonacci series"))
a = 0
b = 1
l = []
if n <= 0:
print("Invalid input")
elif n >= 1:
l.append(a)
if n >= 2:
l.append(b)
if n >= 3:
for i in range(0, n):
c = a + b
l.append(c)
a = b
b = c
print(l)
t = tuple(l)
print(t)
'''Output of Program22
Enter the length of the Fibonacci series4
[0, 1, 1, 2, 3, 5]
(0, 1, 1, 2, 3, 5)
'''
|
6c0b0d9147ed40187e586b74567caa1c7b3d5c8b | ejmaster/python-proj | /python-7.py | 1,956 | 4.15625 | 4 | """
Ask user for username and password
class customers
usernanmne, password, money
ask user withdraw or deposit money
modify the money
k = 203
if ( k == 203):
k += 123
k == 326
"""
class BankUser():
#This line tells the name and password.
def __init__(self):
self.username="Eric"
self.password="Bank"
#Template for setting the username and password.
def set_username(self, new_username):
self.username = new_username
def set_password(self, new_password):
self.password = new_password
#Sets username+password for Eric.
Eric=BankUser ()
Eric.set_username("Eric")
Eric.set_password("Bank")
#This line tells the name and passwordd.
class Money():
def __init__(self):
self.money=0
#Template for setting the money, lose money, or get money.
def set_money(self, new_money):
self.money += new_money
def set_losemoney(self, new_losemoney):
self.money -= new_losemoney
def get_money (self):
return self.money
#Sets self for money.
Eric=Money ()
#While above is true, loop the code.
while True:
#The username and password.
u= input ( "Username:\n")
p= input ( "Password:\n")
if (u=="Eric" and p=="Bank"):
#Verification code.
a= input ("Where do you live? For verification purpouses.\n")
if (a=="Earth"):
z= input ("Wrong answer.\n")
else:
print ("Wrong Answer")
if (z== "No it isnt"):
m=input ("What is your favorite word?\n")
else:
print ("Wrong answer")
if (m== "Word"):
d= input ("Deposit or Withdraw?\n")
else:
print ("Wrong answer")
d = ""
if (d=="Deposit"):
w= int(input ("How much?\n"))
Eric.set_money(w)
if (d=="Withdraw"):
t= int(input ("How much?\n"))
Eric.set_losemoney(t)
#Prints money amount.
print ("Money amount\n",Eric.get_money())
|
987b2bac969d7be2de4801ed8534b5b34921e84d | wan-catherine/Leetcode | /test/test_1775_equal_sum_arrays_with_minimum_number_of_operations.py | 531 | 3.5 | 4 | from unittest import TestCase
from problems.N1775_Equal_Sum_Arrays_With_Minimum_Number_Of_Operations import Solution
class TestSolution(TestCase):
def test_minOperations(self):
self.assertEqual(3, Solution().minOperations(nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]))
def test_minOperations_1(self):
self.assertEqual(-1, Solution().minOperations(nums1 = [1,1,1,1,1,1,1], nums2 = [6]))
def test_minOperations_2(self):
self.assertEqual(3, Solution().minOperations(nums1 = [6,6], nums2 = [1]))
|
c3d4009c9ddda5f3ea427d39213c278fc9790321 | Darnster/ManualAmend | /CryptProcess.py | 1,216 | 3.984375 | 4 | """
Module to encrypt/decrypt passwords to store in the config file
"""
from cryptography.fernet import Fernet
import sys
def encrypt(message: bytes, key: bytes) -> bytes:
return Fernet(key).encrypt(message)
def decrypt(token: bytes, key: bytes) -> bytes:
return Fernet(key).decrypt(token)
def generateKey():
key = Fernet.generate_key()
return key
if __name__ == "__main__":
pwd = sys.argv[1]
print("Password = %s" % pwd)
key = generateKey()
print("your key:\n%s" % key.decode() )
print("(Keep this in a safe place and pass it in to the Manual Amends script)\n")
enCryptedPWD = encrypt( pwd.encode(), key )
print("your encrypted password:\n%s" % enCryptedPWD.decode() )
print("(Store this in your config file as the pwd)\n" )
plain = decrypt( enCryptedPWD, key).decode()
print("Roundtrip testing - your decrypted password:\n%s" % plain)
print("Printed purely to re-assure you that it will decrypt as expected :-)")
"""
>>> key = Fernet.generate_key()
>>> print(key.decode())
itYUevR5OTOHVQG8KcI1_fPwnoYahH33X-RCxRa6mwU=
>>> message = 'John Doe'
>>> encrypt(message.encode(), key)
'gAAAAABciT3pFbbSihD_HZBZ8kqfAj94UhknamBuirZWKivWOukgKQ03qE2mcuvpuwCSuZ-X_Xkud0uWQLZ5e-aOwLC0Ccnepg=='
>>> token = _
>>> decrypt(token, key).decode()
'John Doe'
"""
|
5eeb0d2e63d72df91232b1ea19bee120a3fa69b2 | taoing/python_code | /4.0 gui/tkinter/calculate.py | 2,573 | 3.921875 | 4 | # -*- coding: utf-8 -*-
# 计算3场比赛的平均成绩
from tkinter import Tk, Frame, Label, Button, Menu, Entry, END
class Application(Frame):
'''创建框架模板'''
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
menubar = Menu(self)
filemenu = Menu(self)
filemenu.add_command(label='Calculate', command=self.calculate)
filemenu.add_command(label='Reset', command=self.clear)
menubar.add_cascade(label='File', menu=filemenu)
menubar.add_command(label='Quit', command=root.quit)
root.config(menu=menubar)
self.label1 = Label(self, text='The Bowling Calculator')
# columnspan: 跨3列
self.label1.grid(row=0, columnspan=3)
self.label2 = Label(self, text='Enter score from game 1:')
self.label3 = Label(self, text='Enter score from game 2:')
self.label4 = Label(self, text='Enter score from game 3:')
self.label5 = Label(self, text='Average:')
self.label2.grid(row=2, column=0)
self.label3.grid(row=3, column=0)
self.label4.grid(row=4, column=0)
self.label5.grid(row=5, column=0)
self.score1 = Entry(self)
self.score2 = Entry(self)
self.score3 = Entry(self)
self.average = Entry(self)
self.score1.grid(row=2, column=1)
self.score2.grid(row=3, column=1)
self.score3.grid(row=4, column=1)
self.average.grid(row=5, column=1)
self.button1 = Button(self, text='Calculate Average', command=self.calculate)
self.button1.grid(row=6, column=0)
self.button2 = Button(self, text='Clear result', command=self.clear)
self.button2.grid(row=6, column=1)
# 第一个输入框自动获取焦点
self.score1.focus_set()
def calculate(self):
'''计算平均值'''
num_score1 = int(self.score1.get())
num_score2 = int(self.score2.get())
num_score3 = int(self.score3.get())
average = (num_score1+num_score2+num_score3) / 3
self.average.insert(0, '{0:.2f}'.format(average))
def clear(self):
'''清空当前输入'''
self.score1.delete(0, END)
self.score2.delete(0, END)
self.score3.delete(0, END)
self.average.delete(0, END)
# 重新获取输入焦点
self.score1.focus_set()
root = Tk()
root.title('Bowling Average Calculator')
root.geometry('500x200')
app = Application(root)
app.mainloop()
|
1ec3dd47f082fc78d6343f149b7384005e37cb35 | raahool007/CoffeeMachine | /Topics/Loop control statements/The mean/main.py | 155 | 3.65625 | 4 | total = 0
counter = 0
while True:
bucket = input()
if bucket == '.':
break
total += int(bucket)
counter += 1
print(total / counter) |
285a9572d229fbed2436a23ea367b29849a365a5 | BhargavReddy461/Coding | /Binary Tree/replace_eachNode_with_sum_of_previousAndNextEle_in_Inorder.py | 1,531 | 3.9375 | 4 | class getNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(root, arr):
if not root:
return
inorder(root.left, arr)
arr.append(root.data)
inorder(root.right, arr)
def inordersum(root, arr, i):
if not root:
return
inordersum(root.left, arr, i)
root.data = arr[i-1]+arr[i+1]
i += 1
inordersum(root.right, arr, i)
def inordersumutil(root):
if not root:
return
arr = []
arr.append(0)
inorder(root, arr)
arr.append(0)
i = 1
inordersum(root, arr, i)
def preorderTraversal(root):
# if root is None
if (not root):
return
# first print the data of node
print(root.data, end=" ")
# then recur on left subtree
preorderTraversal(root.left)
# now recur on right subtree
preorderTraversal(root.right)
if __name__ == '__main__':
# binary tree formation
root = getNode(1) # 1
root.left = getNode(2) # / \
root.right = getNode(3) # 2 3
root.left.left = getNode(4) # / \ / \
root.left.right = getNode(5) # 4 5 6 7
root.right.left = getNode(6)
root.right.right = getNode(7)
print("Preorder Traversal before",
"tree modification:")
preorderTraversal(root)
inordersumutil(root)
print()
print("Preorder Traversal after",
"tree modification:")
preorderTraversal(root)
|
2feb3a433c6a39a1e74070e689b992d8979b61f0 | niepengfeiisgood/crn-lung-nodule | /src/crn_lung_nodule/nlp/base_sentence_splitter.py | 13,640 | 3.53125 | 4 | """
# <p>Title: Sentence Boundary program </p>
# <p>Create Date: 16:00:49 03/21/11</p>
# <p>Copyright: Copyright (c) Department of Biomedical Informatics </p>
# <p>Company: Vanderbilt University </p>
# @author Yonghui Wu
# @version 1.2
# <p>Description: This program is used to detect sentence boundary and format each sentence as a single line </p>
# Input: 1: English_dictionary 2: Abbreviation_dictionary 3: input_dir 4: output_dir
# Output: Each file in the file_list will be processed by this sentence boundary tool,
the out put will be generated in output directory with name: "file_name.sent"
Modified so that it will:
1. read input from database
2. parse sentences as parameters (a string/list) and return the result
3. this will require a class-like interface
"""
import re
import sqlite3
import pkg_resources
class BaseSentenceSplitter(object):
def __init__(self, ignorecase=True, config=None, debug=False):
"""
:param ignorecase: case insensitive (default=True)
:param config: dictionary which may contain the following keys
.. note::
prep -- list of prepositions
det -- list of determiners
conj -- list of conjunctions
non_stop_punct -- list of stop punctuation
sentence_word -- list of sentence words
knuthus -- list of knuthus words
abbrevs -- list of abbreviation words
:param debug: enable debug mode (default=False)
:return:
"""
self.prep = {'about', 'above', 'across', 'after', 'against', 'aka', 'along', 'and', 'anti', 'apart', 'around',
'as', 'astride', 'at', 'away', 'because', 'before', 'behind', 'below', 'beneath', 'beside',
'between', 'beyond', 'but', 'by', 'contra', 'down', 'due to', 'during', 'ex', 'except',
'excluding', 'following', 'for', 'from', 'given', 'in', 'including', 'inside', 'into', 'like',
'near', 'nearby', 'neath', 'of', 'off', 'on', 'onto', 'or', 'out', 'over', 'past', 'per', 'plus',
'since', 'so', 'than', 'though', 'through', 'til', 'to', 'toward', 'towards', 'under',
'underneath', 'versus', 'via', 'where', 'while', 'with', 'within', 'without', 'also'}
self.det = {'a', 'an', 'the'}
self.conj = {'and', 'or', 'but', 'if', 'nor', 'for', 'except', 'although', 'no'}
self.non_stop_punct = {}
self.sentence_word = {'we', 'us', 'patient', 'denies', 'reveals', 'no', 'none', 'he', 'she', 'his', 'her',
'they', 'them', 'is', 'was', 'who', 'when', 'where', 'which', 'are', 'be', 'have', 'had',
'has', 'this', 'will', 'that', 'the', 'to', 'in', 'with', 'for', 'an', 'and', 'but', 'or',
'as', 'at', 'of', 'have', 'it', 'that', 'by', 'from', 'on', 'include'}
if config and 'knuthus' in config and 'abbrevs' in config:
self.knuthus = {}
self.abbrevs = {}
else:
conn = sqlite3.connect(pkg_resources.resource_filename('crn_lung_nodule', 'data/ssplit.db'))
cur = conn.cursor()
cur.execute('SELECT abbr FROM abbreviations')
self.knuthus = {x[0] for x in cur.fetchall()}
cur.execute('SELECT word FROM knuthus')
self.abbrevs = {x[0] for x in cur.fetchall()}
for el in config or []:
setattr(self, el, self.load_set_lower(config[el]))
self.abbrevs -= self.knuthus # remove duplicates
self.ignorecase = ignorecase
self.debug = debug
def tokenize(self, text, debug=False):
# debug outputs print statements
debug_ = (debug or self.debug)
# sentences = []
text = self.prepare_text(text)
i = -1
while i + 1 < len(text):
i += 1
txt = text[i]
words = txt.split()
tmp = ''
for j, word in enumerate(words):
pos = self.has_dot(word)
if pos >= 0:
dot_num = self.num_dot(word)
if dot_num == 1:
if self.is_stop_punct(word): # single dot
tmp += word + '\n'
# '.' begining, do not change
elif pos == 0:
tmp += word + ' '
# end of word
elif pos == len(word) - 1:
if self.is_num_list(word):
if j == 0: # 1. Percocet 5/325 one p.o.
tmp += word + ' '
else: # postoperative day 3.
tmp += word[:-1] + ' .\n'
# afebrile .
elif (word[:-1].lower() not in self.abbrevs and
word.lower() not in self.abbrevs):
tmp += (word[:-1] + ' .\n')
else: # abbreviations
if j + 1 < len(words):
nword = words[j + 1]
else:
nword = ''
# elevation MI. The patient was
if (len(nword) > 0 and
self.isupper(nword[0], True) and
# 1.0 MM. C) LEFT BREAST, ...
# added by djc 30jul13
(nword.lower() in self.sentence_word or
(2 <= len(nword) <= 3 and
nword[0].isalpha() and
nword[-1] == ')'
)
)):
tmp += word + '\n'
else:
tmp += word + ' '
else:
lword, rword = word.split('.')
if (self.isupper(rword[0], True) and
(rword in self.sentence_word or
rword.lower() in self.knuthus)):
tmp += lword + '.\n' + rword + ' '
else:
tmp += word + ' '
else:
# "CK-MB of 9.1. His ..."
if word[-1] == '.':
if self.is_digit(word[:-1]):
tmp += word[:-1] + ' .\n'
else: # "without need for O.T. or P.T. He is"
if j + 1 < len(words):
nword = words[j + 1]
else:
nword = ''
if (len(nword) > 0 and
self.isupper(nword[0], True) and
nword.lower() in self.sentence_word):
tmp += word + '\n'
else:
tmp += word + ' '
else:
tmp += word + ' '
else: # normal word
tmp += word + ' '
# end for j, word
tmp = tmp.strip()
if i + 1 < len(text):
words = text[i + 1].split()
nword = words[0]
words = tmp.split()
eword = words[-1].lower()
# handle 'Page : '
if ((len(txt) > 6 and
txt[:6].lower() == 'page :') or
(len(text[i + 1]) > 6 and
text[i + 1].lower() == 'page :')):
text[i] = (tmp.strip() + '\n')
elif tmp[-1] == '.':
if (len(tmp) >= 2 and
tmp[-2] != ' ' and
not (nword == '-' or
self.is_num_list(nword) or
self.isupper(nword[0]))):
text[i] = (tmp.strip() + ' ')
else:
text[i] = (tmp.strip() + '\n')
elif text[i][-1] != '.' and txt[-1] != ':':
# ends in prep, conj, det, and non_stop_punct
if (eword in self.prep or eword in self.det or
eword in self.non_stop_punct or eword in self.conj):
text[i] = (tmp.strip() + ' ')
elif not (nword == '-' or
self.is_num_list(nword) or
self.isupper(nword[0])):
text[i] = (tmp.strip() + ' ')
else:
text[i] = (tmp.strip() + '\n')
else:
text[i] = (tmp.strip() + '\n')
else:
text[i] = tmp
# end for i, txt
if text:
text[-1] += '\n'
for item in text:
for sentence in item.split('\n'):
if sentence:
yield sentence
def isupper(self, word, default=False):
if self.ignorecase:
return default
return word.isupper()
def load_set_lower(self, lst):
"""
Load dictionary in to a set, convert into lowercase.
:param lst:
"""
sett = set()
for line in lst:
line = line[0].strip()
if len(line) > 0:
sett.add(line.lower())
return sett
def num_dot(self, word):
"""
return the number of dot in word
:param word:
"""
i = 0
for w in word:
if w == '.' or word[i] == '!' or word[i] == '?' or word[i] == ';':
i += 1
return i
def has_dot(self, word):
"""
Return the position of '.' in a word. -1 denote there are no '.' appeared
:param word:
"""
i = 0
lenn = len(word)
while i < lenn:
if word[i] == '.' or word[i] == '!' or word[i] == '?' or word[i] == ';':
return i
i += 1
return - 1
def remove_double_star(self, line):
"""
Some auto - inserted patterns in discharge summaries
:param line:
"""
pattern1 = r'\*\*NAME\[.{0,20}\]'
return re.sub(pattern1, '**NAME**', line)
def prepare_text(self, text):
"""
Read text in to list, remove the empty lines
Parameters:
text - string of text to be split
Return:
result - list of strings from text
:param text:
"""
result = []
for line in text.split('\n'):
line = line.strip()
if len(line) > 0:
line = self.remove_double_star(line)
line = self.clean(line)
line = self.seperate_puncts(line)
line = re.sub(r'[ ]+', ' ', line)
line = line.strip()
if len(line) > 0:
result.append(line)
return result
def seperate_puncts(self, line):
"""
seperate punctuations from words, except '.'
:param line:
"""
linee = ''
for w in line:
if self.is_punct(w):
if len(linee) > 0 and linee[-1] != ' ':
linee = linee + ' ' + w + ' '
else:
linee = linee + w + ' '
else:
linee = linee + w
return linee.strip()
def is_digit(self, word):
"""
Identify all numbers
:param word:
"""
if re.match(r'[+-]?\d*[.]?\d+$', word): # all number
return True
return False
def is_num_list(self, word):
"""
for list like: 1. 2.
:param word:
"""
if re.match(r'\d+\.$', word): # num list
return True
return False
def is_punct(self, w):
"""
indentify the punctuation
:param w:
"""
if w == ',' or w == '?' or w == '!' or w == '"' or w == ';' or w == ':':
# '.' and '+' used in ABBR
return True
else:
return False
def clean(self, sentence):
"""
Clean text: replace '[ ]+' into '[ ]'; remove '^[ ]+' and '[ ]+$'
:param sentence:
"""
sentence = re.sub(r'&', '&', sentence)
sentence = re.sub(r'>|>[ ];|<|<[ ];', ' ', sentence)
sentence = re.sub(r'\'s|\'S', ' \'s', sentence)
sentence = re.sub(r'[ ]+', ' ', sentence)
return sentence
def get_ave_len(self, text):
"""
get the average length of all the lines
:param text:
"""
lenn = len(text)
avel = 0
for line in text:
avel += len(line)
return avel / lenn
def is_stop_punct(self, w):
"""
These puncts are definitely a sentence boundary
:param w:
"""
if w == '?' or w == '!' or w == '.' or w == ';':
return True
else:
return False
|
7b6067622701b366b71be9343495f76051ed7e50 | ARSK-11/calculatorpy | /calculator01.py | 2,195 | 3.671875 | 4 | print(" ========= ========= ==== ")
print(" ===== == == ==== ")
print("== == == ==== culator python3")
print("== =========== ==== ")
print(" ===== == == ==========")
print(" ========= == == ==========")
print("-------calculator python-------")
print("calculator manual pakek python awokawok")
print("=======================================")
print("masukan salah satu options di bawah ini")
print("1.options (+)")
print("2.options (-)")
print("3.options (x)")
print("4.options (%)")
print("========================================")
option = int(input("masuk kan salah satu options tersebut: "))
if(option<3):
print("mongo masuk kan format")
else:
print("format tidak vailet")
if option==1:
print("===== silahkan masukan number =====")
y = int(input("masuk kan nominal number (y): "))
x = int(input("masuk kan nominal number (x): "))
sum = y + x
print("========================")
print("sucsess ")
print("+---------------+")
print("hasil:", sum,)
print("+---------------+")
if option==2:
print("===== silahkan masukan number ====")
y = int(input("masuk kan nominal number (y): "))
x = int(input("masuk kan nominal number (x): "))
sum = y - x
print("========================")
print("sucsess ")
print("+---------------+")
print("hasil:", sum,)
print("+---------------+")
if option==3:
print("=============== silahkan masukan number =================")
y = int(input("masuk kan nominal number (y): "))
x = int(input("masuk kan nominal number (x): "))
sum = y * x
print("========================")
print("sucsess ")
print("+---------------+")
print("hasil:", sum,)
print("+---------------+")
if option==4:
print("=============== silahkan masukan number =================")
y = int(input("masuk kan nominal number (y): "))
x = int(input("masuk kan nominal number (x): "))
sum = y / x
print("========================")
print("sucsess ")
print("+---------------+")
print("hasil:", sum,)
print("+---------------+") |
bd92c04905218e57a4f05db61e9299493797eaf2 | Txiaobin/thoughtwork | /python基础/第六节:如何操作文件/student_io.py | 521 | 3.625 | 4 | import csv
import json
def convert_file_format(input_file_path: str, output_file_path: str,
input_format: str = 'csv', output_format: str = 'json'):
csvfile = open(input_file_path,'r', encoding='utf-8')
jsonfile = open(output_file_path, 'w',encoding='utf-8')
fieldnames = ('name','age','gender','class','score')
reader = csv.DictReader( csvfile, fieldnames)
print(type(reader))
out = json.dumps( [ row for row in reader ] ,ensure_ascii=False)
jsonfile.write(out) |
fd0fc5cb9286653244ecb43b825cf9e3bcaabf2f | anmuer/pystudy | /tkinter/tk4.py | 3,192 | 3.890625 | 4 | # coding: UTF-8
from tkinter import *
# pack 布局
"""
root = Tk()
e = Entry(root)
e.pack(padx=10, pady=10)
e.delete(0, END)
e.insert(0, "default string...")
mainloop()
"""
# grid 布局
"""
root = Tk()
Label(root, text="作品:").grid(row=0, column=0)
Label(root, text="作者:").grid(row=1, column=0)
e1 = Entry(root)
e1.grid(row=0, column=1, padx=10, pady=5)
e2 = Entry(root)
e2.grid(row=1, column=1, padx=10, pady=5)
def show():
print("作品:《%s》" % e1.get())
print("作者:%s" % e2.get())
Button(root, text="获取信息", width=10, command=show)\
.grid(row=3, column=0, sticky=W, padx=10, pady=5)
Button(root, text="退出", width=10, command=root.quit)\
.grid(row=3, column=1, sticky=E, padx=10, pady=5)
mainloop()
"""
# 账号密码输入
"""
root = Tk()
Label(root, text="账号:").grid(row=0, column=0)
Label(root, text="密码:").grid(row=1, column=0)
user = StringVar()
pwd = StringVar()
# textvariable 可不用这个参数
e1 = Entry(root, textvariable=user)
e1.grid(row=0, column=1, padx=10, pady=5)
e2 = Entry(root, textvariable=pwd, show="*")
e2.grid(row=1, column=1, padx=10, pady=5)
def show():
print("账号:%s" % e1.get())
print("密码:%s" % e2.get())
Button(root, text="获取信息", width=10, command=show)\
.grid(row=3, column=0, sticky=W, padx=10, pady=5)
Button(root, text="退出", width=10, command=root.quit)\
.grid(row=3, column=1, sticky=E, padx=10, pady=5)
mainloop()
"""
# 失焦验证 focusout validatecommand
"""
root = Tk()
v = StringVar()
def test():
if e1.get() == "cc":
print("right!")
return True
else:
print("wrong!")
e1.delete(0, END)
return False
e1 = Entry(root, textvariable=v, validate="focusout", validatecommand=test)
e2 = Entry(root)
e1.pack(padx=10, pady=10)
e2.pack(padx=10, pady=10)
mainloop()
"""
# 验证参数
"""
root = Tk()
v = StringVar()
def test(content, reason, name):
if content == "cc":
print("Right!")
print(content, reason, name)
return True
else:
print("Wrong!")
return False
testCMD = root.register(test)
e1 = Entry(root, textvariable=v, validate="focusout", \
validatecommand=(testCMD,"%P","%v","%W"))
e2 = Entry(root)
e1.pack(padx=10,pady=10)
e2.pack(padx=10,pady=10)
mainloop()
"""
# 简易计算器
root = Tk()
frame = Frame(root)
frame.pack(padx=10,pady=10)
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
def test(content):
return content.isdigit()
testCMD = root.register(test)
e1 = Entry(frame, textvariable=v1, validate="key",\
validatecommand=(testCMD,"%P"))
e1.grid(row=0,column=0)
Label(frame, text="+").grid(row=0,column=1)
e2 = Entry(frame, textvariable=v2, validate="key",\
validatecommand=(testCMD,"%P"))
e2.grid(row=0,column=2)
Label(frame, text="=").grid(row=0,column=3)
e3 = Entry(frame, textvariable=v3, state="readonly")
e3.grid(row=0,column=4)
def cal():
result = int(e1.get())+int(e2.get())
v3.set(str(result))
Button(frame, text="计算", command=cal).grid(row=1,column=2,pady=5)
mainloop() |
98b62b32098fbc5b30ab91a4adcfa83381fd50a8 | shashank31mar/DSAlgo | /Algorithms_DS/isBST.py | 825 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 25 12:32:14 2018
@author: shagupta
"""
import math
class Node:
def __init__(self,data,left=None,right=None):
self.data = data
self.left = left
self.right = right
def isBST(root):
return isBSTUtil(root,-math.inf,math.inf)
#Finding using decreasing range
def isBSTUtil(root,mini,maxi):
if not root:
return True
if root.data < mini or root.data > maxi:
return False
return isBSTUtil(root.left,mini,root.data-1) and isBSTUtil(root.right,root.data+1,maxi)
def main():
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
print(isBST(root))
if __name__ == "__main__":
main() |
bcd0b4986878958286eae020c0852276d2df37a2 | hamza-yusuff/CP-algo | /new upper lower.py | 290 | 3.671875 | 4 | test=int(input())
for i in range(test):
string=input()
ucount=0
lcount=0
digit=0
for w in string:
if w.isupper()==True:
ucount=ucount+1
elif w.islower()==True:
lcount=lcount+1
elif w.isdigit()==True:
digit=digit+1
print('Case {}:'.format(i+1),min(ucount,lcount)+digit)
|
e1e41401194db9ec89b3e2e8cb9d2530f4a717d6 | mooja/dailyprogrammer | /challenge310easy.py | 736 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Daily Programmer Challenge 310 Easy
#
# https://www.reddit.com/r/dailyprogrammer/comments/64jesw/20170410_challenge_310_easy_kids_lotto/
#
# 14 April 2017
from random import shuffle
def randomized_lists(names, lotto_len):
for idx, name in enumerate(names):
rest = names[:idx] + names[idx+1:]
shuffle(rest)
lotto_list = '{name} -> {students}'.format(
name=name,
students='; '.join(rest[:lotto_len])
)
yield lotto_list
if __name__ == "__main__":
names = "Rebbeca Gann;Latosha Caraveo;Jim Bench;Carmelina Biles;Oda Wilhite;Arletha Eason"
lotto_len = 3
for lotto_list in randomized_lists(names.split(';'), lotto_len):
print(lotto_list)
|
b4e8f53921a146eb0cf98efe51508988ded6cb3e | sharkfinsid/LearnPython | /OOP2.py | 1,689 | 4.3125 | 4 | # Object Orientated Programming in Python Part 2
# Inheritance
class Pet: # Contains all the methods and attributes that all pet classes have
number_of_pets = 0 # Class variable (Not specific to any one instance)
def __init__(self, name, age):
self.name = name
self.age = age
Pet.add_pet()
def show(self):
print(f"I am {self.name} and am {self.age} years old")
def speak(self):
print("I don't know how to speak")
@classmethod
def add_pet(cls):
cls.number_of_pets += 1
@classmethod
def total(cls):
return cls.number_of_pets
class Cat(Pet): # Contains all the methods and attributes that are specific to Cats
def speak(self):
print("Meow")
class Dog(Pet): # Contains all the methods and attributes that are specific to Dogs
def speak(self):
print("Bork")
class Fish(Pet): # We want to add another attribute
def __init__(self, name, age, color):
super().__init__(name, age) # Go to inherited class, call init method and pass name and age args
self.color = color
def show(self):
print(f"I am {self.name}, {self.color} and am {self.age} years old")
# Using the classes
p1 = Pet("Tim", 10)
p1.show()
p1.speak()
c1 = Cat("Lucy", 13)
c1.show()
c1.speak()
d1 = Dog("Tom", 8)
d1.show()
d1.speak()
f1 = Fish("Noel", 2, "Blue")
f1.show()
f1.speak() # inherits the speak from the upper class because it has none
print(f" => Total pets are: {Pet.total()}")
# Note: Also discussed : Static methods in classes - methods that dont need an instance of the class to be executed (good for grouping similar methods into a package) |
6ee1b86d6c1e16457153bcd0b83ca0fb44286529 | PengfeiLv/LeetCode | /Level1/Sort/75. Sort Colors.py | 355 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/1/11 15:40
# @Author : Lvpengfei
# 荷兰国旗问题:快排思想
def sortColors(nums):
lo, hi = -1, len(nums)
i = 0
while i<hi:
if nums[i]<1:
nums[i], nums[lo+1] = nums[lo+1], nums[i]
lo += 1
i += 1
elif nums[i]>1:
nums[i], nums[hi-1] = nums[hi-1], nums[i]
hi -= 1
else:
i += 1
|
044d258b07f9e0241ce15c246cc2e8f2b9ab1849 | Olegs-Adventures/MyRandomCodingAdventures | /LambdaCalculator.py | 3,774 | 3.65625 | 4 | """
Needs more work. But at least I kinda understand how it is supposed to work.
"""
from tkinter import *
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_input.set(operator)
def btnClearOperations():
global operator
operator = ""
text_input.set("")
def btnEquals():
global operator
sumup = str(eval(operator))
operator = ""
text_input.set(sumup)
calculator = Tk()
calculator.title("Calculator")
operator = ""
text_input = StringVar()
txtDisplay = Entry(calculator, font=("arial", 20, "bold"), textvariable=text_input, bd=30, insertwidth=4,
bg="red", justify="right").grid(columnspan=4)
# =======================================================#
btn7 = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="7",
command=lambda: btnClick(7)).grid(row=1, column=0)
btn8 = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="8",
command=lambda: btnClick(8)).grid(row=1, column=1)
btn9 = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="9",
command=lambda: btnClick(9)).grid(row=1, column=2)
btnoperatorplus = Button(calculator, padx=14, pady=10, bd=8, fg="black", font=("arial", 20, "bold"), text="+",
command=lambda: btnClick("+")).grid(row=1, column=3)
# =======================================================#
btn4 = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="4",
command=lambda: btnClick(4)).grid(row=2, column=0)
btn5 = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="5",
command=lambda: btnClick(5)).grid(row=2, column=1)
btn6 = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="6",
command=lambda: btnClick(6)).grid(row=2, column=2)
btnoperatorminus = Button(calculator, padx=14, pady=10, bd=8, fg="black", font=("arial", 20, "bold"), text="-",
command=lambda: btnClick("-")).grid(row=2, column=3)
# =======================================================#
btn1 = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="1",
command=lambda: btnClick(1)).grid(row=3, column=0)
btn2 = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="2",
command=lambda: btnClick(2)).grid(row=3, column=1)
btn3 = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="3",
command=lambda: btnClick(3)).grid(row=3, column=2)
btnoperatortimes = Button(calculator, padx=14, pady=10, bd=8, fg="black", font=("arial", 20, "bold"), text="*",
command=lambda: btnClick("*")).grid(row=3, column=3)
# ======================================================#
btnoperatorzero = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="0",
command=lambda: btnClick(0)).grid(row=4, column=0)
btnoperatorclear = Button(calculator, padx=16, bd=8, fg="black", font=("arial", 20, "bold"), text="C",
command=btnClearOperations, ).grid(row=4, column=1)
btnoperatorequal = Button(calculator, padx=14, pady=6, bd=8, fg="black", font=("arial", 20, "bold"), text="=",
command=btnEquals).grid(row=4, column=2)
btnoperatorfraction = Button(calculator, padx=14, pady=10, bd=8, fg="black", font=("arial", 20, "bold"), text="/",
command=lambda: btnClick("/")).grid(row=4, column=3)
# ======================================================#
calculator.mainloop()
|
456d2f3127fc58c9f11b35303db6bb720fd62390 | jkvilladiego/FOR-THE-WOMEN | /exercise7.py | 716 | 4.09375 | 4 | # EXERCISE 7
# Challenge - Classes Exercise
# Add a method to the Car class called age
# that returns how old the car is (2019 - year)
# *Be sure to return the age, not print it
import datetime
class Cars:
def __init__(self, yearmade, make, model):
self.yearmade = yearmade
self.make = make
self.model = model
def age(self):
today = datetime.date.today()
age = today.year - self.yearmade.year
if today < datetime.date(today.year, self.yearmade.month, self.yearmade.day):
age -= 1
return age
vehicle = Cars(
datetime.date(2014, 3, 31),
"Toyota",
"Vios"
)
print(vehicle.make)
print(vehicle.model)
print(vehicle.age()) |
1ff76f92999b5ec98404d1a2cd519278702d35f7 | emdre/first-steps | /starting out with python/ch13t2 latin-english dict.py | 1,313 | 3.59375 | 4 | import tkinter
class DictionaryGUI:
def __init__(self):
self.main_window = tkinter.Tk()
self.word1_frame = tkinter.Frame(self.main_window)
self.word2_frame = tkinter.Frame(self.main_window)
self.word3_frame = tkinter.Frame(self.main_window)
self.word_button1 = tkinter.Button(self.word1_frame, text='sinister', command=self.show_translation1)
self.word_button2 = tkinter.Button(self.word2_frame, text='dexter', command=self.show_translation2)
self.word_button3 = tkinter.Button(self.word3_frame, text='medium', command=self.show_translation3)
self.word_button1.pack(side='left')
self.word_button2.pack(side='left')
self.word_button3.pack(side='left')
self.word1_frame.pack()
self.word2_frame.pack()
self.word3_frame.pack()
tkinter.mainloop()
def show_translation1(self):
self.label = tkinter.Label(self.word1_frame, text='lewy')
self.label.pack(side='left')
def show_translation2(self):
self.label = tkinter.Label(self.word2_frame, text='prawy')
self.label.pack(side='left')
def show_translation3(self):
self.label = tkinter.Label(self.word3_frame, text='środkowy')
self.label.pack(side='left')
dictionary = DictionaryGUI()
|
0ba98ef88fabe43e633796618b749c371879ab44 | hsuanwen0114/sharon8811437 | /HW5/BFS_06170226.py | 901 | 3.609375 | 4 |
# coding: utf-8
# In[18]:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, s):
s2 = []
queue = [s]
while queue:
s = queue.pop(0)
s2.append(s)
for child in self.graph[s]:
if child not in s2 and child not in queue:
queue.append(child)
return s2
def DFS(self, s):
s2 = []
stack = [s]
while stack:
s=stack.pop(-1)
s2.append(s)
for child in self.graph[s]:
if child not in s2 and child not in stack:
stack.append(child)
return s2
# In[24]:
# In[23]:
|
37e263b0ef2df549a385cfa723b2216c6bc55445 | MandeepKaurJS/The-Tech-Academy-Basic-Python-Projects | /mySimpleprograms in python/exx.py | 198 | 3.875 | 4 | from datetime import datetime
my_date = raw_input("Enter B'date in mmi/dd/yyyy format:")
b_date = datetime.strptime(my_date, '%m/%d/%Y')
print "Age : %d" % ((datetime.today() - b_date).days/365)
|
8c8f00deba08d1da622680855849b9f84707b2a5 | zmalpq/CodeWars | /moving zeros to the end.py | 403 | 4.0625 | 4 | #Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
#move_zeros([1, 0, 1, 2, 0, 1, 3]) # returns [1, 1, 2, 1, 3, 0, 0]
#solution
def move_zeros(array):
zeroLst = []
numLst = []
for i in array:
if int(i) == 0:
zeroLst.append(i)
else:
numLst.append(i)
return numLst + zeroLst
|
40c62a8d77fbc6c00bde1510cd8e45ad15b959fd | elliotjr/CSSE1001 | /Assignments/Assignment 1/assign1.py | 5,159 | 3.6875 | 4 |
###################################################################
#
# CSSE1001/7030 - Assignment 1
#
# Student Number: s4356917
#
# Student Name: Elliot Randall
#
###################################################################
#####################################
# Support given below - DO NOT CHANGE
#####################################
from assign1_support import *
#####################################
# End of support
#####################################
def load_data(dateStr):
"""
Takes a string representing a date in the correct format and returns a list
of data for each minute of the day in time order.
Precondition: The user enters a string that is in the valid date format
of dd-mm-yy.
load_data(str) -> list<tuple<string, float, float,tuple<multiple ints>>>
"""
data = get_data_for_date(dateStr)
elem = data.split("\n")
dlist = []
for i in elem:
split = i.split(',')
if len(i) == 0:
break #If there is nothing in the tuple, remove it.
time = split[0]
temp = float(split[1])
sunlight = float(split[2])
length = len(split)
measure = []#Power measurements for each array.
for n,s in enumerate(split):#Adds the power measurement to a tuple.
if n > 2:
measure.append(int(split[n]))
measure = tuple(measure)
dlist.append((time, temp, sunlight, measure))
return dlist
def max_temp(data):
"""
Retrieves the maximum daily temperature from load_data function and
returns a pair consisting of the maximum temperature and a list of times
at which the temperature was maximum.
From the data generated and formatted in the load_data function,
this function finds the maximum temperature recorded.
max_temp(list) -> tuple<float, list<str>>
"""
temp = -273#Absolute 0.
times = []
for t in data:
if t[1] > temp:
temp = t[1]
for t in data:
if t[1] == temp:
times.append(t[0])
maxrec = (temp, times)
return maxrec
def total_energy(data):
"""
Calculates the total energy produced from load_data function in
one day from all of the PV units in kWh.
total_energy(list) -> float
"""
energy = 0
for i in data:
energy = energy + sum(i[3])
return float(energy)/60000
def max_power(data):
"""
Takes data produced from load_data() function and returns the power produced
by each PV unit in kilowatts.
max_power(list) -> list<tuple<str, float>>
"""
maxes = [0] * len(ARRAYS)
parray = []
for row in data:
powers = row[3]
for i, power in enumerate(powers):
if power > maxes[i]:
maxes[i] = power
fmaxes = [x/float(1000) for x in maxes]#Divide values by 1000 in maxes
parray = list(zip(ARRAYS, fmaxes))#Create a list with tuples including ARRAYS and fmaxes
return parray
def display_stats(dateStr):
"""
Displays max temp, total enery and max power derived from load_data() function.
display_stats(str) -> None
"""
data = load_data(dateStr)
print ""
print "Statistics for",dateStr, "\n"
print "Maximum Temperature:", str(max_temp(data)[0]) + "C at times", ', '.join(max_temp(data)[1]), "\n"
print "Total Energy Production:",str(("{0:.1f}".format(round(total_energy(data),1))))+"kWh", "\n"
print "Maximum Power Outputs:","\n"
for i, n in max_power(data):
print STATS_ROW.format(i, n)
print ""
def interact():
"""
An interactive function that allows the user to view data by command in a text
based interface.
The user enters "date" and then a valid dateStr in the format of dd-mm-yy.
interact() -> None
"""
print "Welcome to PV calculator"
print "\n"
while True:
inputt = raw_input("Command: ")
isplit = inputt.split(" ")
if inputt == "q":
break
try:
kdate = isplit[0]
dateStr = isplit[1]
except IndexError:#Error if not enough input.
print "Unknown Command: "+inputt+'\n'
continue
try:
if len(isplit) > 2:
print "Unknown Command: " + inputt+'\n'
elif 'date' == kdate:
str(display_stats(dateStr))+"\n"
else:
print "Unknown Command: "+ inputt+'\n'
except ValueError:#Error if date is entered incorrectly.
print "Unknown Command:", inputt+'\n'
##################################################
# !!!!!! Do not change (or add to) the code below !!!!!
#
# This code will run the interact function if
# you use Run -> Run Module (F5)
# Because of this we have supplied a "stub" definition
# for interact above so that you won't get an undefined
# error when you are writing and testing your other functions.
# When you are ready please change the definition of interact above.
###################################################
if __name__ == '__main__':
interact()
|
61d6e9c89d71e0db32edd71c79c1a1a486f190e9 | Gaurav-Pande/DataStructures | /leetcode/arrays/sort_string_freq.py | 492 | 3.5 | 4 | # link:https://leetcode.com/problems/sort-characters-by-frequency/submissions/
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
counter = collections.Counter(s)
sorted_counter = sorted(counter.items(), key=lambda item: item[1], reverse = True)
dic = collections.OrderedDict(sorted_counter)
result=""
for k,v in dic.items():
result = result +v*k
return result |
465a969cf307179ca1892072a567be63f6503cb7 | deang2021/PythonTrainingCourse | /app23.py | 300 | 3.96875 | 4 | # Working with Return Statements
# Create a function to square times a number via a placeholder 'number' and return statement
def square(number):
return number * number
# Return a value by passing an argument of 5
print(square(5))
# NOTE: by default python functions returns NONE.
|
344cb9b60bb328ab382a82422e4ffcc149efdd7e | cubomx/BlackJack | /Game.py | 8,677 | 3.609375 | 4 | from random import randint
class Card:
def __init__(self, name, value):
self.__name = name
self.__value = value
self.__hidden = False
@property
def hidden(self):
return self.__hidden
@hidden.setter
def hidden(self, value):
self.__hidden = value
@property
def name(self):
if not self.hidden:
return self.__name
return '<hidden card>'
@name.setter
def name(self, name):
self.__name = name
@property
def value(self):
return self.__value
@value.setter
def value(self, value):
self.__value = value
class Score:
def __init__(self):
self.__hiddenScore = 0
self.__score = 0
@property
def score(self):
return self.__score
@score.setter
def score(self, points):
self.__score += points
@property
def hidden_score(self):
return self.__hiddenScore
@hidden_score.setter
def hidden_score(self, points):
self.__hiddenScore += points
class Player:
def __init__(self, name, mount):
self.__name = name
self.__hand = list()
self.__Score = Score()
self.__mount = mount
self.__bet = 0
@property
def bet(self):
return self.__bet
@bet.setter
def bet(self, bet):
self.__bet = bet
@property
def mount(self):
return self.__mount
@mount.setter
def mount(self, mount):
self.__mount = mount
@property
def Score(self):
return self.__Score
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
@property
def hand(self):
return self.__hand
@hand.setter
def hand(self, card):
self.__hand.append(card)
if isinstance(card, Card):
self.Score.hidden_score = card.value
if len(self.hand) > 1:
self.Score.score = card.value
else:
self.__hand = card
self.Score.hidden_score = -self.Score.hidden_score
self.Score.score = -self.Score.score
print("{0} {1}".format(self.Score.hidden_score, self.Score.score))
class User(Player):
def __init__(self, name, mount=10000):
super().__init__(name, mount)
self.__stand = False
def push(self):
print('mount: ' + (str)(self.mount))
push = self.mount + 1
if
while 0 > push >= self.mount:
push = int(input('How much do you want to push: '))
if push <= self.mount:
self.bet = push
@property
def stand(self):
return self.__stand
@stand.setter
def stand(self, value):
self.__stand = value
class GameManager:
def __init__(self):
self.__name = 'Manager'
self.winner = None
self.__hand = list()
self.__cards = list()
@property
def cards(self):
return self.__cards
@cards.setter
def cards(self, card_name):
if isinstance(card_name, list):
self.__cards = []
else:
self.__cards.append(card_name)
@property
def hand(self):
return self.__hand
@hand.setter
def hand(self, card):
if isinstance(card, list):
self.cards = list()
self.__hand = []
else:
self.hand.append(card)
def who_won(self, player, croupier):
self.winner = True
if croupier.Score.hidden_score < player.Score.hidden_score <= 21 or croupier.Score.hidden_score >21:
player.mount = player.mount + player.bet
return 'Player won'
else:
player.mount = player.mount - player.bet
return 'Crupier won'
''' Sees if the player/crupier has more than 21 points '''
def busts(self, player):
if player.Score.hidden_score > 21:
for card in player.hand:
if card.value == 11:''' Sees if the player/crupier has an Ace Card'''
card.value = 1
player.Score.hidden_score = -10 ''' If the ace card is 1, so remove 10 points'''
if not card.hidden:
player.Score.score = -10
if player.Score.hidden_score <= 21:
return False
print("Perdio {0}: {1}".format(player.name, player.Score.hidden_score))
return True
return False
def cleanHands(self, player, crupier):
self.hand = list()
player.hand = list()
player.stand = False
self.winner = False
crupier.hand = list()
class Crupier(Player):
def __init__(self, name, mount=100000000):
super().__init__(name, mount)
@staticmethod
def give_aleatory_card(cards, type):
rand_card = randint(0, len(cards) - 1)''' Two aleatory numbers for choosing some card from some kind '''
rand_type = randint(0, len(type) - 1)
if rand_card > 9:
value = 10
elif rand_card == 0:
value = 11
else:
value = rand_card+1
card = Card(str(cards[rand_card]) + " of " + type[rand_type], value)
return card
''' Checks if the card isn't in the game '''
def card_available(self, cards, type, game_manager, player):
card = self.give_aleatory_card(cards, type)
while card.name in game_manager.cards:
card = self.give_aleatory_card(cards, type)
player.hand = card
game_manager.hand = card
''' Gives the initial cards to both'''
def give_entry(self, player, cards, type, game_manager):
for i in range(0, 2):
self.card_available(cards, type, game_manager, player)
if isinstance(player, Crupier):
player.hand[0].hidden = True
''' Gives another card while the points of the crupier until it haves 17'''
def play_another(self, player, cards, type, game_manager):
while player.Score.hidden_score < 17:
self.card_available(cards, type, game_manager, self)
def ask_player(self, player, cards, type, game_manager):
choice = 'c'
while choice not in "ah":
choice = str(input('Do you want another(a) or want to stand(h)?')).lower()
if choice == 'a':
player.hand = self.give_aleatory_card(cards, type)
elif choice == 'h':
print("hola")
player.stand = True
game_manager.winner = False
''' Creating the array of all cards'''
def aleatory_card():
cards = ['Ace']
others = ["Jack", "Queen", "King"]
for i in range(2, 11):''' Creating the cards of numbers into the array'''
cards.append(i)
cards += others
return cards
''' Showing the user all cards in board '''
def show_cards(player):
for card in player.hand:
print(card.name)
print("\n")
def continuePlaying():
play = True
option = input("Do you want to continue playing: (y) (n)" + "\n ")
if option.lower() == "n":
play = False
return play
def main():
user = User(str(input('Enter your name: \n')))
crupier = Crupier('Crupier')
type = ["Clovers", "Pikes", "Diamonds", "Hearts"]
cards = aleatory_card()
game_manager = GameManager()
while True:
# Crupier gives the user his card/s
crupier.give_entry(user, cards, type, game_manager)
# Crupier gives himself cards
crupier.give_entry(crupier, cards, type, game_manager)
show_cards(user)
show_cards(crupier)
user.push()
while True:
crupier.ask_player(user, cards, type, game_manager)
if game_manager.busts(user):
print("Busts\n")
game_manager.winner = True
elif user.stand and game_manager.winner is not True:
while crupier.Score.hidden_score < 17:
crupier.play_another(crupier, cards, type, game_manager)
show_cards(user)
show_cards(crupier)
if game_manager.busts(crupier):
game_manager.winner = True
print("Crupier busts\n")
print(game_manager.who_won(user, crupier))
print("mount: " + str(user.mount))
if game_manager.winner:
break
show_cards(user)
show_cards(crupier)
if not continuePlaying():
break
else:
game_manager.cleanHands(user, crupier)
if __name__ == '__main__':
main()
|
e4163395699eb7a8018344bdd2dd25134f744754 | TGlove/AlgorithmLearning | /pyHundredTraining/1-10/T007.py | 137 | 3.5 | 4 | #-*- coding: UTF-8 -*-
# 将一个列表的数据复制到另一个列表中。
l = [1,2,3,4,5,6,7,8,9,11,15,17,19]
b = l[:]
print(b) |
c5722f5bbf81838e640a318850a0e01c6702ed3d | Veron-star/space-turtle-chomp | /game2.py | 618 | 3.8125 | 4 | #Turtle Graphic Game - Space Turtle Chomp
import turtle
#set up screen
turtle.setup(650,650)
wn = turtle.Screen()
wn.bgcolor('navy')
#create player turtle
player = turtle.Turtle()
player.color('darkorange')
player.shape('turtle')
player.penup()
player.speed(0)
#set speed variable
speed = 1
#define functions
def turn_left():
player.left(30)
def turn_right():
player.right(30)
def increase_speed():
global speed
speed += 1
#set keyboard binding
turtle.listen()
turtle.onkey(turn_left, 'Left')
turtle.onkey(turn_right, 'Right')
turtle.onkey(increase_speed, 'Up')
while True:
player.forward(speed) |
ac7b2f8cce4d033c78c796dc78f58bb746a98a40 | jul-star/Stepik_BasicUse | /03/UTest/tst_3_3_07.py | 1,163 | 3.515625 | 4 | import unittest
from ex_3_3_07 import *
class TestCase_3_3_07(unittest.TestCase):
def test_cat3_1(self):
_lines = ['cat',
'catapult and cat',
'catcat',
'concat',
'Cat',
'"cat"',
'!cat?', ]
_Actual = []
_Expected = ['cat',
'catapult and cat',
'"cat"',
'!cat?', ]
for ln in _lines:
if cat3(ln):
_Actual.append(ln)
self.assertListEqual(_Actual, _Expected)
def test_cat3_1(self):
_lines = ['cat',
'catapult and cat',
'catcat',
'concat',
'Cat',
'"cat"',
'!cat?', ]
_Actual = []
_Expected = ['cat',
'catapult and cat',
'"cat"',
'!cat?', ]
for ln in _lines:
if cat3(ln):
_Actual.append(ln)
self.assertListEqual(_Actual, _Expected)
if __name__ == '__main__':
unittest.main()
|
f35c43a18a823c7a45e8e94bc679ddd6862719b6 | nzh1992/Interview | /py_language/builtin_structure/p14.py | 563 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Author: niziheng
Created Date: 2021/6/4
Last Modified: 2021/6/4
Description:
"""
# 问题:
# 了解functools模块么?请介绍一下reduce的用法
# reduce函数将一个序列中,前一次调用的结果和sequence的下一个元素传递给function。
# recude函数共三个参数,function(自定义函数),sequence(序列),initial(初始值)
# initial默认值为0
from functools import reduce
if __name__ == '__main__':
l = [1,2,3,4]
total = reduce(lambda x, y: x+y, l, 0)
print(total)
|
38a849612401790b883113ee3af608b0e989ab8e | swilliams0520/hello_git | /quantify.py | 946 | 3.734375 | 4 | import re
import string
import sys
from collections import OrderedDict
STRIP_PUNCT = str()
for i in string.punctuation:
STRIP_PUNCT += "\\" + i + "|"
def quantify_words(text_file):
word_count = dict()
with open(text_file, "r") as f:
words = f.read().casefold()
clean = re.split(r' |\n', words)
for word in clean:
if word.isspace() or word == '':
continue
word = re.sub(STRIP_PUNCT, '', word)
word_count[word] = word_count.get(word, 0) + 1 #assigns new value to dictionary
word_count = OrderedDict(sorted(word_count.items(), key=lambda t: t[1])) #function that has no name, but is built in so python knows it
for k,v in list(reversed(word_count.items()))[:10]:
print(k,v)
if len(sys.argv) == 2:
text_file = sys.argv[1]
quantify_words(text_file)
else:
print("usage: quantify.py TEXT FILE")
|
3487a9828cf685fb41583a5d3f4ee2acaed4d77b | RRedwards/coursework | /05-Principles-Python/a5_WordWrangler.py | 4,003 | 3.9375 | 4 | """
Student code for Word Wrangler game
"""
import urllib2
import codeskulptor
import poc_wrangler_provided as provided
WORDFILE = "assets_scrabble_words3.txt"
# Functions to manipulate ordered word lists
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new sorted list with the same elements in list1, but
with no duplicates.
This function can be iterative.
"""
if len(list1) < 2:
return list1
cur_idx = 0
while cur_idx < len(list1) - 1:
if list1[cur_idx] == list1[cur_idx + 1]:
list1.pop(cur_idx + 1)
else:
cur_idx += 1
return list1
def intersect(list1, list2):
"""
Compute the intersection of two sorted lists.
Returns a new sorted list containing only elements that are in
both list1 and list2.
This function can be iterative.
"""
if (list1 == []) or (list2 == []):
return []
newlist = []
l1_idx = 0
l2_idx = 0
while (l1_idx < len(list1)) and (l2_idx < len(list2)):
l1_val = list1[l1_idx]
l2_val = list2[l2_idx]
if l1_val == l2_val:
newlist.append(l1_val)
l1_idx += 1
l2_idx += 1
elif l1_val < l2_val:
l1_idx += 1
else:
l2_idx += 1
return newlist
# Functions to perform merge sort
def merge(list1, list2):
"""
Merge two sorted lists.
Returns a new sorted list containing all of the elements that
are in both list1 and list2.
This function can be iterative.
"""
newlist = []
l1_copy = list(list1)
l2_copy = list(list2)
while (len(l1_copy) > 0) and (len(l2_copy) > 0):
if l1_copy[0] < l2_copy[0]:
newlist.append(l1_copy[0])
l1_copy.pop(0)
else:
newlist.append(l2_copy[0])
l2_copy.pop(0)
if len(l1_copy) > 0:
newlist = newlist + l1_copy
if len(l2_copy) > 0:
newlist = newlist + l2_copy
return newlist
def merge_sort(list1):
"""
Sort the elements of list1.
Return a new sorted list with the same elements as list1.
This function should be recursive.
"""
if len(list1) < 2:
return list1
else:
mid = len(list1) / 2
return merge(merge_sort(list1[:mid]), merge_sort(list1[mid:]))
# Function to generate all strings for the word wrangler game
def gen_all_strings(word):
"""
Generate all strings that can be composed from the letters in word
in any order.
Returns a list of all strings that can be formed from the letters
in word.
This function should be recursive.
"""
if word == "":
return [""]
else:
first = word[0]
rest = word[1:]
rest_strings = gen_all_strings(rest)
new_strings = []
for string in rest_strings:
for pos in range(len(string) + 1):
list_copy = list(string)
list_copy.insert(pos, first)
new_str = "".join(list_copy)
new_strings.append(new_str)
return new_strings + rest_strings
# Function to load words from a file
def load_words(filename):
"""
Load word list from the file named filename.
Returns a list of strings.
"""
str_list = []
url = codeskulptor.file2url(filename)
netfile = urllib2.urlopen(url)
for word in netfile.readlines():
str_list.append(word.strip())
return str_list
def run():
"""
Run game.
"""
words = load_words(WORDFILE)
wrangler = provided.WordWrangler(words, remove_duplicates,
intersect, merge_sort,
gen_all_strings)
provided.run_game(wrangler)
# see snippet of file to check it loads correctly:
#words = load_words(WORDFILE)
#for word in words[10000 : 10010]:
# print word
# Uncomment when you are ready to try the game
run()
|
946a45dc4c382ec460038628d7e1f265c5445ed2 | itsdj20/python_practise | /pyth/loop/l5.py | 138 | 3.734375 | 4 | list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
for num in list1:
if num<=150 and num%5==0 :
print(num)
|
8e92179c62e832a778302f80e404373bda220989 | s2t2/trumpmeter-py | /test/helper_text_test.py | 694 | 3.5 | 4 |
import string
from app.helper_text import main_clean, clean
def test_clean():
# it removes stopwords and punctuation, and lowercases the results:
assert clean("Hello world! is a message from me and us") == "hello world message us"
def test_main_clean():
# it converts text into a vector:
results = main_clean("Hello world")
assert results[0].tolist() == [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8363, 1774]]
assert results[1].tolist() == [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8320, 1782]]
def test_remove_punctuation():
cleaned = "Hello world!".translate(str.maketrans('', '', string.punctuation))
assert "!" not in cleaned
|
fd7866956b72194886c1a3ebdd1102186fce7fea | causztic/digital-world | /mini_projects/guiwithkivy/raspberry.py | 916 | 3.625 | 4 | import RPi.GPIO as GPIO
from time import sleep
from firebase import firebase
url = "https://rasbpi-9b253.firebaseio.com/"
token = "tlXOUKslj8JwDSc1ymJ1lbh8n2tkfUIZb5090xlC"
# Create a firebase object by specifying the URL of the database and its secret token.
# The firebase object has functions put and get, that allows user to put data onto
# the database and also retrieve data from the database.
firebase = firebase.FirebaseApplication(url, token)
GPIO.setmode(GPIO.BCM)
ledcolor={'yellow':23, 'red':24}
GPIO.setup(ledcolor.values(), GPIO.OUT)
while True:
redlight = firebase.get('/redlight')
yellowlight = firebase.get('/yellight')
if redlight == "on":
GPIO.output(ledcolor["red"], GPIO.HIGH)
else:
GPIO.output(ledcolor["red"], GPIO.LOW)
if yellowlight == "on":
GPIO.output(ledcolor["yellow"], GPIO.HIGH)
else:
GPIO.output(ledcolor["yellow"], GPIO.LOW)
sleep (3)
|
7f56c30efdd9f360e714f6997c936e5b429a48dc | deadpyxel/simple-roguelike | /map_objects/tile.py | 741 | 3.640625 | 4 | class Tile:
"""Generic Tile class.
A tile may or may not be blocked and may or may not block sight
"""
def __init__(self, blocked: bool, block_sight: bool = None):
"""Tile initializer.
Arguments:
blocked {bool} -- blocking status of tile
Keyword Arguments:
block_sight {bool} -- value determining sight status (default: {None})
"""
self.blocked = blocked
# By default, if a tile is blocked, it also blocks sight
if block_sight is None:
block_sight = blocked
self.block_sight = block_sight # flag if tile blocks sight of other tiles
self.explored = False # has the player been in this tile yet
|
48a23f9eef8297edd673e85c43d292f66b8547da | tanaymeh/nadl-new | /nadl/utils/other.py | 1,467 | 3.671875 | 4 | import numpy as np
from typing import List
class validateMatrixOp:
"""
Bunch of functions to validation matrix operations
"""
def matmulSizeCheck(tensor1: 'Tensor', tensor2: 'Tensor'):
"""Checks if given 2 tensors can be multiplied or not.
Args:
tensor1 (Tensor): First Tensor
tensor2 (Tensor): Second Tensor
"""
if tensor1.shape[1] != tensor2.shape[0]:
return False
else:
return True
def variableMatmulSizeCheck(*args):
"""
Checks if the given sequence of tensors are multiplications compatible
Given list of Tensors will be checked in accordance. Pass them in right order!
"""
# Loop through all tensors by making a window of 2 tensors (current, next)
# Check if the tensors in current window can be multiplied or not.
tensors = args
for _idx_current in range(len(tensors)):
# If we reach last element then return True result
if _idx_current == len(tensors) - 1:
return (True, None)
_idx_next = _idx_current + 1
_current_tensor, _next_tensor = tensors[_idx_current], tensors[_idx_next]
mml_check = validateMatrixOp.matmulSizeCheck(
_current_tensor,
_next_tensor
)
if not mml_check:
return (False, _idx_current) |
9a69d154177969910238e224d872edcd1f5db899 | JimWeisman/PRG105 | /3.4 nested ifs.py | 1,192 | 3.859375 | 4 | #jim weisman
# Spring 2019
# RPG 105
# project 3.4 nested ifs
package_selected = input("Which package did you purchase?: ")
minutes_used = 0
if package_selected == "A" or package_selected == "a" \
or package_selected == "B" or package_selected == "b" \
or package_selected == "C" or package_selected == "c":
minutes_used = int(input("How many minutes did you use this month?: "))
if package_selected == 'A' or package_selected == 'a':
package_cost = 39.99
if minutes_used > 450:
price = package_cost + ((minutes_used - 450) * .45)
print("You owe $" + format(price, ",.2f"))
if minutes_used < 450:
print (" you owe nothnig extra you used less then your monthly allowance")
elif package_selected == 'B' or package_selected == 'b':
package_cost = 59.99
if minutes_used > 900:
price = package_cost + ((minutes_used - 900) * .40)
print("You owe $" + format(price, ",.2f"))
if minutes_used < 900:
print (" you owe nothnig extra you used less then your monthly allowance")
elif package_selected == 'C' or package_selected == 'c':
print("You have unlimited minutes and owe nothing. Have a nice day ")
|
b2c85fb4f7df529d212495c3188e6d0110da4059 | ash/amazing_python3 | /tasks/t-009.py | 255 | 3.765625 | 4 | # Find all local maxima
data = [3, 6, 1, 2, 5, 4, 9, 5, 7, 2, 4]
# Scan data except edge elements:
print('List of found local maxima:')
for i in range(1, len(data) - 1):
if data[i-1] < data[i] > data[i+1]:
print(f'{data[i]} at position {i}')
|
04289a1cb1176ed59a7c3dbd4d4611082f6aa06c | awaisakram64/Statistic_operat | /operation.py | 1,178 | 3.5 | 4 | class Functions:
def Median(self,data):
ln=len(data) #length of data set
data=sorted(data)
if ln%2==0:
return (data[ln//2]+data[(ln//2)+1])/2
else:
return data[(ln//2)+1]
print('Hello')
def Mode(self,data):
dic={}
for i in set(data):
dic[i]=data.count(i)
x=dic[max(dic,key=dic.get)]
#print(x)
if x<=1:return [0]
else:return [key for key,val in dic.items() if val == x]
def Mean(self,data):
return sum(data)/len(data)
def Variance(self,data):
mean=self.Mean(data)
return sum([(i-mean)**2 for i in data])/len(data)
def StaDev(self,data):
return (self.Variance(data))**.5
def main():
func=Functions()
data=[float(i) for i in open("data.txt",'r')]
print('Median is %.2f'%(func.Mean(data)))
print('Mean is %.2f'%(func.Median(data)))
print('Mode is '+(', '.join(map(str,[i for i in func.Mode(data)]))))
print('Variance is %.2f'%(func.Variance(data)))
print('Standard Dev is %.2f'%(func.StaDev(data)))
if __name__ == "__main__":
main()
|
20a272df1d7776188ed3923b9bb496e134f531e3 | bwilson753/Workout-Updater | /workout.py | 2,735 | 3.609375 | 4 | #!/usr/bin/python
import sys
def modify(func, s):
input = open(sys.argv[1], 'r')
output = open(sys.argv[2], 'w')#creates a new text file
for x in input:
l = x.split(' ')
num = int(l[1])
r = func
result = r(num)
if((l[0] == 'walkLunge') | (l[0] == 'stepUp')):
if(result%2 != 0):
result = result + 1
if(l[0] not in s):
output.write('%s %s\n' % (l[0], result))
else:
output.write('%s %s\n' % (l[0], int(num * .5)))
print "You have a new workout written to " + sys.argv[2]
input.close()
output.close()
#put the arg list in a hash table
s = set()
for x in sys.argv:
s.add(x)
choice = True
while choice:
print '''
I increase intensity (except fails)
m maintain intensity (except fails)
r reduce intensity
i instructions
q quit'''
user = raw_input('Enter a command: ')
if(user == 'i'):
print '''In the command line arguments enter the incoming
workout, followed by the name of the file for your new
workout, followed by a list of the exercises from
your previous workout that you were unable to complete
the prescribed number of repetions.
For example,
user/file$./workout.py input.txt output.txt rfess cGPU
Then select how you wish to progress. This workout is
designed for athletes who have experience performing
the exercises but who have not performed calithensics for
a signifcant period of time. Progression is expected
to be moderate or aggressive. Inexperienced athletes or
athletes who are within a late stage training status
should seek a more approrpiate workout.
Athletes who are having difficulty increasing repetitions
should select 'm' (maintain training intensity). Athletes who are
experiencing overtraining symptoms such as soreness or
excessive fatigue should select 'r' (reduce training intensity).
Athletes who have waited more than a week since there
previous workout should also select 'r'.
Otherwise the athlete should select capital 'I'
to increase intesity.
This workout should be performed two to three days
per week on non-consecutive days with approximately
even rest periods in between each workout.'''
elif (len(sys.argv) < 3):
print 'You did not enter enough arguments.'
elif (user == 'I'):
f = lambda x: x + 1 if (x < 10) else x + int(x * .1)
modify(f, s)
choice = False
elif (user == 'm'):
f = lambda x: x
modify(f, s)
choice = False
elif (user == 'r'):
f = lambda x: x if (x == 0) else int(x * .5)
modify(f, s)
choice = False
elif (user == 'q'):
choice = False
else:
print 'Invalid Argument'
|
4fdac71e49e52a377c52a7f095199f0b94a243bd | zilongxuan001/benpython | /ex08.py | 1,590 | 3.9375 | 4 | #--coding: utf-8 --
#Date:20170815
#Title:ex08 打印,打印
#把 ’%r %r %r %r‘赋值给formatter.%r的意思是无论什么都打印出来,不限制格式。
formatter = '%r %r %r %r'
#打印1,2,3,4
print( formatter % (1, 2, 3, 4))
#打印‘one’,‘two’,‘three’,‘four’
print( formatter % ('one', 'two', 'three', 'four'))
#打印‘True’,‘False’,‘False’,‘True’
print( formatter % (True, False, False, True))
#打印四个’%r %r %r %r‘
print( formatter % (formatter, formatter, formatter, formatter))
#打印‘I had this thing.’‘That you could type up right’‘But it didn't sing’‘So I said goodnight.’
print( formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight.")
)
#add score
#引用网址:http://old.sebug.net/paper/books/LearnPythonTheHardWay/
#>自己检查结果,记录你犯过的错误,并且在下个练习中尽量不犯同样的错误。
#>注意最后一行程序中既有单引号又有双引号,你觉得它是如何工作的?
print('\n','add score 1','\n','------------------\n')
#加上注释
#add score
print('\n','add score 2','\n','------------------\n')
#错误
#1.拼写错误 fromatter——>formatter
#2.最后一个print,多个变量不加括号的错误,导致出现“参数不够”的提示。
#add score
print('\n','add score 3','\n','------------------\n')
# %r后的字符串,如果有字符串里有’,则打印时字符串两边出现"。如果字符串里没有‘,则字符串两边为’。 |
857ad96a247c692da0ff37bcd7ea7fa93711bd53 | ViacheslavBor/PythonOOP | /car.py | 845 | 3.828125 | 4 | class Car(object):
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if self.price > 10000:
self.tax = 0.15
else:
self.tax = 0.12
def display_all(self):
print "Price:", self.price
print "Speed:", self.speed
print "Fuel:", self.fuel
print "Mileage:", self.mileage
print "Tax:", self.tax
return self
car1 = Car(2000, "35mph", "Full", "15mpg")
car2 = Car(600, "43mph", "King of Full", "36mpg")
car3 = Car(2000, "35mph", "Empty", "15mpg")
car4 = Car(1000, "40mph", "Full", "30mpg")
car5 = Car(20000, "20mph", "Not Full", "15mpg")
car6 = Car(6000000, "300mph", "Full", "5mpg")
car1.display_all()
print('')
car2.display_all()
print('')
car3.display_all()
print('')
car4.display_all()
print('')
car5.display_all()
print('')
car6.display_all() |
e5ec7fdd82fb42fe59bf7955cfbf5f1c417c0cd2 | alejandromarroquin/functionsandalgorithmswithpython | /Diccionarios.py | 1,289 | 4.03125 | 4 | from os import system
system("cls")
my_dic={
'David':35,
'Fanny':22,
'Valeria':21,
'Iridian':23
}
print(my_dic)
print(my_dic['David'])
print('-----Acceder a un elemento si no sabemos si existe en el diccionario----')
print('El elemento no se encuentra en el diccionario')
print(my_dic.get('Juan',30))
print('El elemento si se encuentra en el diccionario')
print(my_dic.get('David',30))
print('--------Borrar un elemento del diccionario-----')
del my_dic['Iridian']
print(my_dic)
print('------Iterar sobre las llaves del diccionario--------')
for llave in my_dic.keys():
print(llave)
print('------Iterar sobre los valores del diccionario--------')
for valor in my_dic.values():
print(valor)
print('------Iterar sobre las llaves y valores del diccionario--------')
for item in my_dic.items():
print(item)
print('------Consultar si una llave se encuentr en el diccionario--------')
print('Fernanda' in my_dic)
print('Valeria' in my_dic)
print('*************Diccionarios Comprehension****************')
tiendita={
'Jitomate':20,
'Cebolla':12,
'Aguacate':40,
'Lechuga':8
}
double_prices=[price*2 for price in tiendita.values()]
print(double_prices)
print([price*2 for price in tiendita.values() if price*2<=50]) |
c8f3e1d85532c6069e65a8ae1d198b42bc4c7789 | jweissenberger/Google-Developers-Machine-Learning-Recipes | /Recipe#1/Machine Learning Recipes #1.py | 754 | 4.28125 | 4 | # This is a simple learning algorithm that predicts if an input item is an apple or an orange based on its weight and if
# it is considered bumpy or smooth
from sklearn import tree
# training set
features = [[140, 1], [130, 1], [150, 0], [170, 1]]
# the first feature is the weight of the fruit and in the second 1 represents smooth and 0 represents bumpy
labels = [0, 0, 1, 1]
# 0 represents apples and 1 represents
clf = tree.DecisionTreeClassifier() #creates a decision tree classifier based on the training set
clf = clf.fit(features, labels) #the training algorithm
print(clf.predict([[160, 0]])) #want to predict if an unknow fruit that weighs 160 and is bumpy
# this program returns a 1, meaning that it predicts the output |
dd4c78fbc51c608be9a1520aa0d16364172ea30a | gabiks318/mission-manager | /Try.py | 400 | 3.671875 | 4 | from tkinter import *
def printt():
print(square.get(1.0,END))
def main(root):
root.mainloop()
root=Tk()
root.title("Mission Control")
root.geometry("580x450")
app=Frame(root)
app.grid()
square=Text(app,width=15,height=1,wrap=WORD)
square.grid(row=0,column=0)
square.insert(0.0,'meeeeeir')
b= Button(app,text="print",command=printt)
b.grid(row=1,column=0,sticky='W')
main(root=root)
|
74d8457f41b3e69cea700c0b844ea7561dad2a50 | greenfox-velox/szemannp | /week-05/day-3/todo_app/todo.py | 2,908 | 3.546875 | 4 | import sys
class ToDo():
def sort_user_input(self):
if len(sys.argv) == 1:
self.get_usage_info()
if len(sys.argv) >= 2:
self.handle_user_input()
def handle_user_input(self):
if sys.argv[1] == '-l':
self.get_todo_list()
elif sys.argv[1] == '-a':
self.add_new_task()
elif sys.argv[1] == '-r':
self.remove_input_handler()
elif sys.argv[1] == '-c':
pass
print('# undone: set_task_completed()')
else:
raise ValueError('Unsupported argument, please try again.')
self.get_usage_info()
def get_usage_info(self):
file_menu = open('usage.txt')
list_menu = file_menu.read()
file_menu.close()
print(list_menu)
return
def get_todo_list(self):
try:
file_todo = open('todo_list.txt')
todo_list = file_todo.readlines()
print('\n')
if len(todo_list) > 0:
for line in range(len(todo_list)):
print(line + 1, ' - ', todo_list[line].rstrip())
else:
return 'There is nothing to do today!'
file_todo.close()
return ''
except FileNotFoundError:
touch_new_list()
def touch_new_list(self):
file_todo = open('todo_list.txt', 'a')
file_todo.close()
return
def add_new_task(self):
file_todo = open('todo_list.txt', 'a')
if len(sys.argv) > 2:
file_todo.write(sys.argv[2])
file_todo.close()
else:
print('Unable to add, no new task was given')
print('\nNew task successfully added')
print(self.get_todo_list())
return
def get_todo_file_length(self):
num_lines = sum(1 for line in open('todo_list.txt'))
self.num_lines = num_lines
return self.num_lines
def remove_input_handler(self):
line_index_to_remove = 0
num_lines = self.get_todo_file_length()
if len(sys.argv) > 2:
line_index_to_remove = int(sys.argv[2])
if line_index_to_remove <= num_lines:
self.remove_task()
else:
raise ValueError('Unable to remove: item index is out of range.')
else:
print('Unable to remove: index not present. Try again.')
return
def remove_task(self):
delete_line = int(sys.argv[2])
with open("todo_list.txt","r") as file_todo:
todo_list = list(file_todo)
del todo_list[delete_line - 1]
with open("todo_list.txt","w") as file_todo:
for n in todo_list:
file_todo.write(n)
print('\nTask successfully removed!')
print(self.get_todo_list())
return
workywork = ToDo()
workywork.sort_user_input()
|
e3e697b6aabe7e1bfe5f3ed3a45c785482c0f001 | heysushil/full-python-course-2020 | /2.7.operatores_excercise.py | 1,024 | 3.828125 | 4 | # 1. Arithmatic Op (Math ke sare signs):
a = 5
b = 15
print('\nAdd: ', a + b)
print('\nSUb: ', a - b)
print('\nMul: ', a * b)
print('\nDiv: ', b / a)
print('\nModules: ', a % b)
print('\nFloor: ', 50 // 5)
print('\nExponent: ', 10 ** 2)
# 2. Assigment Op (=):
a = 10
b = 20
# b = b + a
b += 5
print('\nB: ', b)
# 3. Comparison Op (< > ! ==):
a = 10
b = 20
print('\nEqual to: ', a == b)
print('\nNot equal to: ', a != b)
print('\nGreater then: ', a > b)
print('\nGreate then equal to: ', a >= b)
print('\nLess then: ', a < b)
print('\nLess then equlal to: ', a <= b)
# 4. Logical Op (and or not):
a = 10
b = 20
print('\nand: ', a < b and b < a)
print('\nor: ', a < b or b < a)
print('\nnot: ', not a)
# 5. Identity Op (is, is not):
print('\nChek a and b: ', a is b)
print('\nChek is not: ', a is not b)
# 6. Membership Op (in, not in):
mylist = [1,2,3,4]
print('\nChekc list: ', 3 in mylist)
print('\nUse not in: ', 4 not in mylist)
# 7. Bitwise Op (True/False):
a = 10
b = 20
print('\nBitwise &: ', a & b) |
50fed2831d0b0bde391b5e0726df18c91af7d7b7 | gitkenan/Data_Structures_and_Algorithms | /4.py | 444 | 4.1875 | 4 | # How do you find all pairs of an integer array whose sum is equal to a given number?
def pairs_which_sum_to(Arr, num):
pairs = []
for i in range(len(Arr)):
for j in range(len(Arr[i:])):
if Arr[i] + Arr[i + j] == num:
pairs.append([Arr[i], Arr[i + j]])
else:
pass
return pairs
Array = [1, 4, 8, 3, 6, 134, 13, 14, 26, 52, 11]
print(pairs_which_sum_to(Array, 27))
|
a34bff9000965069571596f7f68b91b0003cbec1 | akshays-repo/learn.py | /files.py/Artificial intelligence/opencv/intro/circle1.py | 322 | 3.5625 | 4 | import numpy as np
import cv2
# Create a black image
img = np.zeros((512,512,3))
# Draw a diagonal red line with thickness of 5 px and starting and ending point
img = cv2.circle(img,(447,347), 100, (123,0,255), -1) #center radius color thickness
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
108d340169c6a2110d2719a236fcd6d09025a1b6 | SinCatGit/leetcode | /00244/shortest_word_distance_ii.py | 1,111 | 4.0625 | 4 | from collections import defaultdict
from typing import List
class WordDistance:
def __init__(self, words: List[str]):
self.locations = defaultdict(list)
for i, word in enumerate(words):
self.locations[word].append(i)
def shortest(self, word1: str, word2: str):
"""
https://leetcode.com/problems/shortest-word-distance-ii/
https://leetcode.com/articles/shortest-word-distance-ii/
Design a class which receives a list of words in the constructor, and implements a method that takes two words
word1 and word2 and return the shortest distance between these two words in the list. Your method will be called
repeatedly many times with different parameters.
"""
idx1, idx2 = 0, 0
dis1, dis2 = self.locations[word1], self.locations[word2]
res = float('inf')
while idx1 < len(dis1) and idx2 < len(dis2):
res = min(res, abs(dis1[idx1]-dis2[idx2]))
if dis1[idx1] < dis2[idx2]:
idx1 += 1
else:
idx2 += 1
return res
|
290fe745710662a4185714de320d89c9de328864 | srekan/pyLearn | /77_multiplication_table_while.py | 120 | 3.765625 | 4 | # 77_multiplication_table_while.py
n = 2
i = 1
while(i <= 10):
print(f"{n} * {i} = {n*i}")
i += 1 # i = i + 1
|
15cf3da491f5980f53a84b2b04edcff5bbfc9e40 | RadkaValkova/SoftUni-Web-Developer | /Programming Basics Python/Exam problems/Suitcases Load.py | 521 | 3.921875 | 4 | trunk_volume = float(input())
counter = 0
sum_suitcase_volume = 0
while True:
line = input()
if line == 'End':
print('Congratulations! All suitcases are loaded!')
break
suitcase_volume = float(line)
sum_suitcase_volume += suitcase_volume
if trunk_volume <= sum_suitcase_volume:
print('No more space!')
break
else:
counter += 1
if counter % 3 == 0:
suitcase_volume = suitcase_volume * 1.1
print(f'Statistic: {counter} suitcases loaded.')
|
b431fe4854aa80757509d2c671db4f99b6d7dee7 | singyuKang/school | /lab4.py | 1,963 | 4.09375 | 4 | ##201614792 컴퓨터공학과 강신규
##이프로그램은 그림을 그리는 프로그램입니다
from turtle import *
def drawStar():
for i in range(0,5):
forward(150)
right(144)
def drawRectangle():
for i in range(0,4):
forward(150)
right(90)
def drawTriangle():
for i in range(0,3):
forward(150)
right(60)
def drawCircle():
circle(100)
def menu():
print("welcome to Draw\n\n")
print("\t s: draw a star")
print("\t r: draw a rectangle")
print("\t t:draw a triangle")
print("\t c:draw a circle")
print("\t u:utility")
print("\t q:quit")
choice = input("Your Choice:")##choice는 지역변수
return choice
def utilityMenu():
print("\t c:color")
print("\t p:pen size")
print("\t m:move pen location")
utilityChoice = input("Your choice:")
return utilityChoice
def penColor():
print("원하시는 색깔을 고르세요")
color = input("red or yellow")
return color
def penSize(x):
pensize(x)
def penLocation(x,y):
penup()
goto(x,y)
pendown()
def probMenu():
while True:
choice = menu() ##앞에 choice는 다른 변수로 해도상관없다
if choice == 'c':
drawCircle()
elif choice == 'r':
drawRectangle()
elif choice == 's':
drawStar()
elif choice == 't':
drawTriangle()
elif choice == 'u':
utilityMenu()
if utilityChoice == 'c':
penColor()
color(color)
elif utilityChoice == 'p':
penSize()
elif utilityChoice == 'm':
penlocation()
else:
break
else:
break
probMenu()
|
Subsets and Splits