blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
2411fd121ebe80d0983fe0230697879bf23248e2 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/7dfed2d8-675b-4e87-b28d-6a0ad1781636__square_roots.py | 3,149 | 3.9375 | 4 | #! usr/bin/env python
"""
http://programmingpraxis.com/contents/themes/
UNFINISHED
"""
THRESHOLD = 0.000001
def within_threshold(val):
return val <= THRESHOLD
def bisection(x):
lower_limit = 1
upper_limit = x
prev_midpoint = 0
midpoint = (upper_limit + lower_limit) / 2
candidate_square = midpoint ** 2
while not within_threshold(abs(candidate_square - x)) and \
not within_threshold(abs(prev_midpoint - midpoint)):
if candidate_square > x:
upper_limit = midpoint
else:
lower_limit = midpoint
prev_midpoint = midpoint
midpoint = ((upper_limit + lower_limit) / 2)
candidate_square = midpoint ** 2
return midpoint
def hero(x):
lower_limit = 1
upper_limit = x
prev_cand_root = 0
candidate_root = (upper_limit + lower_limit) / 2
candidate_square = candidate_root ** 2
while not within_threshold(abs(candidate_square - x)) and \
not within_threshold(abs(candidate_root - prev_cand_root)):
if candidate_square > x:
upper_limit = candidate_root
else:
lower_limit = candidate_root
prev_cand_root = candidate_root
candidate_root = (candidate_root + (x / candidate_root)) / 2
candidate_square = candidate_root ** 2
return candidate_root
def newtons_method(x):
candidate_root = ((x + 1) / 2)
candidate_square = candidate_root ** 2
prev_cand_root = 0
while not within_threshold(abs(candidate_root - x)) and \
not within_threshold(abs(candidate_root - prev_cand_root)):
prev_cand_root = candidate_root
candidate_root -= (candidate_root ** 2 - x) / (2 * x)
return candidate_root
def reduce_to_range(x):
"""
Reduces a number x to a number in the range [1, 2) by repeated division
or multiplication.
An iterable with two elements: the first one being the reduced number and
the next one being another iterable of True and False. The nth element of
this iterable is True if for the nth iteration of this function,
MULTIPLICATION was applied. Otherwise, it is False and DIVISION was applied.
"""
reduced_number = x
reduction_path = []
while reduced_number > 2 or reduced_number < 1:
if reduced_number > 2:
reduced_number /= 2
reduction_path.append(False)
elif reduced_number < 1:
reduced_number *= 2
reduction_path.append(True)
return (reduced_number, reduction_path)
def optimized_newtons(x):
reduction = reduce_to_range(x)
sqrt_2 = newtons_method(2)
sqrt_x = reduction[0]
for step in reduction[1]:
if step:
sqrt_x *= sqrt_2
else:
sqrt_x /= sqrt_2
return sqrt_x
if __name__ == "__main__":
tests = [4, 5, 16, 23, 40, 2, 167, 125348]
print("THRESHOLD: " + str(THRESHOLD))
print("==========BISECTION==========")
for test_case in tests:
print("sqrt(" + str(test_case) + ") = " + str(bisection(test_case)))
print("==========HERO'S==========")
for test_case in tests:
print("sqrt(" + str(test_case) + ") = " + str(hero(test_case)))
print("==========NEWTON'S==========")
for test_case in tests:
print("sqrt(" + str(test_case) + ") = " + str(newtons_method(test_case)))
print("==========OPTIMIZED==========")
for test_case in tests:
print("sqrt(" + str(test_case) + ") = " + str(optimized_newtons(test_case)))
|
6157a9d2ef53c3f6cc953c5bfad47fd1be6f246a | anujitm2007/Hackerrank-Codes | /Problem Solving/Lily'sHomework.py | 1,880 | 4.125 | 4 |
"""
Whenever George asks Lily to hang out, she's busy doing homework. George wants to help her finish it faster, but he's in over his head! Can you help George understand Lily's homework so she can hang out with him?
Consider an array of distinct integers, . George can swap any two elements of the array any number of times. An array is beautiful if the sum of among is minimal.
Given the array , determine and return the minimum number of swaps that should be performed in order to make the array beautiful.
For example, . One minimal array is . To get there, George performed the following swaps:
Swap Result
[7, 15, 12, 3]
3 7 [3, 15, 12, 7]
7 15 [3, 7, 12, 15]
It took swaps to make the array beautiful. This is minimal among the choice of beautiful arrays possible.
Function Description
Complete the lilysHomework function in the editor below. It should return an integer that represents the minimum number of swaps required.
lilysHomework has the following parameter(s):
arr: an integer array
Input Format
The first line contains a single integer, , the number of elements in . The second line contains space-separated integers .
Constraints
Output Format
Return the minimum number of swaps needed to make the array beautiful.
Sample Input
4
2 5 3 1
Sample Output
2
"""
try:
raw_input
except NameError:
raw_input = input
def solution(a):
m = {}
for i in range(len(a)):
m[a[i]] = i
sorted_a = sorted(a)
ret = 0
for i in range(len(a)):
if a[i] != sorted_a[i]:
ret +=1
ind_to_swap = m[ sorted_a[i] ]
m[ a[i] ] = m[ sorted_a[i]]
a[i],a[ind_to_swap] = sorted_a[i],a[i]
return ret
raw_input()
a = [int(i) for i in raw_input().split(' ')]
asc=solution(list(a))
desc=solution(list(reversed(a)))
print (min(asc,desc))
|
67ca84103c0080ef9badf212be95273908264d67 | yfl-fengzifei-se/DNN_Estimation | /dijkstra/dijkstra.py | 4,895 | 4.34375 | 4 | # -*- coding: utf-8 -*-
# %% define the dijkstra function
def dijkstra(graph_dict, start, end):
"""
This is a recursive function that implements Dijkstra's Shortest Path
algorithm.
It takes as its inputs:
i. a graph represented by a "dictionary of dictionaries" structure,
generated using networkx;
ii. a starting node in that graph; and
iii. an ending node for that graph
It then performs the following steps:
i. initialises a set of distances from the start node as infinity;
ii. initialises a set of 'predecessors' to None (a predecessor is
defined for each node in the network and it lists the prior node
in the path from start to end);
iii. initialises the set of of vertices for which the shortest path
from start to end has been found to empty; and then
iv. whilst there are still vertices left to assess:
a. restricts the set of vertices to those where that still need
analysisng;
b. finds the vertex that is the minimum distance from the start;
c. "relaxes" the neighbours of this closest vertex to see if the
shortest path to that vertex can be improved; and
d. updates the predecessor vertex for each node in the current path
When all vertices have been assessed, the function defines the path
and returns it with its associated cost
"""
distances = {} # empty dict for distances
predecessors = {} # list of vertices in path to current vertex
to_assess = graph_dict.keys() # get all the nodes in the graph that need to be assessed
# set all initial distances to infinity and no predecessor for any node
for node in graph_dict:
distances[node] = float('inf')
predecessors[node] = None
# set the intial collection of permanently labelled nodes to be empty
sp_set = []
# set the distance from the start node to be 0
distances[start] = 0
# as long as there are still nodes to assess:
while len(sp_set) < len(to_assess):
# chop out any nodes with a permament label
still_in = { node: distances[node] for node in [node for node in to_assess if node not in sp_set] }
# find the closest node to the current node
closest = min(still_in, key = distances.get)
# and add it to the set of permanently labelled nodes
sp_set.append(closest)
# then for all the neighbours of the closest node (that was just added)
# to the permanent set
for node in graph_dict[closest]:
# if a shorter path to that node can be found
if distances[node] > distances[closest] + graph[closest][node]['weight']:
# update the distance with that shorter distance; and
distances[node] = distances[closest] + graph[closest][node]['weight']
# set the predecessor for that node
predecessors[node] = closest
# once the loop is complete the final path needs to be calculated - this can
# be done by backtracing through the predecessors set
path = [end]
while start not in path:
path.append(predecessors[path[-1]])
# return the path in order start -> end, and it's cost
#return path[::-1], distances[end]
return distances[end]
# %%
# function to get _all_ dijkstra shortest paths
def dijkstra_all(graph_dict):
ans = []
for start in graph_dict.keys():
for end in graph_dict.keys():
ans.append(dijkstra(graph_dict, start, end))
return ans
#%% read in data - use a pandas dataframe just for convenience
import pandas as pd
data = pd.read_table("~/Desktop/Project/data/melbourne_graph.txt",
sep = " ",
header = None,
names = ['vx', 'vy', 'weight'])
# %% use network x to prepare dictionary structure which can be fed in to the
# dijkstra function
import networkx as nx
graph = nx.from_pandas_edgelist(data, 'vx', 'vy', 'weight')
# graph_nodes = graph.nodes()
graph_dict = nx.to_dict_of_dicts(graph)
G = nx.Graph(graph_dict)
# %% run the functions
print graph_dict
#all_paths = dijkstra_all(graph_dict)
result = []
#length = dict(nx.all_pairs_dijkstra_path_length(G))
length = nx.single_source_dijkstra_path_length(G, 0)
print "start compute length"
with open('distance.txt','w') as f:
for i in graph_dict.keys():
length = nx.single_source_dijkstra_path_length(G, i)
for j in graph_dict.keys():
f.write(str(i)+" "+str(j)+" "+str(length[j]))
|
be6e38b09105770faac3dbb38f96918314442395 | Osama-Yousef/data-structures-and-algorithms-2 | /sorts/insertion_sort/insertion_sort.py | 524 | 3.984375 | 4 |
def insertion_sort(ints):
'''
Traverse from 1 to len(ints)
J starts one spot behind i (i-1)
While j >=0 and the value at i
is less than the value at j,
the value at j+1 gets reassigned to the
value at j, and j+1 becomes the value at i
'''
for i in range(1, len(ints)):
temp = ints[i]
j = i-1
while j >= 0 and temp < ints[j]:
ints[j + 1] = ints[j]
j -=1
ints[j + 1] = temp
return ints
if __name__ == "__main__":
a = [5, 2, 32, 4, 17, 1, 7]
print(insertion_sort(a))
|
287389c369b79af4938e186668eed4d86ff05ec0 | JMRBDev/1DAW | /Programacion/Workspace Folder - Jose Rosendo/Ejercicios de clase/Ejercicios 2.0 (II) - Bucles/2.10_50_primeros_nums.py | 278 | 3.5625 | 4 | # Muestra los 50 primeros números pares a partir del 0, separados por comas y en orden creciente.
nList = []
for i in range(0,50,2):
nList.append(i)
print(*nList, sep=", ") # El asterisco (*) desempaqueta la lista y devuelve todos sus elementos sin los corchetes. |
ea240e32fc5693239aedb9e73913fa2b8e1a7158 | wangredfei/nt_py | /Base/ex06/zy3_list.py | 886 | 3.9375 | 4 |
# 3. 有一些数字存于列表中,如: L = [1, 3, 2, 1, 6, 4, 2, .....98, 82]
# - 将列表中出现的数字存入到另一个列表l2中
# - 要求 : 重复出现多次的数字只能在L2中保留一份(去重)
# - 将列表中出现两次的数字存于L3列表中,在L3列表中只保留一份
l = [1,2,2,3,3,3,4,4,5,5,5,6,6,6,6,6,8,9]
# 定义三个空的列表
l1 = []
l2 = []
l3 = []
for i in l :
count_nub = l.count(i)# 计算本次循环的数有几个
if i not in l1: # 去重放入l1
l1.append(i)
elif count_nub == 2 : # 有两个的放入l2
l2.append(i)
elif count_nub > 2:# 打印有多个的元素分别是哪个
if i not in l3:# 去重要多用in \ not in
print(i,"有",count_nub,"次")
l3.append(i)
print(l1)
print(l2)
print(l3)
# 总结一下.想要去除重复,要想到 in \ not in |
874c314b4b7a612dabbe7c8e79d16c3f7ce6d573 | kujin521/pythonObject | /第五章/列表/基本方法.py | 407 | 3.796875 | 4 | # 创建列表
list1=list()
list2=[]
# 添加元素
list1.append('第一个元素')# 添加到末尾
list2.insert(1,'inset')# 添加到指定位置
list1.extend(list2)# 添加列表
list1.append("再添加一个")
list1.append("再添加二个")
list1.append("再添加个")
# 修改列表
list1[0]='修改元素'
# 删除元素
del list1[1]
list1.pop(1)
list1.remove("再添加二个")
print(list1,list2) |
d22039d8ae2a018b85a1ed3bec9110308c746c63 | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/053 Sort vs Sorted/01 sort vs sorted.py | 1,617 | 4.25 | 4 | # sort -метод только списков сразу изменит его
# sorted - встроенная функция можно передавать любую последовательность и она изначально не меняется чтобы изменить нужно сделать присвоение
a =[3,-2,-5,-7,4,15,11] # sort применить можем только к списку
a1=[2,5,1,6]
b ='hello world'
c =('hi','zero','abrakadabra') # Если тут будет число (любое 56 то числа со строками сравнить нельзя
a.sort() # Метод sort изменяет изначальный списокприменить можем только к списку
print(a) # [-7, -5, -2, 3, 4, 11, 15]
# Теперь рассмотрим sorted ( ВСЕГДА ВОЗВРАЩАЕТ СПИСОК )
print(sorted(a1)) # Напоминаю что значальный список не меняется !!!!!!! если хотим изменить тогда импользуем присвоение
print(a1)
print('*************')
a1 =sorted(a1) # Если хотим изменить то важно присвоение
print(a1)
b=sorted(b) # Все символы отсортируются в алфавитном порядке
c=sorted(c)
print(b)
print(c)
#******************************************
# sort и sorted как они сортируют
print()
c=sorted(c ,reverse=False) # По алфавиту False
print(c)
c=sorted(c ,reverse=True) # Если True то в обратном порядке
print(c)
|
c6b5160b3fe36eedc5b08e5e0f9ba7ea5c48fd44 | colin-broderick/genetic_algorithm | /genetic.py | 2,721 | 3.921875 | 4 | import random
import matplotlib.pyplot as plt
def error(candidate, dataX, dataY):
"""
This function computes the sum of vertical square distances of a data set from a line.
param: candidate: Dictionary containing gradient "m" and y-intercept "c", defining a line.
return: The sum of vertical square distances between data and line.
"""
err = 0
for x, y in zip(dataX, dataY):
y_ = candidate["m"] * x + candidate["c"]
err = err + (y-y_)**2
return err
## Set the random seed to allow repeatable random number generation.
random.seed(15)
## Choose m and c, and generate (x, y) pairs at random.
m = 0.25
c = 3
X = [random.random()*10 for _ in range(20)]
Y = [m * x + c + (random.random()-0.5)*0.2 for x in X]
## Plot the data points.
plt.scatter(X, Y, label="Data")
## Randomly generate the first generation of candidate solutions.
candidates = [{
"m": (random.random() - 0.5) * 10,
"c": (random.random() - 0.5) * 10
} for _ in range(100)]
## Compute the error for each candidate.
for candidate in candidates:
candidate["error"] = error(candidate, X, Y)
## Sort the candidates from best to worst, and display the attributes of the best.
candidates.sort(key=lambda x: x["error"])
print(
"m:", round(candidates[0]["m"], 2),
"c:", round(candidates[0]["c"], 2),
"e:", round(candidates[0]["error"], 2)
)
## Draw the best candidate line from the first generation.
plt.plot([0, 10], [candidates[0]['c'], 10*candidates[0]['m']+candidates[0]['c']], label="First candidate solution")
## Iteratively improve the solution.
for index in range(50):
## Keep the best 25% of candidates and throw away the rest.
candidates = candidates[:25]
## Generate new candidates by randomly perturbing those we kept from the previous generation.
for i in range(25):
for _ in range(3):
new_candidate = {
"m": candidates[i]["m"] + (random.random()-0.5)*10/100,
"c": candidates[i]["c"] + (random.random()-0.5)*10/100
}
candidates.append(new_candidate)
## Compute the error for each candidate.
for candidate in candidates:
candidate["error"] = error(candidate, X, Y)
## Sort the candidates from best to worst, and display the attributes of the best.
candidates.sort(key=lambda x: x["error"])
print(
"m:", round(candidates[0]["m"], 2),
"c:", round(candidates[0]["c"], 2),
"e:", round(candidates[0]["error"], 2)
)
## Draw the best candidate line from the final generation.
plt.plot([0, 10], [candidates[0]['c'], 10*candidates[0]['m']+candidates[0]['c']], label="Final solution")
## Display the plot.
plt.legend()
plt.show()
|
2bc0589b8ed735770da056ed9ed7f71069a49351 | mkukar/Covid19SanDiegoUpdater | /data_analyzer.py | 3,525 | 3.515625 | 4 | # analyzes the latest data for trends and patterns
# Copyright Michael Kukar 2020. MIT License.
import sqlite3
import statistics
class DataAnalyzer:
LATEST_ENTRY_QUERY = "SELECT DATE, TOTAL_CASES, NEW_CASES, NEW_TESTS, HOSPITALIZATIONS, INTENSIVE_CARE, DEATHS from DATA ORDER BY strftime('%Y-%m-%d', DATE) DESC"
MAX_NEW_CASES_ENTRY_QUERY = "SELECT DATE, TOTAL_CASES, MAX(NEW_CASES), NEW_TESTS, HOSPITALIZATIONS, INTENSIVE_CARE, DEATHS from DATA"
def __init__(self, dbFilename):
self.dbFilename = dbFilename
# checks if latest entry has the maximum new cases of entire db
# return : true if latest is max, false otherwise
def checkIfLatestIsMaxNewCases(self):
# connects to database
conn = sqlite3.connect(self.dbFilename)
c = conn.cursor()
c.execute(self.LATEST_ENTRY_QUERY)
latestEntryData = c.fetchone()
c.execute(self.MAX_NEW_CASES_ENTRY_QUERY)
maxEntryData = c.fetchone()
conn.close()
# first index is DATE, if dates equal then max == latestentry
if latestEntryData[0] == maxEntryData[0]:
return True
else:
return False
# trends the new cases difference between X number of latest days in the database
# NOTE - If one of the days new_cases entry is None, will ignore it but not load another day
# days : (optional) number of days to trend
# return : float of trend between days
def getNewCasesTrend(self, days=3):
# with only 1 or less entries, cannot get trend (difference)
if days < 2:
return 0
# essentially a linear interpolation
newCasesEachDay = []
# connects to database
conn = sqlite3.connect(self.dbFilename)
c = conn.cursor()
c.execute(self.LATEST_ENTRY_QUERY)
latestEntries = c.fetchmany(days)
for entry in latestEntries:
# NEW_CASES is in location 2, skips any None entries
if entry[2] is not None:
newCasesEachDay.append(int(entry[2]))
conn.close()
# gets difference between each day, and then averages them
diffBetweenEachDay = []
# too many None cases, so we don't have enough data
if len(newCasesEachDay) < 2:
return 0
for i in range(len(newCasesEachDay)-1):
diffBetweenEachDay.append(newCasesEachDay[i]-newCasesEachDay[i+1])
trend = statistics.mean(diffBetweenEachDay)
return trend
# averages the X latest new_cases days
# NOTE - If one of the days new_cases entry is None, will ignore it but not load another day
# days : (optional) number of days to average
# return : float of average of new_cases across the days
def getLatestNewCasesAverage(self, days=7):
# cannot have zero or negative days
if days < 1:
return 0.0
# connects to databse
conn = sqlite3.connect(self.dbFilename)
newCasesEachDay = []
# connects to database
conn = sqlite3.connect(self.dbFilename)
c = conn.cursor()
c.execute(self.LATEST_ENTRY_QUERY)
latestEntries = c.fetchmany(days)
for entry in latestEntries:
# NEW_CASES is in location 2, skips any None entries
if entry[2] is not None:
newCasesEachDay.append(int(entry[2]))
conn.close()
# gets average of the new cases across the most recent X days
return statistics.mean(newCasesEachDay)
|
0a9f54f5fc8ba014d5f9abb0f8ccce04205acb91 | betty29/code-1 | /recipes/Python/196890_Spawned_Generators/recipe-196890.py | 1,597 | 3.5625 | 4 | from __future__ import generators
import threading
class SpawnedGenerator(threading.Thread):
"Class to spawn a generator."
def __init__(self, generator, queueSize=0):
"Initialise the spawned generator from a generator."
threading.Thread.__init__(self)
self.generator = generator
self.queueSize = queueSize
def stop(self):
"Request a stop."
self.stopRequested = 1
def run(self):
"Called in a separate thread by Thread.start()."
queue = self.queue
try:
it = iter(self.generator)
while 1:
next = it.next()
queue.put((1, next)) # will raise StopIteration
if self.stopRequested:
raise StopIteration, "stop requested"
except:
queue.put((0, sys.exc_info()))
def __call__(self):
"Yield results obtained from the generator."
self.queue = queue = Queue.Queue(self.queueSize)
self.stopRequested = 0
self.start() # run() will stuff the queue in a separate Thread
keepGoing, item = queue.get()
while keepGoing:
yield item
keepGoing, item = queue.get()
# if keepGoing is false, item is exc_info() result
self.exc_info = item # stash it for the curious
type, value, traceback = item
if isinstance(type, StopIteration):
return
else:
raise type, value, traceback
def __iter__(self):
"Return an iterator for our executed self."
return iter(self())
|
9d3716dd640a02870c851d4609be5275ea2ccbf9 | TyroneWilkinson/Python_Practice | /angry_prof.py | 1,083 | 3.796875 | 4 | # https://www.hackerrank.com/challenges/angry-professor/problem
def angryProfessor(k, a):
"""
Given the arrival time of each student and a threshhold number of
attendees, determine if the class is cancelled.
Note:
Arrival times <= 0 are early or on time.
Arrival times > 0 are late.
Parameters:
k (integer): The threshold number of students.
a (list): An integer list housing student arrival times.
Returns:
string: "YES" or "NO" if the class is cancelled or not.
"""
return "YES" if len([s for s in a if s < 1]) < k else "NO"
# t = int(input()) # Number of test cases
# for _ in range(t):
# n, k = map(int, input().split()) # Number of students and threshold
# a = [int(x) for x in input().split()] # Student arrival times
# print(angryProfessor(k,a))
############################################################
for _ in range(int(input())):
n, k = map(int, input().split()) # Number of students and threshold
print("YES") if len([s for s in input().split() if int(s) < 1]) < k else print("NO")
|
910cd6bfdb56c45970ad0e6f2456730648ac8cc2 | vinzdef/Algorithms | /Fractal.py | 244 | 3.625 | 4 | from turtle import *
def f(length, depth):
if depth == 0:
forward(length)
else:
f(length/3, depth-1)
right(60)
f(length/3, depth-1)
left(120)
f(length/3, depth-1)
right(60)
f(length/3, depth-1)
|
069bc221ddde3a98814acda70e5a40f16c6be5e2 | faisalabuzaid/snakes-cafe | /snakes-cafe/snakes_cafe/snakes_cafe.py | 1,258 | 4.09375 | 4 | menu = {
'Appetizers': {'Wings': 0, 'Cookies': 0, 'Spring Rolls': 0},
'Entrees': {'Salmon': 0, 'Steak': 0, 'Meat Tornado': 0, 'A Literal Garden': 0},
'Desserts': {'Ice Cream': 0, 'Cake': 0, 'Pie': 0},
'Drinks': {'Coffee': 0, 'Tea': 0, 'Unicorn Tears': 0}
}
print("""**************************************
** Welcome to the Snakes Cafe! **
** Please see our menu below. **
**
** To quit at any time, type "quit" **
**************************************""", "\n")
for category in menu:
print(category)
print("-" * len(category))
for item in menu[category]:
print(item)
print('\n')
print("""***********************************
** What would you like to order? **
***********************************""", "\n")
order = input("> ")
while order != 'quit':
for key in menu.keys():
if order in menu[key].keys():
menu[key][order]+= 1
if menu[key][order] == 1:
print(f'** {menu[key][order]} order of {order} has been added to your meal **')
break
else:
print(f'** {menu[key][order]} orders of {order} have been added to your meal **')
break
else:
print('** Sorry this item is unavailable, please order item from our menu **')
order = input("> ") |
56870dd61008504213d5472820bb951f9a2bb73e | anithavedantam/LeetCode-Programs | /BST_LevelOrderTraversal.py | 1,137 | 4.09375 | 4 | '''
Author: Anitha Kiron Vedantam
Description: This is a program get the Level-Order Traversal of a Binary Search Tree.
'''
# Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def LevelOrderTraversal(root):
if not root:
return []
res = []
queue = []
queue.append(root)
while queue:
level = []
nextQueue = []
for node in queue:
level.append(node.data)
if node.left:
nextQueue.append(node.left)
if node.right:
nextQueue.append(node.right)
queue = nextQueue
res.append(level)
return res
if __name__ == '__main__':
root = node(4)
root.left = node(2)
root.right = node(5)
root.left.left = node(1)
root.left.right = node(3)
print("Level Order Traversal of Binary Search Tree:")
print(LevelOrderTraversal(root))
|
b5899a74a7f9c69d1e3c71d662258750f6378f76 | tassianunes/Exercicios_Python-adicionais- | /SoftwareEngineeringChallenge/des053.py | 106 | 4.0625 | 4 | frase = str(input('Digite uma frase: ')).strip
if frase[:] == frase[::-1]:
print('É um polindrono') |
442847413ad03c78c386efb43f3fda1e5b5a921a | alexgian1/Password-Generator | /pw_gen.py | 2,681 | 3.890625 | 4 | #Password Generator
import random
numbers = ['1','2','3','4','5','6','7','8','9','0']
letters_lowercase = ["a","b","c","d","e","f",'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
letters_uppercase = [letter.upper() for letter in letters_lowercase]
characters = ['!','@','#','$','%','^','&','*']
password = []
cont_numbers = False
cont_lowercase = False
cont_uppercase = False
cont_characters = False
validPassword = False
length = int(raw_input("Enter Password Length (6-30): "))
if length >= 6 and length <= 30:
choice_numbers = raw_input("Contain Numbers? Y/N: ")
while choice_numbers != "Y" and choice_numbers != "N" and choice_numbers != "y" and choice_numbers != "n":
choice_numbers = raw_input("Contain Numbers? Y/N: ")
if choice_numbers == "y" or choice_numbers == "Y":
cont_numbers = True
validPassword = True
choice_lowercase = raw_input("Contain Lowercase Letters? Y/N: ")
while choice_lowercase != "Y" and choice_lowercase != "N" and choice_lowercase != "y" and choice_lowercase != "n":
choice_lowercase = raw_input("Contain Lowercase Letters? Y/N: ")
if choice_lowercase == "y" or choice_lowercase == "Y":
cont_lowercase = True
validPassword = True
choice_uppercase = raw_input("Contain Upercase Letters? Y/N: ")
while choice_uppercase != "Y" and choice_uppercase != "N" and choice_uppercase != "y" and choice_uppercase != "n":
choice_uppercase = raw_input("Contain Upercase Letters? Y/N: ")
if choice_uppercase == "y" or choice_uppercase == "Y":
cont_uppercase = True
validPassword = True
choice_characters = raw_input("Contain Special Characters? Y/N: ")
while choice_characters != "Y" and choice_characters != "N" and choice_characters != "y" and choice_characters != "n":
choice_characters = raw_input("Contain Special Characters? Y/N: ")
if choice_characters == "y" or choice_characters == "Y":
cont_characters = True
validPassword = True
if validPassword:
allowedCharacters = []
if cont_numbers == True:
for i in numbers:
allowedCharacters.append(i)
if cont_lowercase == True:
for i in letters_lowercase:
allowedCharacters.append(i)
if cont_uppercase == True:
for i in letters_uppercase:
allowedCharacters.append(i)
if cont_characters == True:
for i in characters:
allowedCharacters.append(i)
random.shuffle(allowedCharacters)
while len(password) < length:
for i in allowedCharacters:
if len(password) >= length:
break
else:
password.append(i)
print "\n","".join(password)
raw_input()
log = open("log.txt", "a+")
log.write("".join(password)+"\n")
log.close()
|
6bbae80cb15f50c7ee34cc20a814d2208f06b1af | kreier/T400 | /micropython/motor/motor_pwm.py | 777 | 3.65625 | 4 |
import machine
from machine import Pin, PWM
import time
pwm1 = PWM(Pin(5), freq=1000, duty=0)
pwm2 = PWM(Pin(4), freq=1000, duty=0)
M1 = machine.Pin(0, machine.Pin.OUT)
M2 = machine.Pin(2, machine.Pin.OUT)
M1.on() # forward
M2.on() # forward
print("Motor on")
speed = 10
while speed < 1030 :
speed += 10
time.sleep_ms(50)
pwm1.duty(speed)
pwm2.duty(speed)
print("Max speed")
while speed > 20:
speed -= 10
time.sleep_ms(50)
pwm1.duty(speed)
pwm2.duty(speed)
M1.off() # now backward
M2.off()
while speed < 1030 :
speed += 10
time.sleep_ms(50)
pwm1.duty(speed)
pwm2.duty(speed)
print("Max speed")
while speed > 20:
speed -= 10
time.sleep_ms(50)
pwm1.duty(speed)
pwm2.duty(speed)
pwm1.deinit()
pwm2.deinit()
print("Motor off")
|
a3d73a3372c0e872f2a72c3776fa93c5311eac31 | shamikbose/python_examples | /Coding Interview Qs/kClosest.py | 1,131 | 3.59375 | 4 | # K-closest points
import random
from typing import List
import heapq
from time import time
x_range = 10000
y_range = 10000
point_count = 5000000
points = [
(random.randint(0, x_range), random.randint(0, y_range)) for i in range(point_count)
]
def kClosest(points: list, k: int) -> List[List]:
closest_points = {}
for point in points:
dist = sum([point[i] ** 2 for i in range(len(point))])
closest_points[point] = dist
return sorted(closest_points.items(), key=lambda kv: kv[1])[:k]
def kClosestHeap(points: list, k: int) -> List[List]:
heap = []
for x, y in points:
dist = -(x ** 2 + y ** 2)
if len(heap) == k:
heapq.heappushpop(heap, (dist, (x, y)))
else:
heapq.heappush(heap, (dist, (x, y)))
return [point for (dist, (point)) in heap][::-1]
start = time()
print(kClosest(points, 5))
end = time()
print("Time taken to find K-closest without heap: {:.3f} seconds".format(end - start))
start = time()
print(kClosestHeap(points, 5))
end = time()
print("Time taken to find K-closest with heap: {:.3f} seconds".format(end - start))
|
a4b1b5f4551408091b01db09bdbfd2e134ebf7d7 | JulianCabreraS/thecompletepythoncourse | /DataStructures/List/Comprehension.py | 501 | 4.3125 | 4 | numbers = [0, 1, 2, 3, 4]
doubled_numbers = []
for num in numbers:
doubled_numbers.append(num * 2)
print(doubled_numbers)
# -- List comprehension --
numbers = [0, 1, 2, 3, 4] # list(range(5)) is better
doubled_numbers = [num * 2 for num in numbers]
# [num * 2 for num in range(5)] would be even better.
print(doubled_numbers)
# -- You can add anything to the new list --
friend_ages = [22, 31, 35, 37]
age_strings = [f"My friend is {age} years old." for age in friend_ages]
print(age_strings) |
1aa35937ae4000814cd479e73a0734be81510b62 | fakepp/RabbitGame | /key_capture.py | 996 | 3.765625 | 4 | from msvcrt import getch
class KeyCapture:
def __init__(self):
return
def input(self):
key = ord(getch())
if key == 3:
return 'ESC'
if key >= 48 and key <= 57:
return str(key-48)
if key == 27: #ESC
return 'ESC'
#exit()
elif key == 13: #Enter
return 'GO'
elif key == 32: #Space
return 'S'
elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
key = ord(getch())
if key == 80: #Down arrow
return 'D'
elif key == 72: #Up arrow
return 'U'
elif key == 75: #Left arrow
return 'L'
elif key == 77: #Right arrow
return 'R'
elif key == 83: #Right arrow
return 'DEL'
#print('done')
if __name__ == "__main__":
keyc = KeyCapture()
keyc.input() |
ea607e7bf997efa64e4e16489dc5c1903b365030 | vkuppu/NLP-Natural-Language-Processsing-Implementation | /HtmlParserTokenize.py | 2,230 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### 30July 2019
# ### Snippet to pasre html and read text and create tokens.
# ### Needs few more modifications
# In[1]:
import urllib.request
# In[2]:
response = urllib.request.urlopen('file:///C:/reut2-002.html')
# In[3]:
html = response.read()
# In[5]:
#print (html)
# In[5]:
##use BeautifulSoup to clean the grabbed text like this,
# In[7]:
from bs4 import BeautifulSoup
import urllib.request
response = urllib.request.urlopen('file:///C:/reut2-002.html')
html = response.read()
soup = BeautifulSoup(html,"html5lib")
text = soup.get_text(strip=True)
#print (text)
# In[7]:
###convert that text into tokens by splitting the text like this,
# In[9]:
from bs4 import BeautifulSoup
import urllib.request
response = urllib.request.urlopen('file:///C:/reut2-002.html')
html = response.read()
soup = BeautifulSoup(html,"html5lib")
text = soup.get_text(strip=True)
tokens = [t for t in text.split()]
#print (tokens)
# In [10]
### Convert that text into tokens and Count Word Frequency by FreqDist
#### Written on 31-Jul-2019
from bs4 import BeautifulSoup
import urllib.request
import nltk
response = urllib.request.urlopen('file:///C:/reut2-002.html')
html = response.read()
soup = BeautifulSoup(html,"html5lib")
text = soup.get_text(strip=True)
tokens = [t for t in text.split()]
freq = nltk.FreqDist(tokens)
for key,val in freq.items():
print (str(key) + ':' + str(val))
# In [10]
### Convert that text into tokens and filter the text , Filtered text storing in a file.
from bs4 import BeautifulSoup
import urllib.request
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
# IO library used for Read and write a file
import io
#word_tokenize accepts a string as an input, not a file.
stop_words = set(stopwords.words('english'))
response = urllib.request.urlopen('file:///C:/reut2-002.html')
html = response.read()
soup = BeautifulSoup(html,"html5lib")
text = soup.get_text(strip=True)
words=word_tokenize(text)
for w in words:
if not w in stop_words:
appendFile = open('e:/filteredtext.txt','a')
appendFile.write(" "+w)
appendFile.close()
|
9f6659cb75c42c371fdf51425cc84ab237a1fd20 | fraserweist/euler | /0xx/001-multiples.py | 262 | 3.671875 | 4 | import sys
def main():
if len(sys.argv) != 2:
print "usage:\npython 001-multiples.py n"
quit()
script, n = sys.argv
result = 0
for i in range(int(n)):
if i % 3 == 0 or i % 5 == 0:
result += i
print "result = "+str(result)
main() |
280f56d61905df5f285e14671de4648974171d61 | xerifeazeitona/PCC_Basics | /chapter_10/exercises/01_learning_python.py | 1,005 | 5.03125 | 5 | """
10-1. Learning Python
Open a blank file in your text editor and write a few lines summarizing
what you’ve learned about Python so far. Start each line with the phrase
"In Python you can. . . ."
Save the file as learning_python.txt in the same directory as your
exercises from this chapter.
Write a program that reads the file and prints what you wrote three
times.
Print the contents:
- once by reading in the entire file
- once by looping over the file object
- once by storing the lines in a list and then working with them outside
the with block.
"""
file_path = "learning_python.txt"
print("\nReading the entire file...")
with open(file_path) as file_object:
print(file_object.read().rstrip())
print("\nLooping over the file object...")
with open(file_path) as file_object:
for line in file_object:
print(line.rstrip())
print("\nOutside the with block...")
with open(file_path) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
|
9bb9b92dbb96034f4bc134b5eb96c4ab030e193c | timstevens1/go_fish | /Go_Fish_Final.py | 15,689 | 3.75 | 4 | import random
from deck import Deck
import time
# initialize global variables for player hands, score and end game statistics.
# AUTHORS: EMMA TAIT and TIM STEVENS
PLAYER_HAND = []
COMPUTER_HAND = []
PLAYER_SCORE = 0
COMPUTER_SCORE = 0
LIES = 1
TOTAL_CARDS_PASSED = 0 # for stats
GF_COUNTER = 0
SUCCESS_COUNTER = 0
START_TIME = 0
END_TIME = 0
TURN_COUNTER = 0
CARD_FREQUENCY = [0,0,0,0,0,0,0,0,0,0,0,0,0]
RANK = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
deck = Deck()
PLAYER_HAND, COMPUTER_HAND, deck = deck.deal_hands()
LAST_ASKED = ''
ASK_INDEX = 0
#input validation for difficulty level
###AUTHOR: JOSE VILA
difficulty_level = None
while difficulty_level is None:
difficulty_level_value = input(
"Welcome to Go Fish: the computer program!\n\nGo fish is a game where you try to get as many sets of four of a\nkind (called books) as possible. To do this, you may ask the computer for\n"
+"a card each turn. You must have the card in your hand in order to be able to ask for it. \n\nIf the computer has the card you requested it will give it to you. If not it will tell you\n"
+"to 'Go Fish' and you will draw a card. Then it will be the computer's turn. The computer will \ngo through the same process. If you have the card that the computer asked for it will\n"
+"take the card, if not it will draw. \n\nWhen you have four cards of the same rank they will be removed from your \nhand and you will score one point. The game ends when ther are no more\n"
+"cards in the deck or in either player's hand (they have all been played as books).\n\nYou can play go fish against a computer program here based on 3 different difficulty levels:\n" +
"1: The computer plays randomly.\n" + "2: The computer plays with some strategy.\n" + "3: The computer lies.\n")
#make sure only integers are entered
try:
difficulty_level = int(difficulty_level_value)
except ValueError:
print("I'm sorry. {input} is not a number.".format(input=difficulty_level_value))
difficulty_level = None
continue
else:
#successful input!
#now validate the number
if difficulty_level > 3 or difficulty_level == 0:
print("The number you input is not a difficulty level")
difficulty_level = None
continue
#successful difficulty level entered! break the loop
else:
START_TIME = time.time()
break
## This method determines the computer's response to players requests
## depending on the difficulty level
###AUTHOR: EMMA TAIT
def Computer_Response(hand, level, card):
global LIES
response = False
if level == 1:
if card in hand:
response = True
return response
#computer chooses card to ask for at random from cards in its hand
if level == 2:
if card in hand:
response = True
return response
#computer asks for card drawn or rotates through other cards
if level == 3:
if card in hand and LIES != 3:
response = True
LIES += 1
if card in hand and LIES == 3:
response = False
LIES = 1
return response
#computer lies every 3rd time it has what player asks for
# adds correct number of cards to hand that asked for them
###AUTHORS EMMA TAIT
def add_cards(hand,card,num):
x = 0
while x < num:
hand.append(card)
x += 1
return hand
#removes the correct number of cards from the hand that had them
###AUTHORS: EMMA TAIT
def remove_cards(hand,card,num):
x = 0
while x < num:
hand.remove(card)
x += 1
return hand
#gets the number of cards of the type asked for from the asked hand
#also collects statistic information on cards
###AUTHORS: EMMA TAIT AND TIM STEVENS
def num_cards_of_type_asked(hand,card):
global TOTAL_CARDS_PASSED
global RANK
global CARD_FREQUENCY
num_cards = 0
for x in hand:
if x==card:
num_cards+=1
TOTAL_CARDS_PASSED += num_cards
CARD_FREQUENCY[RANK.index(card)] += 1
return num_cards
#makes sure that the deck is not empty before they draw a card.
###AUTHOR: EMMA TAIT
def Go_Fish():
global deck
global GF_COUNTER
deck_empty = False
if len(deck) == 0:
deck_empty = True
else:
time.sleep(0.5)
print ("\nGo fish...\n")
time.sleep(0.5)
GF_COUNTER +=1
return deck_empty
#determine if player has books of cards and tally score.
### AUTHOR: TIM STEVENS
def Make_Books(player, counter):
# index of rank array is a mapping to num_decks
ranks = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
# counters of number of cards of a given rank in the hand
num_card_type = [0,0,0,0,0,0,0,0,0,0,0,0,0]
for card in player:
# increments appropriate rank counter for each card
num_card_type[ranks.index(card)] +=1
for i in range(13):
# 4 cards of a rank in the hand
if num_card_type[i]>= 4:
# increment deck counter
counter+=1
# remove deck from hand
player = [x for x in player if not ranks[i] in x]
return player, counter
#print statistics at the end of the game.
###AUTHOR: TIM STEVENS
def End_Game():
global TOTAL_CARDS_PASSED
global PLAYER_SCORE
global COMPUTER_SCORE
global GF_COUNTER
global START_TIME
global SUCCESS_COUNTER
global TURN_COUNTER
global CARD_FREQUENCY
global RANK
global END_TIME
END_TIME = time.time()
avg_card_passed = TOTAL_CARDS_PASSED/(TURN_COUNTER*2)
most_common_card = RANK[CARD_FREQUENCY.index(max(CARD_FREQUENCY))]
least_common_card = RANK[CARD_FREQUENCY.index(min(CARD_FREQUENCY))]
#computer wins
if COMPUTER_SCORE > PLAYER_SCORE:
print('You lost!')
print('Game Stats:\n')
print('Your Score: {}'.format(PLAYER_SCORE))
print('Computer Score: {}'.format(COMPUTER_SCORE))
print('Total cards passed: {}'.format(TOTAL_CARDS_PASSED))
print('Total times players went fish: {}'.format(GF_COUNTER))
print('Total correct guesses: {}'.format(SUCCESS_COUNTER))
print('Most common card asked for: {} occurred {} times'.format(most_common_card,max(CARD_FREQUENCY)))
print('Least common card asked for: {} occurred {} times'.format(least_common_card,min(CARD_FREQUENCY)))
print('Mean number of cards passed per turn: {0:.1f}'.format(avg_card_passed))
print('Number of turns: {}'.format(TURN_COUNTER))
print('Game duration: {0:.2f}'.format(TIME_COUNTER),"seconds")
#player wins
else:
print('Congratulations! You won!')
print('Game Stats:\n')
print('Your Score: {}'.format(PLAYER_SCORE))
print('Computer Score: {}'.format(COMPUTER_SCORE))
print('Total cards passed: {}'.format(TOTAL_CARDS_PASSED))
print('Total times players went fish: {}'.format(GF_COUNTER))
print('Total correct guesses: {}'.format(SUCCESS_COUNTER))
print('Most common card asked for: {} occurred {} times'.format(most_common_card, max(CARD_FREQUENCY)))
print('Least common card asked for: {} occurred {} times'.format(least_common_card, min(CARD_FREQUENCY)))
print('Mean number of cards passed per turn: {0:.1f}'.format(avg_card_passed))
print('Number of turns: {}'.format(TURN_COUNTER))
print('Game duration: {0:.2f}'.format((END_TIME-START_TIME)/60),"minutes")
#the players turn. Allows the player to request a card. Gets the card if the computer has it, if not draws a card.
# if the card the player draws is the card they asked for they get to go again.
#AUTHOR: EMMA TAIT and KYLE WHALEN (debugging)
def Player_Turn():
global PLAYER_SCORE
global GF_COUNTER
global SUCCESS_COUNTER
global COMPUTER_SCORE
global COMPUTER_HAND
global PLAYER_HAND
global deck
print ("Score: \t Player: ",PLAYER_SCORE,"Computer: ",COMPUTER_SCORE)
#Handles case if player's hand is empty and the deck is not
if len(PLAYER_HAND) == 0 and len(deck) !=0 :
drawn_card = deck[random.randint(0,len(deck)-1)]
PLAYER_HAND.append(drawn_card)
deck.remove(drawn_card)
Computer_Turn()
#if players hand is not empty.
elif len(PLAYER_HAND) !=0:
PLAYER_HAND.sort()
print("YOUR HAND: ",PLAYER_HAND,"\n")
time.sleep(0.7)
#validates card input from user
###AUTHOR: JOSE VILA
card = None
while card is None:
card = input("What do you ask for? ").upper() #allows user to enter lowercase letters for Jack Queen King and Ace ranks
time.sleep(0.5)
if card not in PLAYER_HAND:
print("The card you asked for is not in your hand. Try again. ")
card = None
continue
else:
break
###AUTHOR: EMMA TAIT
response = Computer_Response(COMPUTER_HAND, difficulty_level, card)
#if computer has what the player asked for pass the cards
if response == True:
SUCCESS_COUNTER +=1
print("You got what you asked for!\n")
time.sleep(0.7)
num_cards = num_cards_of_type_asked(COMPUTER_HAND,card)
PLAYER_HAND = add_cards(PLAYER_HAND,card,num_cards)
COMPUTER_HAND = remove_cards(COMPUTER_HAND,card,num_cards)
#check for books
PLAYER_HAND, PLAYER_SCORE = Make_Books(PLAYER_HAND,PLAYER_SCORE)
PLAYER_HAND.sort()
print ("YOUR HAND: ",PLAYER_HAND,"\n")
time.sleep(0.7)
#if computer does not have what the player asked for
else:
if not Go_Fish():#checks if there are cards in the deck to draw
drawn_card = deck[random.randint(0,len(deck)-1)]
PLAYER_HAND.append(drawn_card)
deck.remove(drawn_card)
print("You drew a ",drawn_card,"\n")
time.sleep(0.7)
PLAYER_HAND.sort()
print ("YOUR HAND:",PLAYER_HAND,"\n")
time.sleep(0.7)
#check to see if player has books
PLAYER_HAND, PLAYER_SCORE = Make_Books(PLAYER_HAND,PLAYER_SCORE)
#checks to make sure game is running, if so, passes the turn to the computer
if len(deck) != 0 or len(PLAYER_HAND) != 0 or len(COMPUTER_HAND) !=0: # while game is going
Computer_Turn()
else:
End_Game()
#computer turn. Allows the computer to request a card. Gets the card if the player has it, if not draws a card.
# if the card the player draws is the card they asked for they get to go again.
#AUTHOR: EMMA TAIT and KYLE WHALEN (debugging)
def Computer_Turn():
global PLAYER_SCORE
global COMPUTER_SCORE
global COMPUTER_HAND
global PLAYER_HAND
global TURN_COUNTER
global GF_COUNTER
global SUCCESS_COUNTER
global deck
global difficulty_level
TURN_COUNTER +=1
## handles case when computer's hand is empty and there is still a deck. It draws a card and passes the turn.
if len(COMPUTER_HAND) == 0 and len(deck) != 0:
drawn_card = deck[random.randint(0,len(deck)-1)]
COMPUTER_HAND.append(drawn_card)
deck.remove(drawn_card)
Player_Turn()
#if the computer's hand is not empty
elif len(COMPUTER_HAND) != 0:
#Easy difficulty
if difficulty_level == 1:
card_asked = COMPUTER_HAND[random.randint(0,len(COMPUTER_HAND)-1)]
print ("Computer: Do you have any",card_asked,"\n")
time.sleep(0.7)
num_cards = num_cards_of_type_asked(PLAYER_HAND,card_asked)
# if player has what computer asked for add cards to player hand and remove from computer hand
if card_asked in PLAYER_HAND:
SUCCESS_COUNTER += 1
COMPUTER_HAND = add_cards(COMPUTER_HAND,card_asked,num_cards)
PLAYER_HAND = remove_cards(PLAYER_HAND,card_asked,num_cards)
#check for books
COMPUTER_HAND, COMPUTER_SCORE = Make_Books(COMPUTER_HAND,COMPUTER_SCORE)
print("The computer took your ",card_asked,"\n")
time.sleep(0.7)
else:
if not Go_Fish():#checks to see if there are cards in the deck that can be drawn
drawn_card = deck[random.randint(0,len(deck)-1)]
COMPUTER_HAND.append(drawn_card)
deck.remove(drawn_card)
#check to see if game is over, if not go to the next player
COMPUTER_HAND, COMPUTER_SCORE = Make_Books(COMPUTER_HAND,COMPUTER_SCORE)
if len(deck) != 0 or len(PLAYER_HAND) != 0 or len(COMPUTER_HAND) !=0: # while game is going
Player_Turn()
else:
End_Game()
# Medium and Hard Difficulty: NOTE: The computer uses the same strategy to pick which card to ask for.
# The difference in difficulty is in the response to the users request.
###AUTHOR: EMMA TAIT and KYLE WHALEN (debugging)
if difficulty_level == 2 or difficulty_level == 3:
#makes sure that computer asks for most recent card drawn unless that was what it asked for the
#previous turn in which case it iterates through its hand.
global LAST_ASKED
global ASK_INDEX
if LAST_ASKED != '':
ASK_INDEX = COMPUTER_HAND.index(LAST_ASKED)
print ("comp hand",COMPUTER_HAND)
card_asked = COMPUTER_HAND[len(COMPUTER_HAND)-1]
COMPUTER_HAND.sort()
print ("comp hand",COMPUTER_HAND)
if card_asked == LAST_ASKED:
for card in COMPUTER_HAND:
if card == card_asked:
ASK_INDEX += 1
print(ASK_INDEX)
if ASK_INDEX < len(COMPUTER_HAND):
card_asked = COMPUTER_HAND[ASK_INDEX]
ASK_INDEX += 1
else:
ASK_INDEX = 0
card_asked = COMPUTER_HAND[ASK_INDEX]
LAST_ASKED = card_asked
print ("Computer: Do you have any",card_asked, "\n")
time.sleep(0.7)
num_cards = num_cards_of_type_asked(PLAYER_HAND,card_asked)
# if player has what computer asked for add cards to player hand and remove from computer hand
if card_asked in PLAYER_HAND:
SUCCESS_COUNTER +=1
COMPUTER_HAND = add_cards(COMPUTER_HAND,card_asked,num_cards)
PLAYER_HAND = remove_cards(PLAYER_HAND,card_asked,num_cards)
#check for books
COMPUTER_HAND, COMPUTER_SCORE = Make_Books(COMPUTER_HAND,COMPUTER_SCORE)
print("The computer took your ",card_asked,"\n")
time.sleep(0.7)
else:
if not Go_Fish():#checks to make sure there are cards in the deck to draw
drawn_card = deck[random.randint(0,len(deck)-1)]
COMPUTER_HAND.append(drawn_card)
deck.remove(drawn_card)
# checks to see if game is over, if not goes to next turn
COMPUTER_HAND, COMPUTER_SCORE = Make_Books(COMPUTER_HAND, COMPUTER_SCORE)
if len(deck) != 0 or len(PLAYER_HAND) != 0 or (COMPUTER_HAND !=0): # while game is going
Player_Turn()
else:
End_Game()
else:
End_Game()
#initializes first turn
Player_Turn()
|
5b38779a3dd38498c00735cb4bab8976d6b043c6 | 28ACB29/HackerRank-Solutions | /Python/Strings/Capitalize!.py | 273 | 3.953125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
def capitalize(old_string):
return old_string[0].upper() + old_string[1:] if len(old_string) > 0 else old_string
S = raw_input().strip()
words = S.split(" ")
print(" ".join(map(capitalize, words)))
|
391f416cc8cb7ab3addbe8b44cf801ba420a9f2d | viraco4a/SoftUni | /PythonBasics/Conditional-Statements-Lab/ToyShop.py | 698 | 3.703125 | 4 | first = 2.6
second = 3
third = 4.1
fourth = 8.2
fifth = 2
discount = 0.25
discount_amount = 50
rent = 0.1
excursion_price = float(input())
first_num = int(input())
second_num = int(input())
third_num = int(input())
fourth_num = int(input())
fifth_num = int(input())
profit = first_num * first + second_num * second + third_num * third + fourth_num * fourth + fifth_num * fifth
order = first_num + second_num + third_num + fourth_num + fifth_num
if order >= discount_amount:
profit *= (1 - discount)
profit *= (1 - rent)
difference = profit - excursion_price
if difference >= 0:
print(f"Yes! {difference:.2f} lv left.")
else:
print(f"Not enough money! {-difference:.2f} lv needed.") |
78f16b17fa2dd0c571293019f9c5ee04c0c14197 | vinodkkumarr/PythonBasic | /Assignment operators.py | 313 | 4.25 | 4 | print("assignment operators")
a=5
print("Value of a is " + str(a))
a+=2
print ("Value increament by 1 using a+=1 is " + str(a))
a-=2
print ("Value decreased by 2 using a-=2 is " + str(a))
a*=2
print ("Value multiplied by 2 using a*=2 is " + str(a))
a/=2
print ("Value divided by 2 using a/=2 is " + str(a))
|
0964932ad9ce2e76abb80846f5a6029395983712 | www111111/A1804_02 | /get.py | 511 | 3.984375 | 4 | '''
class Yl(object):
def __init__(self,name):
self.name=name
def get(self):
print(self.name)
def set(self,name):
self.name=name
print(self.name)
yl1=Yl('yl')
yl1.get()
yl1.set('sb')
print(yl1.name)
'''
class Animal(object):
def dong(self,a):
print('111',a)
class Dog(Animal):
def eat(self,a):
#super().dong(a)
self.dong(a)
print('222')
ss=Animal()
dog=Dog()
dog.eat('bb')
ss.dong('s')
#引用带argument也可以用
|
5c39f58cc936cdc03b2d43fe13931181300e3390 | prannb/CS671_assign2 | /doc2vec/stopwords.py | 533 | 3.703125 | 4 | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import re
example_sent = "This is a sample sentence, showing off the stop words br filtration."
stop_words = set(stopwords.words('english'))
word_tokens = word_tokenize(example_sent)
# filtered_sentence = [w for w in word_tokens if not w in stop_words]
# filtered_sentence = []
for w in word_tokens:
if (w not in stop_words) and re.match(r"\w", w):
# filtered_sentence.append(w)
print w
# print(word_tokens)
# print(filtered_sentence)
|
93867a655df365a26af7b7768d11f307a2a713db | protivofazza/studies | /hw_1_2.py | 2,953 | 3.90625 | 4 | print("Завдання №1.2\nПрограма для виводу результатів різних операцій над двома числами")
print("_" * 65)
value_1 = int(input('Введіть перше число: '))
value_2 = int(input('Введіть друге число: '))
print("\nРезультати арифметичних операцій над двома числами", value_1, "та", value_2)
print("-"*57)
result = value_1 + value_2
print("- Результат додавання:\t\t\t\t\t", value_1, "+", value_2, "=", result)
result = value_1 - value_2
print("- Результат віднімання:\t\t\t\t\t", value_1, "-", value_2, "=", result)
result = value_1 * value_2
print("- Результат множення:\t\t\t\t\t", value_1, "*", value_2, "=", result)
result = value_1 / value_2
print("- Результат ділення:\t\t\t\t\t", value_1, "/", value_2, "=", result)
result = value_1 // value_2
print("- Результат цілочисленного ділення:\t\t", value_1, "//", value_2, "=", result)
result = value_1 ** value_2
print("- Результат зведення в степінь:\t\t\t", value_1, "**", value_2, "=", result)
result = value_1 % value_2
print("- Результат залишку від ділення:\t\t", value_1, "%", value_2, "=", result)
print("\nРезультати операцій порівняння двох чисел", value_1, "та", value_2)
print("-"*57)
result = value_1 > value_2
print("- Результат порівняння:\t\t\t\t\t", value_1, ">", value_2, " ---", result)
result = value_1 < value_2
print("- Результат порівняння:\t\t\t\t\t", value_1, "<", value_2, " ---", result)
result = value_1 == value_2
print("- Результат порівняння:\t\t\t\t\t", value_1, "==", value_2, "---", result)
result = value_1 != value_2
print("- Результат порівняння:\t\t\t\t\t", value_1, "!=", value_2, "---", result)
result = value_1 >= value_2
print("- Результат порівняння:\t\t\t\t\t", value_1, ">=", value_2, "---", result)
result = value_1 <= value_2
print("- Результат порівняння:\t\t\t\t\t", value_1, "<=", value_2, "---", result)
print("\nРезультати логічних операцій для звичайних чисел майже не мають сенсу, проте вони можливі.\nДля чисел",
value_1, "та", value_2, "вони видаватимуть такі результати:")
print("-"*57)
result = value_1 and value_2
print("- Результат логічного 'І':\t\t\t\t", value_1, "and", value_2, "---", result)
result = value_1 or value_2
print("- Результат логічного 'АБО':\t\t\t", value_1, "or", value_2, " ---", result)
print("- Логічний 'НІ' працює з одним числом") |
8112a3e208dc2dbf03aac548067f2dbd4bb8aaf6 | zoeyangyy/algo | /jump_step2.py | 309 | 3.5625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def jumpFloorII(self, number):
# write code here
li = [0, 1, 2]
if number <= 2:
return li[number]
for i in range(3, number+1):
li.append(sum(li)+1)
return li[-1]
c = Solution()
print(c.jumpFloorII(5)) |
c027122d9acd8590cae810aee51e6a301981ee03 | IngArmando0lvera/Examples_Python | /Condicionales/15 Ejercicio 1 son par.py | 452 | 4 | 4 | '''Ejercicio N.1
Crear un programa que pida 2 numeros y obtener como resultado
cual de ellos es par o si ambos son par
'''
#obtenemos datos
dato1 = int(input("Ingrese dato 1: "))
dato2 = int(input("Ingrese dato 2: "))
#procesamos
if dato1%2 == 0 and dato2%2 == 0:
print("Ambos datos son par!")
elif dato1%2 == 0:
print("Dato 1 es par!")
elif dato2%2 == 0:
print("Dato 2 es par!")
else:
print("Ninguno es par!")
|
e7192153b93fe1609f026160277e73e263278f54 | Manikantas1729/PythonPrograms | /Decorators/simple_decorator-1.py | 398 | 3.59375 | 4 | def my_decorator(func):
def wrapper_my_decorator(*args, **kwargs): # args and kwargs to accept fn with args and kwargs
print("Something before fucntion is called")
func(*args, **kwargs)
print("Something after funciton is called")
return wrapper_my_decorator
@my_decorator # called pie syntac
def play_game(game):
print(f"Lets play {game}")
play_game("cricket") |
42d784590c5a8f27f913d5d17e2c2721f08db59c | LeiLu199/assignment6 | /yx887/interval/exceptions.py | 620 | 3.53125 | 4 | class Error(Exception):
"""Base class for exceptions in this module.
Attributes:
msg (str): Explanation of the exception.
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class NotAnIntervalError(Error):
"""Raised when user input string is not in valid interval form. """
pass
class InvalidBoundsError(Error):
"""Raised when given interval bounds and bound types represent an empty interval. """
pass
class NotOverlappingError(Error):
"""Raised when trying to merge two intervals that not overlap. """
pass
|
3bc6767a45ecd330a81a93f84c15f429badc2f2c | gistable/gistable | /all-gists/733643/snippet.py | 3,819 | 3.796875 | 4 | import math
import random
class Statistic(object):
"""
Hookin' it up with the seven descriptive statistics.
"""
def __init__(self, sample):
self.sample = sample
def size(self):
return len(self.sample)
def min(self):
return min(self.sample)
def max(self):
return max(self.sample)
def mean(self):
return sum(self.sample) / len(self.sample)
def median(self):
length = len(self.sample)
if length % 2 == 0:
return (self.sample[length/2] + self.sample[length/2 + 1]) / 2
else:
return self.sample[math.floor(length/2)]
def variance(self):
mean = self.mean()
return sum(math.pow(mean - value, 2) for value in self.sample) / (len(self.sample)-1)
def standard_deviation(self):
return math.sqrt(self.variance())
def histogram(self, width=80.0):
k = int(math.ceil(math.sqrt(self.size())))
size = (self.max() - self.min()) / k
bins = [(self.min() + (i * size), (self.min() + (i + 1) * size)) for i in xrange(k)]
labels = ['%8.5f - %8.5f [%%s]' % bin for bin in bins]
labelsize = max(len(label) for label in labels)
populations = [len([i for i in self.sample if bin[0] <= i < bin[1]]) for bin in bins]
maxpop = max(populations)
histosize = width - labelsize - 1
width = width - len(str(maxpop)) - 1
for i, label in enumerate(labels):
label = label % str(populations[i]).rjust(len(str(maxpop)))
print label.rjust(labelsize), '#' * int(populations[i] * width / float(maxpop))
if __name__ == '__main__':
sample = [15, 20, 21, 36, 15, 25, 15]
statistic = Statistic(sample)
print 'mean is %s' % statistic.mean()
print 'variance is %s' % statistic.variance()
print '+1 deviation (68%%): %s' % (statistic.mean() + statistic.standard_deviation())
print '+2 deviation (95%%): %s' % (statistic.mean() + statistic.standard_deviation() * 2)
print '+3 deviation (99%%): %s' % (statistic.mean() + statistic.standard_deviation() * 3)
print 'Standard deviation of 15, 20, 21, 36, 15, 25, 15 is: %s' % statistic.standard_deviation()
statistic.histogram()
print ''
print ''
statistic = Statistic([random.gauss(25, 10) for _ in xrange(1000)])
print 'mean: %s, variance is: %s, min: %s, max: %s' % (statistic.mean(), statistic.variance(), statistic.min(), statistic.max())
print '+1 deviation (68%%): %s' % (statistic.mean() + statistic.standard_deviation())
print '+2 deviation (95%%): %s' % (statistic.mean() + statistic.standard_deviation() * 2)
print '+3 deviation (99%%): %s' % (statistic.mean() + statistic.standard_deviation() * 3)
statistic.histogram()
statistic = Statistic([random.triangular(0, 3400, 2876) for _ in xrange(1000)])
print 'mean: %s, variance is: %s, min: %s, max: %s' % (statistic.mean(), statistic.variance(), statistic.min(), statistic.max())
print '+1 deviation (68%%): %s' % (statistic.mean() + statistic.standard_deviation())
print '+2 deviation (95%%): %s' % (statistic.mean() + statistic.standard_deviation() * 2)
print '+3 deviation (99%%): %s' % (statistic.mean() + statistic.standard_deviation() * 3)
statistic.histogram()
statistic = Statistic([random.expovariate(0.001) for _ in xrange(250)])
print 'mean: %s, variance is: %s, min: %s, max: %s' % (statistic.mean(), statistic.variance(), statistic.min(), statistic.max())
print '+1 deviation (68%%): %s' % (statistic.mean() + statistic.standard_deviation())
print '+2 deviation (95%%): %s' % (statistic.mean() + statistic.standard_deviation() * 2)
print '+3 deviation (99%%): %s' % (statistic.mean() + statistic.standard_deviation() * 3)
statistic.histogram()
|
a0d1896c552d41fc803dc3bdd2dd9e5d885449eb | Yakobo-UG/Python-by-example-challenges | /challenge 12.py | 392 | 4.1875 | 4 | #Ask for two numbers. If the first one is larger than the second, display the second number first and then the first number, otherwise show the first number first and then the second.
First_No = int(input("Entaer the first number: "))
Second_No = int(input("ENter the second number: "))
if First_No > Second_No:
print( Second_No, First_No )
else:
print(First_No, Second_No)
|
57608405c9e638cc483b6f492a5cef133de8ee42 | priscillashort/priscillashort.github.io | /Samples/Python/Loan/LoanPaymentCalculator.py | 1,041 | 4.03125 | 4 | def is_number(s):
try:
float(s)
return True
except ValueError:
return False
print('Welcome to the loan payment calculator. Please input the rate per period, present value, and number of periods and the loan payment will be printed')
x = input("Rate per period as a percentage (eg. 8 for 8%): ")
while is_number(x) == False:
print("Oops! This is not a number.")
x = input("Rate per period as a percentage (eg. 8 for 8%): ")
y = input("Present Value: ")
while is_number(y) == False:
print("Oops! This is not a number.")
y = input("Present Value: ")
z = input("Number of periods: ")
while is_number(z) == False:
print("Oops! This is not a number.")
z = input("Number of periods: ")
if is_number(x) == True and is_number(y) == True and is_number(z) == True:
x=float(x)/100
y=float(y)
z=float(z)
Result = (x*y)/(1-(1+x)**-z)
Result = float(Result)
Result = round(Result,2)
print('The loan payment is $' + str(Result))
input('Enter any key to exit: ')
|
0011e7aa3eb483adaba88932c5ca491853cf2796 | aagray33/Bank-System | /bank-app1.py | 975 | 4.03125 | 4 | from Bank import BankAccount
print("Welcome to App1\n===============\n")
salary,initial_cbalance,initial_sbalance = map(float, input("Enter salary and initial balances for Checking and Saving accounts: ").split())
#create accounts
acc1 = BankAccount("Checking",initial_cbalance)
acc2 = BankAccount("Saving",initial_sbalance)
print(acc1)
print(acc2)
print("Month--salary--expense--saving")
def transfer(amount, source, destination):
source.withdraw(amount)
destination.deposit(amount)
for i in range(12):
expense = .8*salary
addsaving = .15*salary
print(i+1,"--"+str(int(salary))+"--"+str(int(expense))+"--"+str(int(addsaving)), sep='')
#deposit the money made into checking
acc1.deposit(salary)
#withdraw expenses
acc1.withdraw(expense)
#transfer saving money from checking into savings
transfer(addsaving, acc1, acc2)
salary = salary + salary*.002
print(acc1)
print(acc2)
|
738afdff536b7cd924f91f121aa6e3b2d87f84ab | nbveroczi/holbertonschool-higher_level_programming | /basic_oop_with_python/circle.py | 1,322 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 17 21:22:02 2016
@author: nbveroczi
"""
"""
Script Circle:
This is a script that describes a Circle Class with Private attributes, Public
attributes and Public method.
Return: the area of the circle(float)
"""
#start
from math import pi
''' Class '''
class Circle():
''' Constructor '''
def __init__(self, radius):
#private attributes
self.__radius = radius
self.__center = [int,int]
self.__color = ("")
#public attributes
self.name = ("")
''' Destructor '''
def __del__(self):
pass
''' Getter '''
def get_radius(self):
return self.__radius
def get_center(self):
return self.__center
def get_color(self):
return self.__color
def get_name(self):
return self.name
''' Setter '''
def set_radius(self, radius):
self.__radius = radius
def set_center(self, center):
self.__center = center
def set_color(self, color):
self.__color = color
def set_name(self, name):
self.name = name
''' Public Method '''
def area(self):
return((self.__radius ** 2) * pi) #float
|
ac60110f2450a6961917a3959d5fbf1ad1b1f39b | pageinsec/genericScripts | /python3/simpleClient.py | 361 | 3.53125 | 4 | # Simple client, will connect, send a message, and close
import socket
# Get info for server
hostIP = input("Host IP: ")
hostPort = int(input("Host Port: "))
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((hostIP, hostPort))
print("Connected")
message = input("What's the message? ")
client.sendall(message.encode())
client.close()
|
ea6884339ab45af836ec9c3245e3c952e4dca0cf | mkmathur/Projects | /Numbers/factorial.py | 188 | 4.09375 | 4 | def factorial(n):
result = 1
for i in range(2,n+1):
result = result * i
return result
def recursive_factorial(n):
if n <= 1:
return 1
else:
return n * recursive_factorial(n-1)
|
22ef110810841aee1e94165558669042e64fe4d7 | pulkitmathur10/FSBC2019 | /Day 05/regex3.py | 314 | 3.875 | 4 | #Regular Expression 3
import re
while True:
em_str = input("Enter the card number ")
if not em_str:
break
card_val = re.findall(r'^[456]{1}[\d]{3}-?[\d]{4}-?[\d]{4}-?[\d]{4}', em_str)
if card_val:
print("Valid")
else:
print("Invalid")
|
24e3bafc93f78b29ba58e379534a3dc692eb1af0 | maryyang1234/hello-world | /string/9.计算元音数量.py | 202 | 3.703125 | 4 | def calcuVowel(str):
set_vowel = set("aeiouAEIOU")
count = 0
for i in str:
if i in set_vowel:
count+=1
return count
str = "GeeksforGeeks"
print(calcuVowel(str))
|
fa95db05e5b2a11122249ebc62d2e028bfd5cb39 | sandykramb/PythonBasicConcepts | /Divisible_by_5.py | 111 | 3.875 | 4 | numero = int(input("Digite um numero inteiro:"))
if numero %5 == 0:
print ("Buzz")
else:
print (numero)
|
993fb31b390398fd379feea6d40e0a0b4655db4c | kbutler52/Teach2020 | /valueOf_i.py | 58 | 3.625 | 4 | i=0
while i<5:
print('The value of i =',i)
i=i+1
|
91e4be9f0e5c38425441cdb13bd75d7422b250d6 | Hyperparticle/lct-master | /charles-university/2018-npfl104/hw/coding-bat/simple_class.py | 244 | 3.515625 | 4 | class SimpleClass:
def __init__(self):
self.name = 'SimpleClass'
self.methods = ['add', 'mul']
self.simple = True
def add(self, a, b):
return a + b
def mul(self, a, b):
return a * b
|
1437a4699704fedf33f9703a54a069820929c917 | andreaslillevangbech/AoC-2020 | /day18/solve.py | 720 | 3.5 | 4 | #!/usr/bin/env python3
import re
import itertools
lines = open('input').read().strip().split('\n')
class Num:
def __init__(self, num):
self.num = num
def __add__(self, other):
return Num(self.num * other.num)
def __sub__(self, other):
return Num(self.num + other.num)
def __mul__(self, other):
return Num(self.num + other.num)
def process(line):
tr = str.translate(line, tab)
return re.sub(r'(\d+)', r'Num(\1)', tr)
tab = str.maketrans("+*", "-+")
pr = map(process, lines)
res = map(lambda l: eval(l).num, pr)
print(sum(res))
print("Part 2")
tab = str.maketrans("+*", "*+")
pr = map(process, lines)
res = map(lambda l: eval(l).num, pr)
print(sum(res))
|
11f86ff14963c148a094bdf9bb80433823313e67 | giovannyortegon/holbertonschool-machine_learning | /math/0x00-linear_algebra/5-across_the_planes.py | 467 | 3.796875 | 4 | #!/usr/bin/env python3
""" Adds two matrices element-wise """
add_arrays = __import__('4-line_up').add_arrays
def add_matrices2D(mat1, mat2):
""" add_matrices2D
mat1: First matrix
mat2: Second Matrix
Return: Result of elements of matrix
"""
new_mat = []
len_mat = len(mat1)
if len(mat1[0]) == len(mat2[0]):
new_mat = [add_arrays(mat1[i], mat2[i]) for i in range(len_mat)]
return new_mat
else:
return None
|
cdfa44f95373939e342fe1021a1fc1b7ff3f6880 | NovaPlusCoding/Infytq-Assignment-Solution | /Programming-Fundamentals-Using-Python/Day9/Practice-Exercise/Level2/problem21.py | 352 | 3.609375 | 4 | #PF-Prac-21
def check_numbers(num1,num2):
num_list = []
count = 0
for i in range(num1, (num2 // 2) + 1):
num_list.extend([x for x in range(i + 1, num2 + 1) if x % i == 0])
print(num_list)
num_list = set(num_list)
count = len(num_list)
return [num_list, count]
num1=2
num2=20
print(check_numbers(num1, num2))
|
7de0083aecebb52fc9ee9316a291eafcf846489a | kiselevskaya/Python | /experiments/32_biology_meets_programming/hamming_distance.py | 918 | 3.578125 | 4 |
def hamming_distance(p, q):
mismatches = []
if len(p) != len(q):
return 'Input strings must be equal'
for i in range(len(p)):
if p[i] != q[i]:
mismatches.append(i)
return len(mismatches)
def approximate_pattern_matching(text, pattern, d):
positions = []
last_check_index = len(text)-len(pattern)+1
for i in range(last_check_index):
compare_pattern = text[i:i+len(pattern)]
mismatches = hamming_distance(compare_pattern, pattern)
if d >= mismatches:
positions.append(i)
return positions
def approximate_pattern_count(text, pattern, d):
count = 0
last_check_index = len(text)-len(pattern)+1
for i in range(last_check_index):
compare_pattern = text[i:i+len(pattern)]
mismatches = hamming_distance(compare_pattern, pattern)
if d >= mismatches:
count += 1
return count
|
6b13ecb095f8c9a9d5bed414ab31776baddcee6f | ztnewman/python_morsels | /fix_csv.py | 367 | 3.65625 | 4 | #!/usr/bin/env python3
import csv
import sys
input_file = sys.argv[1]
output_file = sys.argv[2]
csv.register_dialect('pipes', delimiter='|')
with open(input_file, 'rt') as f1, open(output_file, 'wt') as f2:
reader = csv.reader(f1,dialect='pipes')
writer = csv.writer(f2)
for row in reader:
print(row)
writer.writerow(row)
|
1dfe57869fe165e4424c5c178e08108a14d1190f | liketheflower/mypy_practise | /code/basic_checking/wrong_type.py | 725 | 3.828125 | 4 | from typing import List
# correct
ib:int = 1
# wrong
ia:int = 1.3
# correct
is_trueb: bool = True
# wrong
is_truec: bool = 1
is_truea: bool = 1.2
# correct
a:List = []
# wrong
aa:List = {}
"""
wrong_type.py:5: error: Incompatible types in assignment (expression has type "float", variable has type "int")
wrong_type.py:7: error: Incompatible types in assignment (expression has type "int", variable has type "bool")
wrong_type.py:10: error: Incompatible types in assignment (expression has type "float", variable has type "bool")
wrong_type.py:14: error: Incompatible types in assignment (expression has type "Dict[<nothing>, <nothing>]", variable has type "List[Any]")
Found 4 errors in 1 file (checked 1 source file)
"""
|
172428ace0812eb494df7f22839f9b7fb402b9af | nekapoor7/Python-and-Django | /Python/Python Concepts/StringPrograms/StringLength.py | 138 | 4.21875 | 4 | """Write a Python program to calculate the length of a string."""
import re
text = input()
l = re.findall(r'[a-zA-Z]',text)
print(len(l)) |
3f54a0975a77e2810975147f09c003d7c63db848 | ryugahidiky/my_utils | /Codejam/Qualification Round 2020/Parenting Partnering Returns/ParentingPartneringReturns.py | 754 | 3.734375 | 4 | def solve(unsorted_list):
sorted_list = sorted(unsorted_list, key=lambda tup: tup[0])
res="C"
c=sorted_list[0]
j=[0,0]
for i in sorted_list[1:]:
current_task=i
if current_task[0]>=c[1]:
res+="C"
c=current_task
else:
if current_task[0]>=j[1]:
res+="J"
j=current_task
else:
return "IMPOSSIBLE"
result=""
for i in unsorted_list:
result+=res[sorted_list.index(i)]
sorted_list[sorted_list.index(i)]=[0,0]
return result
if __name__ == '__main__':
t = int(input())
for x in range(1, t + 1):
matrix=[]
n=int(input())
#reading the matrix:
for i in range(n):
a=[int(x) for x in input().split()]
matrix.append(a)
#solving
print("Case #{}: {}".format(x, solve(matrix))) |
3aa86d5a44e69d55973b9aca1cae2c7a54fe7a40 | AnchitSajalDhar/python-course | /study2.py | 257 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 23 20:18:23 2020
@author: Hp
"""
str1=input("input the string to be reversed")
word=str1.split()
word.sort()
#str1.sort()
print(str1)
print("the sorted string is ")
for i in word:
print(i)
|
d7d37d8798eb9b90875f3c431d4f5df2562b037a | Du-Arte/AprendiendoPython | /Tablas.py | 327 | 3.859375 | 4 | for i in range(1,11):
Titulo="Tabla del {}"
print(Titulo.format(i))
#usamos for y else
for j in range(1,11):
#i es numero base y j el elemento de la tabla
salida="{} x {} = {}"
print(salida.format(i,j,i*j))
else:
#al acabar saltamos de linea
print()
|
263095dd0d51156d096ca9b1515a95c0703342d3 | rahul-art/computer_vision_classification | /cnn.py | 3,018 | 3.5625 | 4 | from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
'''
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 3, activation = 'softmax'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])'''
import keras
'''
model = Sequential()
model.add(Conv2D(6, kernel_size=(3, 3), activation='relu', input_shape=(64, 64, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(16, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(120, activation='relu'))
model.add(Dense(84, activation='relu'))
model.add(Dense(3, activation='softmax'))
model.summary()
model.compile(loss="categorical_crossentropy", optimizer="Adam", metrics=['accuracy'])
# Part 2 - Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('/home/rahul/Downloads/dlcvnlp/cnn/dogcat_new/familyimage',
target_size = (64, 64),
batch_size = 32)
test_set = test_datagen.flow_from_directory('/home/rahul/Downloads/dlcvnlp/cnn/dogcat_new/familyimage',
target_size = (64, 64),
batch_size = 32)
mod = model.fit_generator(training_set,
steps_per_epoch = 200,
epochs = 1,
validation_data = test_set,
validation_steps = 100)
training_set.class_indices
model.save("familylenet1.h5")
print("Saved model to disk")'''
#Part 3 - Making new predictions
from keras.models import load_model
model=load_model('familylenet1.h5')
import numpy as np
from keras.preprocessing import image
test_image = image.load_img('r.jpg', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = model.predict(test_image)
#training_set.class_indices
if result[0][0] == 1:
prediction = 'anna'
print(prediction)
if result[0][1]==1:
prediction = 'lion'
print(prediction)
if result[0][2]==1:
prediction = 'rahul'
print(prediction) |
dc3b8d9262c21fa4b0ddd6189dbf91296005c82f | marko-knoebl/python-course | /einheit6/bank_account.py | 992 | 3.53125 | 4 | import datetime
class BankAccount(object):
def __init__(self, acc_nr, owner, inital_balance):
self.acc_nr = acc_nr
self.owner = owner
self.inital_balance = inital_balance
self.transactions = []
def add_transaction(self, date, amount):
# create new transaction
new_transaction = {'date': date, 'amount': amount}
self.transactions.append(new_transaction)
def add_transaction_interactive(self):
new_transaction_amout = float(raw_input('Neue Transaktion:'))
new_transaction_date = datetime.date.today().isoformat()
new_transaction = {'date': new_transaction_date, 'amount': new_transaction_amout}
self.transactions.append(new_transaction)
my_account = BankAccount('1045433', 'Marko Knoebl', 10)
print my_account.transactions
my_account.add_transaction('2016-04-30', -5)
my_account.add_transaction('2016-02-10', 10)
my_account.add_transaction_interactive()
print my_account.transactions
|
ae0d6dec6ddc7a8fdc2262f841332cd25e20f98b | DavidBitner/Aprendizado-Python | /Curso/ExMundo3/Ex115Modulo.py | 2,087 | 3.96875 | 4 | def linha():
print('-' * 40)
def limpar():
return print('\033[m', end='')
def verde():
return print('\033[32m', end='')
def vermelho():
return print('\033[31m', end='')
def menu():
linha()
print('MENU PRINCIPAL'.center(40))
linha()
while True:
print(f'1 - Ver pessoas cadastradas')
print(f'2 - Cadastrar nova Pessoa')
print(f'3 - Sair do Sistema')
linha()
try:
vermelho()
opcao = int(input('Sua Opção: '))
limpar()
linha()
except ValueError:
limpar()
linha()
vermelho()
print('ERRO! Você não digitou um numero!')
limpar()
linha()
else:
if opcao < 1 or opcao > 3:
vermelho()
print('ERRO! Numero Inválido!')
limpar()
linha()
elif opcao == 1:
listar()
linha()
elif opcao == 2:
adicionar()
linha()
elif opcao == 3:
linha()
print('Saindo do sistema... Até logo!'.center(40))
linha()
break
def adicionar():
print('ADICIONANDO NOVA PESSOA'.center(40))
linha()
txt = open('Ex115Modulo.txt', 'a+')
nome = str(input('Digite o nome: ')).strip().capitalize()
idade = leiaInt('Digite a idade: ')
txt.write(f'{nome}'.ljust(30))
txt.write(f'{idade} anos'.rjust(10))
txt.write('\n')
txt.close()
def listar():
print('PESSOAS CADASTRADAS'.center(40))
linha()
txt = open('Ex115Modulo.txt', 'r')
if txt.mode == 'r':
conteudo = txt.read()
print(conteudo)
def leiaInt(txt):
while True:
try:
numero = int(input(txt))
except ValueError:
linha()
vermelho()
print('ERRO: por favor, digite um numero inteiro válido.')
limpar()
linha()
else:
break
return numero
|
9cc5c7f8e13b5dd37f9a968f59ac535ded89d3d8 | DreamingLi/Blog-back-end | /test.py | 363 | 3.90625 | 4 | def is_between_and_even(test_value, low_value, high_value):
if low_value <= test_value <= high_value:
if not test_value % 2:
return True
else:
return False
else:
return False
print(is_between_and_even(23, 22, 24))
print(is_between_and_even(22.0, 22.0, 24.5))
print(is_between_and_even(21.99, 22.0, 24.5))
|
0d1a1176a9bbc701b20828596b174dcc1751cac0 | nickdinhh1998/password-generator | /Password generator.py | 542 | 4 | 4 | import string
import random
user_choice = None
while user_choice == None:
try:
user_choice = int(input('How many characters you want to have in your password:'))
if user_choice < 6:
print('Password must be with 6 characters at least')
user_choice = None
except ValueError:
user_choice = None
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(1,user_choice+1))
print('Your password is {}'.format(password))
|
8a60ec7dd14afad2a51fbcd98320c024d132b0a9 | zingpython/Intro_python_1 | /units_of_time_again.py | 488 | 3.671875 | 4 | # In this exercise you will reverse the process
# described in the previous exercise.
# Develop a program that begins by reading a number
# of seconds from the user. Then your program should
# display the equivalent amount of time in the
# form D:HH:MM:SS, where D, HH, MM, and SS represent
# days, hours, minutes and sec- onds respectively.
# The hours, minutes and seconds should all be formatted so that
# they occupy exactly two digits, with a leading 0 displayed if necessary. |
4fb907cf9eb8ff79126fc2505cf8423460a01a33 | 19platta/misguided-the-game | /game.py | 19,643 | 3.71875 | 4 | import pygame
import character
import environment
import os
from pygame.locals import (
K_ESCAPE,
KEYDOWN,
QUIT,
)
class Game:
"""
Class representing the Game state, controlling the interactions between
the other classes, and running the game.
Attributes:
screen: the window to draw visuals on
clock: Pygame clock object, keeps track of ingame time
rooms: a list of all the room instances in the game
current_room: the room instance the player is currently in
backgrounds: a list of all the background instances in the game
current_background: the background instance currently being displayed
player: player controlled character, instance of the Player class
guide: starts as None, becomes instance of Guide at appropriate
point in the story
"""
def __init__(self):
"""
Initialize an instance of the Game class.
"""
# 500 / 250 / 125 room height
SCREEN_HEIGHT = 700 # 350 or 175 or 88
SCREEN_WIDTH = 1080 # 540 or 270 or 135
# Set up the drawing window
self.screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
pygame.key.set_repeat(100, 100)
# Set up the clock to limit ticks per second
self.clock = pygame.time.Clock()
# Set up all the rooms the game will cycle through and
# initialize the first as the current room
self.rooms = [
environment.Room('lightforestentrance'),
environment.Room('lightforest1'),
environment.Room('lightforest2'),
environment.Room('darkforestcampfire'),
environment.Room('darkforest1'),
environment.Room('maze'),
environment.Room('innoutside'),
environment.Room('innlobby')
]
# Set up all the backgrounds the game will cycle through and
# initialize the first as the current background
self.current_room = self.rooms[0]
self.backgrounds = [
environment.Background('daysky'),
environment.Background('nightsky'),
environment.Background('twilightsky')
]
self.current_background = self.backgrounds[0]
# Initialize the player, the guide (properly initialized later)
# and a list that can be used to store conversations
self.player = character.Player('player')
self.guide = None
self.conversations = []
def intro(self):
"""
Play an introduction animation at the beginning of the game.
"""
intro = pygame.image.load("Media/wallpaper/copepod-studios.png")
credit = True
# Fade in of copepod studios logo
for i in range(225):
intro.set_alpha(i)
self.screen.blit(intro, [265, 200])
pygame.display.flip()
self.clock.tick(35)
# Delay for a short time
self.clock.tick(60)
# Main opening screen of Misguided
filelist = sorted(os.listdir('Media/wallpaper/introsequence'))
for file in filelist:
intro = pygame.image.load('Media/wallpaper/introsequence/' + file)
self.screen.blit(intro, [0, 0])
pygame.display.flip()
self.clock.tick(6)
pygame.event.clear()
# Wait for keypress to continue to the game
while credit is True:
for event in pygame.event.get():
if event.type == KEYDOWN:
credit = False
self.clock.tick(30)
def update(self):
"""
Update all game components
"""
self.current_background.update(self.screen)
self.current_room.update(self.screen, self.player)
self.player.update(self.screen)
if self.guide is not None:
self.guide.update(self.screen, self.player)
def run(self):
"""
Run the game.
This function contains the main game loop and game logic. It will run
the game until the player quits.
"""
# First run the intro
self.intro()
running = True
# Spawn the player
self.player.spawn(self.current_room, 'initial')
# Main game loop
while running:
# Look at every event in the queue
for event in pygame.event.get():
# Did the user hit a key?
if event.type == KEYDOWN:
# Was it the Escape key? If so, stop the loop.
if event.key == K_ESCAPE:
running = False
# Did the user click the window close button?
# If so, stop the loop.
elif event.type == QUIT:
running = False
# Run the room specific functions through room manager, and handle
# the case in which the player tries to exit the room
if self.room_manager() and (self.player.is_exiting() is not None):
rooms = self.player.is_exiting()
self.current_room = [room for room in self.rooms
if room.get_name() == rooms[0]][0]
self.player.spawn(self.current_room, rooms[1])
# Move the player based on input, then update everything
self.player.move(pygame.key.get_pressed())
self.update()
# These lines are for debugging boundaries
# self.current_room.draw_objects(self.screen)
# self.player.draw_rect(self.screen)
# Update the display based on the screen
pygame.display.flip()
self.screen.fill((0, 0, 0))
# Control the game ticks per second
self.clock.tick(30)
# Done! Time to quit.
pygame.quit()
def conversation(self, p1, p2):
"""
Have a conversation between two characters where neither interrupts
the other.
Assumes that self.conversations is a list, and that its elements
have been set to contain the lines the characters will say, beginning
with the first speaker's first line.
Args:
p1: the first character to speak
p2: the second character to speak
"""
# Check to see if there is anything to say
if len(self.conversations) > 0:
# Make sure the characters don't talk over each other
if not p2.is_speaking() and not p1.is_speaking():
if len(self.conversations) % 2 == 1:
p1.say_once(self.conversations[0])
del self.conversations[0]
else:
p2.say_once(self.conversations[0])
del self.conversations[0]
return True
else:
return False
def room_manager(self):
"""
Run the correct room function based on which room the character is in.
"""
if self.current_room == self.rooms[0]:
return self.room0()
elif self.current_room == self.rooms[1]:
return self.room1()
elif self.current_room == self.rooms[2]:
return self.room2()
elif self.current_room == self.rooms[3]:
return self.room3()
elif self.current_room == self.rooms[4]:
return self.room4()
elif self.current_room == self.rooms[5]:
return self.room5()
elif self.current_room == self.rooms[6]:
return self.room6()
elif self.current_room == self.rooms[7]:
return self.room7()
def room0(self):
"""
Run first room of the game.
In this room the player meets the tutorial NPC who tells them how to
interact with objects.
Returns:
True if the NPC has finished talking and the room is clear, False
otherwise
"""
tutorial_man = self.current_room.npcs[0]
# If the player passes the initial boundary, tutorial man walks
# over and speaks
if (self.player.get_pos()[0] > 200 or tutorial_man.get_pos()[0] < 1090)\
and tutorial_man.get_pos()[0] > 500:
tutorial_man.move('left')
tutorial_man.say_once('Don\'t go into that forest, it\'s big and '
'spooky!')
# If the player starts heading into the forest, tutorial man speaks
if self.player.get_pos()[0] > 600 and tutorial_man.get_pos()[0] <= 500\
and tutorial_man.is_speaking() is False:
tutorial_man.say_once('If you must go into the forest, '
'at least take this advice: if you'
' see anything that highlights in yellow, '
'you can interact with it by pressing '
'spacebar')
# If the player walks up to tutorial man, he speaks
if tutorial_man.is_speaking() is False and \
self.player.collide(tutorial_man):
tutorial_man.say('if you see anything that highlights in yellow,'
' you can interact with it by pressing spacebar')
# If tutorial man is not speaking, the player can exit
if self.current_room.is_clear() and tutorial_man.is_speaking() is False:
return True
return False
def room1(self):
"""
Run second room of the game.
In this room, the player walks through unthreatening forest.
Mostly for establishment.
Returns:
True if the room is clear, False otherwise.
"""
if self.current_room.is_clear():
return True
return False
def room2(self):
"""
Run third room of the game.
In this room, the player discovers a mushroom ring. When they interact
with it, it teleports them to a different world.
Returns:
True if the player has interacted with the mushroom ring and the
teleportation animation has played, False otherwise.
"""
if self.current_room.is_clear():
self.player.spotlight_on()
# Iterate through the teleport animation, and freeze the player
# in place so they can't move
for filename in sorted(os.listdir('Media/misc/teleport')):
self.player.spotlight_image(os.path.join('Media/misc/teleport',
filename))
self.update()
pygame.display.flip()
pygame.time.wait(200)
self.player.spotlight_off()
return True
return False
def room3(self):
"""
Run the fourth room of the game.
In this room, the player finds the guide, initializing an instance of
the Guide class, and talks to a turtle who explains how to open the
guide. The turtle also explains that to get home the player needs to
find another mushroom ring to get home, establishing the goal.
Returns:
True if the player has picked up the guide and finished talking to
the turtle, False otherwise.
"""
turtle = self.current_room.npcs[0]
self.current_background = self.backgrounds[2]
# If the player walks up to the turtle, a conversation happens
if self.player.collide(turtle):
self.conversation(turtle, self.player)
# If the room is clear the player has picked up the book. In this
# case make the turtle walk out and speak. Also update the guide
# with some info
if self.rooms[3].is_clear():
if len(self.rooms[3].interactables) > 0:
del self.rooms[3].interactables[0]
self.guide = environment.Guide()
self.guide.update_text()
self.conversations = [
'Oh look, it\'s a book! I bet you can open it by pressing'
' TAB. Those guides are never wrong but I wouldn\'t trust'
' it if I were you.',
'Where am I?',
'Well you\'re here, obviously. You just appeared. You must'
' have come through the mushroom ring.',
'How do I get back home?',
'I think you\'ll have to find another mushroom ring. '
'They only work once you know.'
]
if turtle.get_pos()[0] < 490:
turtle.move('right')
turtle.say_once('What have you got there?')
# If the conversation is empty, it has already happened, so allow
# the player to leave
if not self.conversations:
return True
return False
def room4(self):
"""
Run the fifth room of the game.
In this room, the player meets another turtle who needs help looking
for his keys in the leaf pile. The player can interact with multiple
leaf piles, but a trapdoor exit is hidden under one pile that the
player "falls" through.
Returns:
True if the player has interacted with the trapdoor leaf pile,
False otherwise
"""
self.guide.update_text(2)
self.current_background = self.backgrounds[2]
turtle = self.current_room.npcs[0]
# If the player walks up to the turtle, he speaks
if self.player.collide(turtle) and not turtle.is_speaking():
turtle.say('Help help I lost my keys! They must be in one'
' of these leaf piles but I\'m too small to search'
' all of them. Will you help me find them?')
# If the player has interacted with the hidden trap door
# then the game stops for a second to show the trap door,
# then exits to the next level
if self.rooms[4].interactables[0].is_end_state():
self.update()
pygame.display.flip()
pygame.time.wait(1000)
return True
return False
def room5(self):
"""
Run the sixth room of the game.
This room is a maze the player must solve in the dark, with only a
small transparent circle of illumination around them. They must first
find the turtle's key, which is hidden in the maze, then find the exit.
The player's chatbox provides hints as to how to proceed.
Returns:
True if the player has collected the key and is at the maze exit,
False otherwise
"""
self.guide.update_text(3)
# Reset the player's spotlight and turn it on because the room
# is dark
self.player.spotlight_image()
self.player.spotlight_on()
self.player.say_once('Oof! I fell down a hole. I wonder if my guide'
' has any advice.')
# If the player has picked up the key, the room is clear
# and can be exited. Also the player speaks when they pick
# up the key
if self.current_room.is_clear():
if len(self.current_room.interactables) > 0:
del self.current_room.interactables[0]
self.player.inventory.append('key')
self.player.say_once('Found the key! Now I just have to'
' get out of this maze.')
return True
return False
def room6(self):
"""
Run the sixth room of the game.
In this room, the player attempts to enter the inn. THey are not able
to at first, but the turtle enters and upon returning his key, he
provides the player with a megaphone, allowing them to shout loudly
enough to be heard in the inn.
Returns:
True if the megaphone is in the player's inventory and the player
is at the exit, False otherwise
"""
turtle = self.current_room.npcs[0]
self.guide.update_text(4)
self.current_background = self.backgrounds[1]
self.player.spotlight_off()
# Check to see if the player is at the inn door
if 600 < self.player.get_pos()[0] < 700 and \
self.player.get_pos()[1] < 470:
# If the player doesn't have the megaphone yet, the guide will
# update with a hint
if 'megaphone' not in self.player.inventory:
self.player.say_once('Is anybody there?')
self.guide.update_text(5)
if not self.player.is_speaking():
self.player.say_once('Maybe the guide can help.')
# If the player has the megaphone, the stage is complete and the
# room is clear
else:
return True
# If the guide has given its hint, have the turtle walk in and set up
# the conversation
if not self.player.is_speaking() and turtle.get_pos()[0] < 300 \
and self.guide.get_index() == 5:
turtle.move('right')
self.conversations = [
'Hey! Did you find my key?',
' I sure did, here you go.',
'Thanks! I don\'t have much to give you but you can have this'
' old megaphone I found lying around if you want.'
]
# If the player collides with the turtle, have the conversation and
# spawn the megaphone in the right place
if self.player.collide(turtle):
self.conversation(turtle, self.player)
if not (self.player.is_speaking() and turtle.is_speaking()):
if len(self.current_room.interactables) > 0 and \
len(self.conversations) == 0:
self.current_room.interactables[0].place(300, 550)
# If the megaphone has been interacted with and is still in the room,
# remove it from the room and add to the player's inventory
# Also remove the key from the inventory
if self.current_room.is_clear() and \
len(self.current_room.interactables) > 0:
del self.current_room.interactables[0]
del self.player.inventory[self.player.inventory.index('key')]
self.player.inventory.append('megaphone')
return False
def room7(self):
"""
Run the final room of the game.
This is the final room so far, though we hope to add more in future.
In this room the player enters the lobby of the inn and interacts with
the turtle innkeeper. The innkeeper tells them they will be safe here
until they set out again and thanks them for playing the first chapter,
indicating that this first part of the game is over.
To be continued...
Returns:
True if the player has interacted with the innkeeper and the
innkeeper has made his speech, False otherwise.
"""
innkeeper = self.current_room.npcs[0]
# If the player walks up to the turtle, he speaks
if self.player.collide(innkeeper):
innkeeper.say_once('Welcome to the inn! You\'ll be safe here until'
' you start on the next part of your journey.'
' Thanks for playing chapter one! Come back soon'
' for more adventures.')
return True
return False
|
abff64a57d80c7a204433579db61ebf73313e0e6 | IngridDilaise/programacao-orientada-a-objetos | /listas/lista-de-exercicio-02/questao4.py | 250 | 3.859375 | 4 |
print("Digite suas quatros notas bimestrais")
nota1=int(input("primeira nota:"))
nota2=int(input("segunda nota:"))
nota3=int(input("terceira nota:"))
nota4=int(input("quarta nota:"))
media=(nota1+nota2+nota3+nota4)/4
print("A sua média é:",media) |
85977f09ab0cf9286a06155cededcf1d21d1e386 | a18499/Python | /nest_list.py | 425 | 3.90625 | 4 | movies = ["The Holy Grailliam","1975","Terry Jones & Terry Gilliam","91",
["Graham Chapman",["Michael Palin","John Cleese","Terry Gilliam","Eric Idle","Terry Jones"]]]
print(movies)
for each_item in movies:
if isinstance(each_item,list):
for each_nest_item in each_item:
if isinstance(each_nest_item,list):
for each_inter_nest_item in each_nest_item:
print(each_inter_nest_item)
else :
print(each_nest_item)
else :
print(each_item)
|
bb15daa5d2b4c52c1db4cd08ef8d03b5fbdca876 | h-jaiswal/mini-projects | /TCS OOPS based on py3/main.py | 1,263 | 3.71875 | 4 | class Table:
def __init__( self, tableNo, waiterName, status):
self.tableNo = tableNo;
self.waiterName = waiterName;
self.status = status
def findWaiterWiseTotalNoOfTables(tableList):
waiterNameList = {}
for table in tableList:
if table.waiterName not in waiterNameList:
waiterNameList[ table.waiterName ] = 0
else:
waiterNameList[ table.waiterName ] += 1
return waiterNameList
def findWaiterNameByTableNo(tableList, tableNo):
for table in tableList:
if table.tableNo == tableNo:
return table.waiterName
return None
def main():
numTable = int(input())
tableList = []
for i in range(numTable):
tableNo = int(input())
waiterName = input()
status = input()
tableList.append( Table(tableNo, waiterName, status) )
reqTableNo = int(input())
reqWaiterName = findWaiterNameByTableNo(tableList, reqTableNo)
reqWaiterNameList = findWaiterWiseTotalNoOfTables(tableList)
for waiterName, tableCount in reqWaiterNameList.items():
print(waiterName+"-"+str(tableCount))
print("No Table Found" if reqWaiterName == None else reqWaiterName)
if __name__ == "__main__":
main()
|
712579cf85063e55aae683ed768fb3e71f190026 | danielfess/Think-Python | /binomial.py | 504 | 3.828125 | 4 | def binomial_coeff(n,k):
"""Compute the binomial coefficient "n choose k".
n: number of trials
k: number of successes
returns: int
"""
#x = 1 if k==0 else 0
return binomial_coeff(n-1,k) + binomial_coeff(n-1,k-1) if k>0 and n>0 else (1 if k==0 else 0)
print(binomial_coeff(0,0))
print(binomial_coeff(0,1))
print(binomial_coeff(1,0))
print(binomial_coeff(1,1))
print(binomial_coeff(1,2))
print(binomial_coeff(3,2))
print(binomial_coeff(5,3))
print(binomial_coeff(4,2))
print(binomial_coeff(2,0)) |
ed8d4a9f7521c340309d725b4eb33c4a423a508c | rpiga/Runestone | /thinkcspy/ch08/Excercise 11 - ex_7_19.py | 975 | 3.609375 | 4 | import image
FACTOR = 2
def enlargeImage(origImage, factor = FACTOR):
origW = origImage.getWidth()
origH = origImage.getHeight()
#print(">", origW, origH)
enlargedImage = image.EmptyImage(factor * origW,
factor * origH)
new_index = 0
for w in range(0, origW):
for h in range(0, origH):
origPixel = origImage.getPixel(w, h)
for new_w in range(w * FACTOR,
(w * FACTOR) + FACTOR):
for new_h in range(h * FACTOR,
(h * FACTOR) + FACTOR):
enlargedImage.setPixel(new_w, new_h, origPixel)
new_index = new_index + FACTOR
return enlargedImage
img = image.Image("luther.jpg")
win = image.ImageWin(img.getWidth() * FACTOR,
img.getHeight() * FACTOR)
new_img = enlargeImage(img)
new_img.draw(win)
win.exitonclick()
|
dde04a82e454bdad6300b902cd733c761cf1d93a | vishukamble/Python-Practice | /Basics/stringCompression2.py | 568 | 3.953125 | 4 | # __author__ = Vishu Kamble
# """ A python program to find how many times a character is repeated in sing """
def compressed(s):
length = len(s)
result = ""
if length == 0:
return
if length == 1:
return s+"1"
else:
count = 1
i = 1
while i < length:
if s[i] == s[i-1]:
count += 1
else:
result += s[i-1] + str(count)
count = 1
i+=1
result += s[i-1] + str(count)
return result
print compressed("AAAABBBCCCCCDDDD") |
7e32eafb41375b19703517dfe956cf81aced8d4a | KevinCodez/Snake-Game | /main.py | 1,117 | 3.515625 | 4 | from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time
screen = Screen()
h = 600
w = 600
screen.setup(height=h, width=w)
screen.bgcolor("black")
screen.title("Snake")
screen.tracer(0)
snake = Snake()
food = Food()
scoreboard = Scoreboard()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
snake.move()
# Detect collision with food
if snake.head.distance(food) < 15:
food.eat()
snake.extend()
scoreboard.increase_score()
# Detect collision with wall
if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() < -280 or snake.head.ycor() > 280:
scoreboard.reset_game()
snake.reset_snake()
# Detect collision with tail
for square in snake.snake_body[1:]:
if snake.head.distance(square) < 10:
scoreboard.reset_game()
snake.reset_snake()
screen.exitonclick()
|
92c8728b9333869c8f9d073264f93d796340f9b9 | Geoffrey-Kong/CCC-Solutions | /'06/Junior/CCC '06 J1 - Canadian Calorie Counting.py | 556 | 3.546875 | 4 | a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a == 1:
c1 = 461
elif a == 2:
c1 = 431
elif a == 3:
c1 = 420
elif a == 4:
c1 = 0
if b == 1:
c2 = 100
elif b == 2:
c2 = 57
elif b == 3:
c2 = 70
elif b == 4:
c2 = 0
if c == 1:
c3 = 130
elif c == 2:
c3 = 160
elif c == 3:
c3 = 118
elif c == 4:
c3 = 0
if d == 1:
c4 = 167
elif d == 2:
c4 = 266
elif d == 3:
c4 = 75
elif d == 4:
c4 = 0
txt = "Your total Calorie count is {}."
totalcalories = c1 + c2 + c3 + c4
print(txt.format(totalcalories))
|
e143d7f6a0b63609e1866f29f54cffac806c4c14 | shmehta21/DS_Algo | /bt_to_bst.py | 1,115 | 4.0625 | 4 | '''
1.) Create an array after In-order traversal
2.) Sort the in-order traversal array
3.) Iterate over the in-order array and sorted in-order array together
and replace elements from sorted_arr to in_order arrat
'''
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def bt_to_bst(root):
inorder_arr = []
inorder_traversal(root, inorder_arr)
sorted_arr = sorted(inorder_arr)
print(f'Sorted arr => {sorted_arr}')
for i in range(len(sorted_arr)):
inorder_arr[i] = sorted_arr[i]
print(inorder_arr)
def inorder_traversal(root,inorder_arr):
if root.left:
inorder_traversal(root.left,inorder_arr)
inorder_arr.append(root.data)
if root.right:
inorder_traversal(root.right, inorder_arr)
print(f'In order arr => {inorder_arr}')
return inorder_arr
if __name__ == "__main__":
root = Node(0)
root.left = Node(1)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.left.left.right = Node(6)
root.left.left.right.right = Node(8)
root.right.left = Node(5)
root.right.left.right = Node(7)
bt_to_bst(root) |
a058efdfcef74e6abbb46f30f9d24c66355a0ed0 | anipshah/geeksforgeeks_problems | /CommonElements.py | 535 | 4.0625 | 4 | # Find common elements in three sorted arrays
def common(l1,l2,l3):
n1=len(l1)
n2=len(l2)
n3=len(l3)
i,j,k = 0,0,0
res=[]
while i<n1 and j<n2 and k<n3:
if l1[i] == l2[j] and l2[j] == l3[k]:
res.append(l1[i])
i+=1
j+=1
k+=1
elif l1[i]<l2[j]:
i+=1
elif l2[j]<l3[k]:
j+=1
else:
k+=1
return res
l1=[2,3,4,5]
l2=[1,2,3]
l3=[1,2,3,4,5,6,7]
print(common(l1,l2,l3)) # [2,3]
|
4672744d0eac8a92369e9bc272e83af87235aae5 | fang-ren/algorithm_practice | /CareerCup/4.py | 480 | 3.875 | 4 | """
8/17/2017
Author: Fang Ren
"""
"""
divide 2 numbers without using / or %
"""
def dividing(a, b):
ans = 0
if b == 0 and a != 0:
return "Infinity"
if a == 0:
return 0
if a*b > 0:
sign = '+'
elif a * b < 0:
sign = '-'
a = abs(a)
b = abs(b)
while a >= b:
a = a-b
ans += 1
if sign == '+':
return ans, a
if sign == '-':
return -ans, a
print dividing(11, -5), 11/(-5), 11%(-5)
|
424e65ec4c65d7da6e7903d30eff9401405c65f2 | gabo-cs-zz/Python-Exercism | /Side Exercises/darts/darts.py | 297 | 3.75 | 4 | from math import sqrt
def score(x, y):
distance = sqrt(x**2 + y**2)
if landed(distance, 0, 1):
return 10
if landed(distance, 1, 5):
return 5
if landed(distance, 5, 10):
return 1
return 0
def landed(number, min, max):
return min <= number <= max
|
033750a6e734a68421b532b43d35407374f69a74 | brianchiang-tw/leetcode | /2020_November_Leetcode_30_days_challenge/Week_3_Search in Rotated Sorted Array II/by_binary_search.py | 2,612 | 4.25 | 4 | '''
Description:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
Follow up:
This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
Would this affect the run-time complexity? How and why?
'''
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> bool:
# ------------------------------------------------------
def helper(left, right):
if left > right:
return False
mid = left + (right - left) // 2
if nums[mid] == target:
return True
else:
if nums[mid] < nums[right]:
# right half is sorted
if nums[mid] < target <= nums[right]:
return helper(left=mid+1, right=right)
else:
return helper(left=left, right=mid-1)
elif nums[mid] > nums[right]:
# left half is sorted
if nums[left] <= target < nums[mid]:
return helper(left=left, right=mid-1)
else:
return helper(left=mid+1, right=right)
else:
# repeated at mid and right, discard the rightmost element
return helper(left=left, right=right-1)
# ------------------------------------------------------
return helper(left=0, right=len(nums)-1)
## Time Complexity: O( n )
#
# The overhead in time is the cost of binary search + linear search, which is of O( n )
## Sapce Complexity: O( n )
#
# The overhead in space is the storage for recursion call stack, which is of O( n )
import unittest
class Testing( unittest.TestCase ):
def test_case_1( self ):
result = Solution().search( nums = [2,5,6,0,0,1,2], target = 0 )
self.assertEqual(result, True)
def test_case_2( self ):
result = Solution().search( nums = [2,5,6,0,0,1,2], target = 3 )
self.assertEqual(result, False)
if __name__ == '__main__':
unittest.main() |
1b6a7d2cdf65f6c2cafa1761c0af8117e6755478 | WillPowerCraft/my-first-repository | /int_float_min_max_abs.py | 2,478 | 3.703125 | 4 | # Целочисленный тип данных
# x = 1 - целочисленный литерал, питон присваивает ему int
# Ниже представлены все целочисленные операторы
# a = 13
# b = 7
#
# total = a + b
# diff = a - b
# prod = a * b
# div1 = a / b
# div2 = a // b
# mod = a % b
# exp = a ** b
#
# print(a, '+', b, '=', total)
# print(a, '-', b, '=', diff)
# print(a, '*', b, '=', prod)
# print(a, '/', b, '=', div1)
# print(a, '//', b, '=', div2)
# print(a, '%', b, '=', mod)
# print(a, '**', b, '=', exp)
#
# # В Python размер числа ограничен лишь производительностью компьютера
#
# atom = 10 ** 80 # количество атомов во вселенной
# print('Количество атомов =', atom)
#
# # Для удобного чтения чисел можно использовать нижнее подчеркивание
# num1 = 25_000_000
# num2 = 25000000
# print(num1)
# print(num2)
#
# # Числа с плавающей точки или дробные числа представлены типом данных - float
# e = 2.71828 # литерал с плавающей точкой
# pi = 3.1415 # литерал с плавающей точкой
#
# # Арифметические операторы для дробных чисел
# a = 13.5
# b = 2.0
#
# total = a + b
# diff = a - b
# prod = a * b
# div = a / b
# exp = a ** b
#
# print(a, '+', b, '=', total)
# print(a, '-', b, '=', diff)
# print(a, '*', b, '=', prod)
# print(a, '/', b, '=', div)
# print(a, '**', b, '=', exp)
#
# # Преобразование числа с плавающей точкой
# # Питон может автоматически преобразовать целое число в дромное, но не наоборот
# # Преобразование дробного числа в целое происходит с округлением в сторону 0
# # Не путить преобразование с округлением
# num1 = 17.89
# num2 = -13.56
# num3 = int(num1)
# num4 = int(num2)
# print(num3)
# print(num4)
#
# x = float(input())
# print(x - int(x))
# min max example 1
# a = max(3, 8, -3, 12, 9)
# b = min(3, 8, -3, 12, 9)
# c = max(3.14, 2.17, 9.8)
# print(a)
# print(b)
# print(c)
# abs - абсолютное число
# print(abs(10))
# print(abs(-7))
# print(abs(0))
# print(abs(-17.67)) |
b910f02a8b1d0d1bdfab05f0894bb261011d4874 | s3cret/py-basic | /process/multi-process/multiprocessing1.py | 638 | 3.90625 | 4 | '''multiprocessing1 doc
os.fork() will copy the current process
using which to create a child process
1> in parent process os.fork() returns the child process id
2> in the forked child process os.fork() returns 0
in this case, child process can retrieve parent process id
by calling os.getppid() function
'''
import os
if __name__ == '__main__':
pid = os.fork()
print('Process %s start ...' % os.getpid())
if pid == 0:
print('I am child process %s and my parent process is %s' % (os.getpid(), os.getppid()))
else:
print('I am the parent process %s and I have just created %s' % (os.getpid(), pid))
|
88590a5aa1c39ee64b6fdc2fe0725862c0dad696 | MarcusRainbow/Maze | /DijkstrasRats.py | 4,396 | 3.796875 | 4 | import random
from typing import List
from RatInterface import Rat, MazeInfo
from SimpleMaze import SimpleMaze, random_maze, render_graph
from Localizer import OneDimensionalLocalizer
class DijkstrasMazeInfo(MazeInfo):
def __init__(self, maze: List[List[int]]):
self.maze = maze
self.position = -1
self.direction = -1
def set_pos(self, pos: int, back: int, _directions: int, _rat: Rat):
self.position = pos
self.back = back
# Returns the current position in the maze
def pos(self) -> int:
assert self.position >= 0
return self.position
# Returns what would be the next position in the maze
# if we were to set off in the direction specified
# by turn (1..num_edges)
def peek(self, turn: int) -> int:
assert self.position >= 0
assert self.back >= 0
assert turn > 0
node = self.maze[self.position]
num_edges = len(node)
assert turn <= num_edges
direction = (turn + self.back) % num_edges
return node[direction]
class DijkstrasRat(Rat):
def __init__(self, end: int):
self.end = end
# Initially all nodes are unvisited. We set the distance to zero
# for the starting node, and omit all the others, to say that
# they are unvisited.
self.distance = {0: 0}
self.visited = set()
# The maze asks which way we want to turn. We use Dijkstra's
# algorithm to determine which way to go, where the
# heuristic distance is the number of nodes minus the pos.
def turn(self, directions: int, info: MazeInfo) -> int:
pos = info.pos()
distance = self.distance[pos]
# update any unvisited nodes with the distance from this node (STEP_SIZE)
STEP_SIZE = 1
min_dir = 0
min_distance = 0
unvisited = 0
for dir in range(1, directions + 1):
node = info.peek(dir)
if node not in self.visited:
unvisited = unvisited + 1
edge_distance = self.update_distance(node, distance + STEP_SIZE)
if min_dir == 0 or edge_distance < min_distance:
min_distance = edge_distance
min_dir = dir
# If all nodes have been visited, this is a problem
if unvisited == 0:
raise Exception("Hit a problem. We have visited all nodes and have nowhere to go")
# If all nodes but one have been visited (presumably the node we came from,
# as that clearly must have been open), mark this node as visited and return
elif unvisited == 1:
self.visited.add(pos)
# show where we are and how we are progressing
A = ord('A')
print("pos=%s directions=%i unvisited=%i next=%s next_distance=%i" %
(chr(pos + A), directions, unvisited, chr(min_dir + A), min_distance))
visited_as_str = { chr(v + A) for v in self.visited }
distance_as_str = { chr(n + A): d for (n, d) in self.distance.items() }
print(" visited: %s" % visited_as_str)
print(" distance: %s" % distance_as_str)
# Head in the direction of the shortest unvisited node
assert min_dir > 0
return min_dir
def update_distance(self, node: int, distance: int) -> int:
if node not in self.distance or self.distance[node] > distance:
self.distance[node] = distance
return self.distance[node]
# Returns the distance from start to end (-1 if we never got there)
def distance_to_end(self) -> int:
if self.end not in self.distance:
return -1
else:
return self.distance[self.end]
def test_dijkstras_rat():
SIZE = 6
maze = SimpleMaze(random_maze(0.5, OneDimensionalLocalizer(SIZE, 3)), False)
#print(maze)
render_graph(maze.maze(), "temp/dijkstras_maze")
rat = DijkstrasRat(SIZE)
info = DijkstrasMazeInfo(maze.maze())
MAX_ITER = 30
iter = maze.solve(rat, MAX_ITER, info)
print("test_dijkstras_rat solved in %i iterations" % iter)
print(" distance from start to end is %i" % rat.distance_to_end())
assert(iter > 0 and iter < MAX_ITER)
if __name__ == "__main__":
test_dijkstras_rat()
|
450c06a1c85ec20557945559273ca1a3349df48e | FrankieZhen/Lookoop | /LeetCode/otherQuestion/小米/Q1.py | 1,828 | 3.640625 | 4 | #!/bin/python
# -*- coding: utf8 -*-
import sys
import os
import re
"""
小米之家有很多米粉喜欢的产品,产品种类很多,价格也不同。比如某签字笔1元,某充电宝79元,某电池1元,某电视1999元等
假设库存不限,小明去小米之家买东西,要用光N元预算的钱,请问他最少能买几件产品?
输入
第1行为产品种类数
接下来的每行为每种产品的价格
最后一行为预算金额
输出
能买到的最少的产品的件数,无法没有匹配的返回-1
样例输入
2
500
1
1000
样例输出
2
"""
#请完成下面这个函数,实现题目要求的功能
#当然,你也可以不按照下面这个模板来作答,完全按照自己的想法来 ^-^
#******************************开始写代码******************************
# ac 71%
def solution(prices, budget):
"""最少能买几件"""
prices.sort()
prices = prices[::-1] # 从高到低排序
if budget == 0 or 0 in prices:
return -1
# print(prices)
ret = 0
for p in prices:
cur = budget // p
ret += cur
budget -= cur*p
if budget == 0:
break
if ret == 0 or budget != 0: # 没有匹配或者钱没有用完
ret = -1
return ret
#******************************结束写代码******************************
def inputs():
_prices_cnt = 0
_prices_cnt = int(input())
_prices_i=0
_prices = []
while _prices_i < _prices_cnt:
_prices_item = int(input())
_prices.append(_prices_item)
_prices_i+=1
_budget = int(input())
res = solution(_prices, _budget)
print(str(res) + "\n")
def test():
prices = [0]
budget = 0
ret = solution(prices, budget)
print(ret)
if __name__ == '__main__':
test() |
9e9fccfb40951024d44f8ec778015f40aa6cda71 | mave89/Python_Random | /retrieveTags_insideTags_BeautifulSoup.py | 993 | 3.8125 | 4 | import urllib
from BeautifulSoup import *
inp_url = raw_input('Enter web address:')
#position of the hyperlink from the top
inp_position = int(raw_input('Enter position:'))
#number of times the links need to be surfed
inp_count = int(raw_input('Enter count:'))
#loop to parse links depending on the inp_count given by user
for i in range(inp_count):
#read the first link first
fhand = urllib.urlopen(inp_url).read()
print 'Retrieving link',i,':',inp_url
#soupify the html received
soup = BeautifulSoup(fhand)
#find the list of anchor tags and parse the href content in them so that we...
#...can parse the next link
tags = soup('a') #tags will be a list
#get the href part of the anchor tag along with the contents
inp_url = tags[inp_position-1].get('href')
inp_content = tags[inp_position-1].contents[0]
#print the last value stored in inp_content, which is our required value
print 'Last url parsed was:',inp_url
print 'The content in the last url was:',inp_content |
e10e59df79a2f33026e413062438f4f71309ca22 | Krishna2709/DataStructures-and-Algorithms | /MergeSort.py | 664 | 4.0625 | 4 | # Merge Sort
# TimeComplexity - O(nlogn)
def Merge(a,b):
mergedArray = []
while len(a) != 0 and len(b) != 0 :
if a[0] < b[0]:
mergedArray.append(a[0])
a.remove(a[0])
else:
mergedArray.append(b[0])
b.remove(b[0])
if len(a) == 0:
mergedArray += b
else:
mergedArray += a
return mergedArray
def MergeSort(arr):
if len(arr) == 0 or len(arr) == 1:
return arr
else:
mid = int(len(arr)/2)
a = MergeSort(arr[:mid])
b = MergeSort(arr[mid:])
return Merge(a,b)
'''
arr = [44,34,52,12,22,84,90,20,32]
print(MergeSort(arr))
''' |
e4bb1a73d77abf18d69a2360913eebbf7dfe4871 | wats1787/pig_latin- | /pig_latin.py | 265 | 3.921875 | 4 | def pigLatin (word):
ww = word
list1 = ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'y', 'Y']
if ww[0] not in list1:
ww = ww[1:] + ww[0] + 'ay'
else:
ww = ww + 'yay'
return ww
print(pigLatin('input string here')
|
0de523f7218eb921e33b08a5053b5a0830224408 | szmn90/22.01.2021 | /zadanie2.py | 309 | 3.71875 | 4 | def ostatnielinie(f,n):
with open(f) as file:
print('Ostatnie ',n, 'linijek pliku to: ',f)
for line in (file.readlines()[-n:]):
print(line,end='')
name = input('Nazwa pliku tekstowego: ')
n=int(input('Ile ostatnich linijek? '))
print(ostatnielinie(name,n))
#działa |
1b0a1f19d5c47add41b338731462ed2b0655d54b | zhou-yi-git/PAT | /BasicLevel/1061 判断题.py | 441 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-03-20 10:12
# @Author : zhou
# @File : 1061 判断题
# @Software: PyCharm
# @Description:
n,m = map(int,input().split())
score = list(map(int,input().split()))
correct = input().split()
for i in range(n):
stu_score = 0
ans = input().split()
for j in range(len(ans)):
if ans[j] == correct[j]:
stu_score += score[j]
print(stu_score) |
09ac8953b26598270878d5d54b50639a1351f282 | EdwinKato/Space-Allocator | /src/fellow.py | 580 | 3.625 | 4 | """Class definition of Fellow
It inherits directly from Person
"""
from .person import Person
class Fellow(Person):
"""Fellow
"""
def __init__(self, first_name, last_name, wants_accommodation,
person_id, has_living_space=None, has_office=None):
super(
Fellow,
self).__init__(
first_name,
last_name,
wants_accommodation,
person_id,
has_living_space,
has_office)
self.set_type()
def set_type(self):
self._type = "fellow"
|
d9fec576532335eae7f88fd233efd8093c830b22 | SkillfulGuru/Webscraping-BeautifulSoup-NZX | /web1.py | 872 | 3.625 | 4 | from urllib.request import urlopen
from bs4 import BeautifulSoup
#html = urlopen('http://www.pythonscraping.com/pages/page1.html')
#bs = BeautifulSoup(html.read(), 'html5lib')
# print(bs.h1)
from urllib.error import URLError
from urllib.error import HTTPError
# try:
# html = urlopen('https://pythonscrapingthisurldoesnotexist.com')
# except HTTPError as e:
# print(e)
# except URLError as e:
# print('The server could not be found!')
# else:
# print('It Worked!')
def getTitle(url):
try:
html = urlopen(url)
except HTTPError as e:
return None
try:
bs = BeautifulSoup(html.read(), 'html.parser')
title = bs.body.h1
except AttributeError as e:
return None
return title
title = getTitle('http://www.pythonscraping.com/pages/page1.html')
if title == None:
print('Title could not be found')
else:
print(title) |
3a3d002ecc5f9268651a22f57201db73709a9bc6 | RankeTao/pythontest | /tuplex.py | 6,373 | 4.375 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
#ex12.1
def most_frequent(s):
"""Sorts the letters in s in reverse order of frequency.
s:string
Returns: list of letters
"""
hist = make_histogram(s)
t = []
for x, freq in hist.items():
t.append((freq, x))
t.sort(reverse = True)
# print(t)
res = []
for freq, x in t:
res.append(x)
return res
def make_histogram(s):
"""Make a map from letters to number of time they appear in s.
s:string
Returns: map from letter to frequency
"""
hist = {}
for x in s:
if x is '\n':
pass
else:
hist[x] = hist.get(x, 0) + 1
return hist
def read_file(filename):
"""Reaturns the contents of a file as a string."""
return open(filename).read()
if __name__ == '__main__':
string = read_file("words.txt")
letter_seq = most_frequent(string)
for x in letter_seq:
print(x)
# ex12.2
def make_word_list(filename):
fin = open(filename)
word_lst = []
for word in fin:
word_lst.append(word.strip().lower())
return word_lst
wordlst = make_word_list("words.txt")
def anagrams(word_lst):
"""map from word to list of anagrams"""
words_dict = {}
for word in word_lst:
characters = ''.join(sorted(list(word)))
if characters in words_dict:
words_dict[characters].append(word)
else:
words_dict[characters] = [word]
return words_dict
wrd_dct = anagrams(wordlst)
def print_anagrams(words_dict):
"""打印包含异位构词数量最多的词汇列表,第二多次之,依次按异位构词数量排列."""
len_v_k_lst = []
for v in words_dict.values():
len_v_k_lst.append((len(v), v))
len_v_k_lst.sort(reverse = True)
for i in range(1, 10):
print(len_v_k_lst[i])
print_anagrams(wrd_dct)
#ex12.3
def word_difference(word1,word2):
"""Computes the number of differneces between two words
word1, word2: strings
Returns: integer
"""
assert len(word1) == len(word2)
count = 0
for c1, c2 in zip(word1, word2):
if c1 != c2:
count +=1
return count
def metathesis_pairs(words_dict):
"""print all pairs of words that differ byb swapping two letters
d: map from word to list of anagrams
"""
for anagrams in words_dict.values():
for word1 in anagrams:
for word2 in anagrams:
if word1 < word2 and word_difference(word1, word2) ==2:
print(word1, word2)
metathesis_pairs(wrd_dct)
#ex12.4
def sub_words(word):
"""creat a list of words which a character is substracted from a word"""
sub_words_lst = []
for i in range(len(word)):
sub_word = word[:i]+word[i+1:]
sub_words_lst.append(sub_word)
return sub_words_lst
def is_subtractable(word, wordlst):
sub_wordlst = sub_words(word)
for word in sub_wordlst:
if word in wordlst:
if word != 1:
return is_subtractable(word, sub_wordlst)
else:
return True
else:
pass
return False
is_subtractable("spit", wordlst)
#answer
#from __future__ import print_function, division
# 1、必须在文档的开头,2、在开头加上from __future__ import print_function
# 这句之后,即使在python2.X,使用print就得像python3.X那样加括号使用。
###-----------------------------------------------------------###
def make_word_dict():
"""Reads a word list and returns a dictionary"""
d = dict()
fin = open("words.txt")
for line in fin:
word = line.strip().lower()
d[word] = None
#have to add single letter words to the word list;
#also, the empty string is considered a word.
for letter in ['a', 'i', '']:
d[letter] = letter
return d
"""memo is a dictionary that maps from each word that is known
to be reducible to a list of its reducible children. It starts
with the empty string."""
memo = {}
memo[''] = ['']
def is_reducible(word, word_dict):
"""If word is reducible, returns a list of its reducible children.
Also adds an entry to the memo dictionary.
A string is reducible if it has at least one chils that is reducible.
The empty string is also reducible.
word: string
word_dict: dictionary with words as keys
"""
# if have already checked this word, return the answer
if word in memo:
return memo[word]
# check each of the children and make a list of the reducible ones
res = []
for child in children(word, word_dict):
if is_reducible(child, word_dict):
res.append(child)
#memorize and return the result
memo[word] = res
return res
def children(word, word_dict):
"""Returns a list of all words that can be formed by removing one letter.
word: string
Returns: list of strings
"""
res = []
for i in range(len(word)):
child = word[:i]+word[i+1:]
if child in word_dict:
res.append(child)
return res
def all_reducible(word_dict):
"""Checks all words in the word_dict; returns a list reducible ones.
word_dict: dictionary with words as keys
"""
res = []
for word in word_dict:
t = is_reducible(word, word_dict)
if t != []:
res.append(word)
return res
def print_trail(word):
"""Print the sequence of words that reduces this word to the empty string.
If there is more than one choice, it chooses the first.
word: string
"""
if len(word) == 0:
return
print(word, end = ' ')
t = is_reducible(word, word_dict)
print_trail(t[0])
def print_longest_words(word_dict):
"""Finds the longest reducible words and prints them.
word_dict: dictionary of valid words
"""
words = all_reducible(word_dict)
# use DSU to sort by word length
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
#Print the longest 5 words
for _, word in t[0:5]:
print_trail(word)
print('\n')
word_dict = make_word_dict()
children("strarnger", word_dict)
is_reducible("stranger", word_dict)
all_reducible(word_dict)
print_trail('stranger')
print_longest_words(word_dict)
#if __name__ == '__main__':
|
6423e10c90048532f098824a4f0c7d4a626dc327 | dhellmann/commandlineapp | /docs/source/PyMagArticle/Listing5.py | 1,172 | 3.59375 | 4 | #!/usr/bin/env
# Base class for sqlite programs.
import sqlite3
import commandlineapp
class SQLiteAppBase(commandlineapp.CommandLineApp):
"""Base class for accessing sqlite databases.
"""
dbname = 'sqlite.db'
def optionHandler_db(self, name):
"""Specify the database filename.
Defaults to 'sqlite.db'.
"""
self.dbname = name
return
def main(self):
# Subclasses can override this to control the arguments
# used by the program.
self.db_connection = sqlite3.connect(self.dbname)
try:
self.cursor = self.db_connection.cursor()
exit_code = self.takeAction()
except:
# throw away changes
self.db_connection.rollback()
raise
else:
# save changes
self.db_connection.commit()
return exit_code
def takeAction(self):
"""Override this in the actual application.
Return the exit code for the application
if no exception is raised.
"""
raise NotImplementedError('Not implemented!')
if __name__ == '__main__':
SQLiteAppBase().run()
|
b314bbf40b5ea86eae4429d3d0319b931ee1da3c | xxxmian/CodingTime | /jiuzhang-reinforcement/numofIsland.py | 2,147 | 3.546875 | 4 | class UnionFind:
def __init__(self, num):
self.num = num
self.rec = [i for i in range(num)]
def find(self, a):
assert a < self.num
while a != self.rec[a]:
a = self.rec[a]
return a
def union(self, a, b):
assert a < self.num
assert b < self.num
fa = self.find(a)
fb = self.find(b)
if fa != fb:
self.rec[fa] = fb
def countPlate(self):
c = 0
for i in range(self.num):
if self.rec[i] == i:
c += 1
return c
class Solution:
"""
@param grid: a boolean 2D matrix
@return: an integer
"""
def numIslands(self, grid):
# write your code here
if not grid:
return 0
n, m = len(grid), len(grid[0])
uf = UnionFind(n * m)
water = 0
for i in range(n):
for j in range(m):
if grid[i][j] == 0:
water += 1
continue
for x, y in [(i + 1, j), (i, j + 1)]:
if x >= n or y >= m or grid[x][y] == 0:
continue
uf.union(i * m + j, x * m + y)
return uf.countPlate() - water
input = [[1,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0],[1,0,0,1,1,0,0,1,0,0,0,1,0,1,0,1,0,0,1,0],[0,0,0,1,1,1,1,0,1,0,1,1,0,0,0,0,1,0,1,0],[0,0,0,1,1,0,0,1,0,0,0,1,1,1,0,0,1,0,0,1],[0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0],[1,0,0,0,0,1,0,1,0,1,1,0,0,0,0,0,0,1,0,1],[0,0,0,1,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1],[0,0,0,1,0,1,0,0,1,1,0,1,0,1,1,0,1,1,1,0],[0,0,0,0,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,1],[0,0,1,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,1,0],[1,0,0,1,0,0,0,0,0,0,0,1,0,0,1,0,1,0,1,0],[0,1,0,0,0,1,0,1,0,1,1,0,1,1,1,0,1,1,0,0],[1,1,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,1],[0,1,0,0,1,1,1,0,0,0,1,1,1,1,1,0,1,0,0,0],[0,0,1,1,1,0,0,0,1,1,0,0,0,1,0,1,0,0,0,0],[1,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,1,0,1,1],[1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0],[0,1,1,0,0,0,1,1,1,0,1,0,1,0,1,1,1,1,0,0],[0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,1,1],[0,0,0,0,0,0,1,1,1,1,0,1,0,0,0,1,1,0,0,0]]
s=Solution()
print(s.numIslands(input))
|
0d92df85218fd0d86c7fb8465d7fb7815a144912 | bam6076/PythonEdX | /midterm_part7.py | 488 | 3.828125 | 4 | ## Write a function called pattern_sum that receives two single digit
## positive integers, (k and m) as parameters and calculates and
## returns the total sum as: k + kk + kkk + ....
## (the last number in the sequence should have m digits)
def pattern_sum(k, m):
total = 0
for i in range (1, m+1):
total = total + newk(i, k)
return total
def newk(d, k):
new = k
for j in range (1, d):
new = new + k*10**j
return new
print (pattern_sum (5,3))
|
af4f28e3d7907c639c3d28f04d3f1d84e8221dc0 | raochuan/LintCodeInPython | /set_matrix_zeroes.py | 1,635 | 3.71875 | 4 | # -*- coding: utf-8 -*-
class Solution:
"""
@param matrix: A list of lists of integers
@return: Nothing
"""
def setZeroes(self, matrix):
# write your code here
if not matrix:
return
rows = len(matrix)
cols = len(matrix[0])
# 确定第1行是非有0要处理
zero_first_row = False
for col in range(0, cols):
if matrix[0][col] == 0:
zero_first_row = True
break
# 确定第1列是非有0要处理
zero_first_col = False
for row in range(0, rows):
if matrix[row][0] == 0:
zero_first_col = True
break
# 利用第1行和第1列,标记某行某列需要清零。
for row in xrange(1, rows):
for col in xrange(1, cols):
if matrix[row][col] == 0:
matrix[row][0] = 0
matrix[0][col] = 0
# 根据标记清零。
for row in xrange(1, rows):
if matrix[row][0] == 0:
zero_row(matrix, row, 0, cols)
for col in xrange(1, cols):
if matrix[0][col] == 0:
zero_col(matrix, col, 0, rows)
# 判断第1行和第1列是否需要清理
if zero_first_row:
zero_row(matrix, 0, 0, cols)
if zero_first_col:
zero_col(matrix, 0, 0, rows)
def zero_row(matrix, row, left, right):
while left < right:
matrix[row][left] = 0
left += 1
def zero_col(matrix, col, up, low):
while up < low:
matrix[up][col] = 0
up += 1 |
d4221d2a381d050ba860e6fbdbcc6eb631fabf96 | mot12341234/Couresa_AlgorithmToolBox | /week3_greedy_algorithms/7_maximum_salary/largest_number.py | 734 | 3.875 | 4 | #Uses python3
import sys
def IsGreatOrEqual(max_digit, digit):
# max_digit = 23
# digit = 3
# 323 and 233, then max_digit = 3
return int(str(digit) + str(max_digit)) >= int(str(max_digit) + str(digit))
def largest_number(a):
# res = ""
# for x in a:
# res += x
# return res
res = []
while a != []:
max_digit = 0
for digit in a:
if IsGreatOrEqual(max_digit, digit):
max_digit = digit
res.append(max_digit)
a.remove(max_digit)
return res
if __name__ == '__main__':
# input = sys.stdin.read()
n = int(input())
data = list(map(int, input().split()))
print(''.join([str(i) for i in largest_number(data)]))
|
6212a9c1840f1864260f34d3beb7b709007072aa | cloudmesh-community/sp19-222-89 | /project-code/scripts/split_data.py | 2,158 | 3.765625 | 4 | #this function correctly formats the input data into a 2D numpy array
import numpy as np
def format(data):
#variable to store # of features, in this case we have 8
nfeatures = 8
#get the values from the list of dictionaries, put them into
#a new list
list_data = []
for i in data:
list_data.append(i.values())
#convert our data list to a numpy array
a = np.array(list_data)
#find out how many labels we need
a_shape = np.shape(a)
#now make array for features
a_features = np.zeros((a_shape[0], nfeatures))
#populate that array
for i in range(0, a_shape[0]):
for j in range(0, nfeatures):
a_features[i][j] = list(a[i])[j]
return a_features
#splits the data for training/testing
def split(data):
#variable to store # of features, in this case we have 8
nfeatures = 8
#get the values from the list of dictionaries, put them into
#a new list
list_data = []
for i in data:
list_data.append(i.values())
#convert our data list to a numpy array
a = np.array(list_data)
#separate features from labels
#find out how many labels we need
a_shape = np.shape(a)
#make a new array for it
a_labels = np.zeros(a_shape[0])
#populate that array (slice isn't working so)
for i in range(0, a_shape[0]):
if(list(a[i])[8] == '3'):
a_labels[i] = 1
else:
a_labels[i] = 0
#now make array for features
a_features = np.zeros((a_shape[0], nfeatures))
#populate that array
for i in range(0, a_shape[0]):
for j in range(0, nfeatures):
a_features[i][j] = list(a[i])[j]
#split to training and testing
#80% for training, 20% for testing
n_train = np.int(np.round(a_shape[0] * 0.8))
n_test = a_shape[0] - n_train
a_feat_training = a_features[0:n_train]
a_feat_testing = a_features[0:n_test]
a_label_training = a_labels[0:n_train]
a_label_testing = a_labels[0:n_test]
return a_feat_training, a_label_training, a_feat_testing, a_label_testing
|
436d7ba10fc2d9350300c9facbf8decf11bbee1d | diegoami/hackerrank-exercises | /30days/nested_logic.py | 1,348 | 3.609375 | 4 |
inputarray = [
"9 6 2015",
"6 6 2015"
]
inputarray2 = [
"31 8 2004",
"20 1 2004"
]
inputarray3 = [
"2 6 2014",
"5 7 2014"
]
inputarray4 = [
"31 12 2009",
"1 1 2010"
]
from tools import input, initArrayInputter
initArrayInputter(inputarray4)
import sys
d1,m1,y1 = map(int,input().split())
d2,m2,y2 = map(int,input().split())
def is_leap(year):
if (year > 1918):
return (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0)
else:
return (year % 4 == 0 )
month_days = [31,28,31,30,31,31,30,31,30,31,30,31]
def get_day_years(yx):
return 366 if is_leap(yx) else 365
def get_day_of_year(dx,mx,yx):
m = list(month_days)
if (is_leap(yx)):
m[1] = 29
if (yx== 1918):
m[1] -= 13
tot = sum([m[i] for i in range(mx-1)])+dx
dp = 0
"""
if (y1 == y2):
dp = get_day_of_year(d1,m1,y1)-get_day_of_year(d2,m2,y2)
elif (y1 == y2 + 1):
dp = get_day_of_year(d1, m1, y1) + ( get_day_years( y2) - get_day_of_year(d2, m2, y2))
elif (y1 > y2):
dp = get_day_of_year(d1, m1, y1) + ( get_day_years(y2) - get_day_of_year(d2, m2, y2)) + sum([get_day_years(y) for y in range(y1+1,y2-1)])
else:
pass
print(dp*15)
"""
if (y1 > y2):
dp = 10000
elif (y1 == y2) and (m1 > m2):
dp = (m1-m2)*500
elif (y1 == y2) and (m1 == m2) and (d1 > d2):
dp = (d1-d2)*15
else:
pass
print(dp) |
c6f6c0f75e5eefc8cb593fd431b96a4896986aec | MTset/Python-Programming-Coursework | /Python 04: Advanced Python/Lesson 02: Data Structures/arr.py | 969 | 3.546875 | 4 | """
Class-based dict allowing tuple subscripting and sparse data
"""
from collections import defaultdict
class array:
def __init__(self, X, Y, Z):
"Create an defaultdict subscripted to represent a 3D matrix."
self._data = defaultdict(int)
self._x = X
self._y = Y
self._z = Z
def __getitem__(self, key):
"Returns the appropriate element."
return self._data[self._validate_key(key)]
def __setitem__(self, key, value):
"Sets the appropriate element."
self._data[self._validate_key(key)] = value
def _validate_key(self, key):
"""Validates a key against the array's shape, returning good tuples.
Raises KeyError on problems."""
x, y, z = key
if (x in range(self._x) and
y in range(self._y) and
z in range(self._z)):
return key
raise KeyError("Subscript out of range") |
a2ebd3129a58d0cbc3e6f277aae3abf565140984 | linhptk/phamthikhanhlinh-fundamental-C4E27 | /Session01/HW/turtle_multi circles.py | 143 | 3.90625 | 4 | from turtle import *
shape("turtle")
color("green")
for i in range(100):
for j in range (10):
left(1)
forward(1)
mainloop() |
1fb05582f903045a97f766415feab6e8709056c1 | saraducks/Python_interview_prep | /Leetcode/Strings_python/str_to_integer.py | 451 | 3.703125 | 4 | def myAtoi(str):
"""
:type str: str
:rtype: int
"""
if len(str) == 0:
return 0
set_negative = False
if str[0] == '-':
set_negative = True
start_range = 1 if set_negative == True else 0
for i in range(start_range, len(str)):
if not str[i].isdigit():
return "No special characters"
return -1 *int(str[1::]) if set_negative else int(str)
result = myAtoi("-123")
print result |
1af5f2285ee0e0e17642fa70ce250afaacf4075f | daniel-reich/ubiquitous-fiesta | /BokhFunYBvsvHEjfx_9.py | 130 | 3.640625 | 4 |
def seven_boom(lst):
for num in lst:
if "7" in str(num):
return "Boom!"
return "there is no 7 in the list"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.