blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
e0f971ff852be442b84445bddc4058e32e7f340e | HamaguchiKazuki/nlp100 | /chap1/06.py | 1,363 | 3.71875 | 4 | # "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,
# それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.
# さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.
def str2cl(src):
# return [list(w) for w in [''.join([c for c in w if c.isalnum()]) for w in src.split()]]
# 文章を分ける
word_list = []
for word in src.split():
# 単語を整形する('This' 'is' 'pen.' -> 'This' 'is' 'pen')
char_list = []
for char in word:
if char.isalnum():
char_list.append(char)
word_list.append(char_list)
return word_list
def n_gram(n, gl):
n_gram_list = []
for g in gl:
if len(g) >= n:
for i in range(len(g)-n+1):
n_gram_list.append(g[i:i+n])
return n_gram_list
if __name__ == '__main__':
s1 = "paraparaparadise"
s2 = "paragraph"
X = set(map(''.join, n_gram(2, str2cl(s1))))
Y = set(map(''.join, n_gram(2, str2cl(s2))))
# sets
print('X =', X)
print('Y =', Y)
# sum, product, diff
print('X + Y =', X.union(Y))
print('X * Y =', X.intersection(Y))
print('X - Y =', X.difference(Y))
# include 'se' or not
print('X include "se":', 'se' in X)
print('Y include "se":', 'se' in Y)
|
21570acb75474207349f9f6afb107f564345f84c | comicxmz001/LeetCode | /Python/136_SingleNumber.py | 555 | 3.640625 | 4 | class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#Using XOR to find the single number.
#Because every number appears twice, while N^N=0, 0^N=N,
#XOR is cummutative, so the order of elements does not matter.
#Finally, it will be res = 0 ^ singlenumber ==> res = singlenumber
res = 0
for num in nums:
res ^= num
return res
nums = [1,1,5,5,3,4,4,9,9,8,8,7,7]
foo = Solution()
print foo.singleNumber(nums)
|
779c2e05f0e05ea77fca10f01bb326f99848c7cd | Matt-the-Marxist/schoolStuff | /docs/classwork/python/lessons/7.1.8.py | 281 | 3.78125 | 4 | author_name = ("Martin", "Luther", "King, Jr.")
def citeAuthor(authorNameTuple):
result = []
result.append(authorNameTuple[len(authorNameTuple)-1])
for i in range(len(authorNameTuple)-1):
result.append(authorNameTuple[i])
return(tuple(result))
print(citeAuthor(author_name)) |
ae542976955ed6870d8c39a220ce61add09ec324 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2449/60700/283544.py | 706 | 3.59375 | 4 | def search(l: list, s: str):
if s >= l[0]:
return binarySearch(l[0: l.index(max(l))], s)
else:
return binarySearch(l[l.index(min(l)): len(l)-1], s)+l.index(min(l))
def binarySearch(l: list, s: str):
index = -1
lp = 0
rp = len(l)-1
while True:
t = (lp + rp) // 2
if s == l[t]:
index = t
break
if s > l[t]:
lp = t
if s < l[t]:
rp = t
if lp == rp:
break
return index
line = input()
s = input()
l = line.split(',')
if s >= l[0]:
print(binarySearch(l[0: l.index(max(l))], s))
else:
print(binarySearch(l[l.index(min(l)): len(l) - 1], s) + l.index(min(l)))
|
88db0fde524dd4304e9753d398fa99a84835c81b | Mudasirrr/Courses- | /MITx-6.00.2x/weighted-graph-problem.py | 3,626 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
@author: salimt
"""
# -*- coding: utf-8 -*-
"""
@author: salimt
"""
class Node(object):
def __init__(self, name):
"""Assumes name is a string"""
self.name = name
def getName(self):
return self.name
def __str__(self):
return self.name
class Edge(object):
def __init__(self, src, dest):
"""Assumes src and dest are nodes"""
self.src = src
self.dest = dest
def getSource(self):
return self.src
def getDestination(self):
return self.dest
def __str__(self):
return self.src.getName() + '->' + self.dest.getName()
class Digraph(object):
"""edges is a dict mapping each node to a list of
its children"""
def __init__(self):
self.edges = {}
def addNode(self, node):
if node in self.edges:
raise ValueError('Duplicate node')
else:
self.edges[node] = []
def addEdge(self, edge):
src = edge.getSource()
dest = edge.getDestination()
if not (src in self.edges and dest in self.edges):
raise ValueError('Node not in graph')
self.edges[src].append(dest)
def childrenOf(self, node):
return self.edges[node]
def hasNode(self, node):
return node in self.edges
def getNode(self, name):
for n in self.edges:
if n.getName() == name:
return n
raise NameError(name)
def __str__(self):
result = ''
for src in self.edges:
for dest in self.edges[src]:
result = result + src.getName() + '->'\
+ dest.getName() + '\n'
return result[:-1] #omit final newline
class Graph(Digraph):
def addEdge(self, edge):
Digraph.addEdge(self, edge)
rev = Edge(edge.getDestination(), edge.getSource())
Digraph.addEdge(self, rev)
class WeightedEdge(Edge):
def __init__(self, src, dest, weight):
# Your code here
self.src = src
self.dest = dest
self.weight = weight
pass
def getWeight(self):
# Your code here
return self.weight
def __str__(self):
# Your code here
return self.src.getName() + '->' + self.dest.getName() + ' (' + str(self.getWeight()) +')'
# For example, an acceptable permutation (edge)
# is between "ABC" and "ACB" but not between "ABC" and "CAB".
nodes = []
nodes.append(Node("ABC")) # nodes[0]
nodes.append(Node("ACB")) # nodes[1]
#nodes.append(Node("BAC")) # nodes[2]
#nodes.append(Node("BCA")) # nodes[3]
#nodes.append(Node("CAB")) # nodes[4]
#nodes.append(Node("CBA")) # nodes[5]
g = Graph()
for n in nodes:
g.addNode(n)
n = len(nodes)
for node in range(n-1):
currentNode = Node.getName(nodes[node])
for item in range(node+1, n):
nextNode = Node.getName(nodes[item])
# print(currentNode, nextNode)
if currentNode == nextNode: raise ValueError ('Same Value Exists!')
if currentNode[0] == nextNode[0] and currentNode[1] == nextNode[2] \
and currentNode[2] == nextNode[1]:
g.addEdge(Edge(g.getNode(currentNode), g.getNode(nextNode)))
if currentNode[0] == nextNode[1] and currentNode[1] == nextNode[0] \
and currentNode[2] == nextNode[2]:
g.addEdge(Edge(g.getNode(currentNode), g.getNode(nextNode)))
print(g)
|
f902d5e9b15377319406c871c08771579782abc1 | Muhammad5943/Data-Science | /Importing_file/11.HTTPRequeststoImportFilesfromWeb.py | 325 | 3.671875 | 4 | from urllib.request import urlopen, Request
import requests
""" url = "https://www.wikipedia.org/"
request = Request(url)
response = urlopen(request)
html = response.read()
response.close()
# print(html)
print(response)
print(request) """
url = "https://www.wikipedia.org/"
r = requests.get(url)
text = r.text
print(text) |
fd5273ff91085b226fbfb637b400fba81e9f080f | EvgeniiGrigorev0/home_work-_for_lesson_2 | /lesson_5/hw_1_lesson5.py | 646 | 4.15625 | 4 | # 1. Создать программно файл в текстовом формате,
# записать в него построчно данные, вводимые
# пользователем. Об окончании ввода данных свидетельствует пустая строка.
my_file = open('первое задание.txt', 'w', encoding="utf-8")
line = input('Введите текст \n:')
while line:
my_file.writelines(line)
line = input('Введите текст \n')
if not line:
print('Текстовый документ успешно создан!')
break
my_file.close()
|
c5b42e41613571b2a9f7a71fa25ff94ecbcad882 | mrhota/cs373 | /examples/FunctionPolymorphism.py | 815 | 3.90625 | 4 | #!/usr/bin/env python
# -----------------------
# FunctionPolymorphism.py
# -----------------------
# parametric run-time polymorphism
class A (object) :
def __init__ (self, n) :
self.n = n
def __lt__ (self, other) :
return self.n < other.n
class B (A) :
pass
def my_max (x, y) :
if x < y :
return y
return x
print "FunctionPolymorphism.py"
assert hasattr(int, "__lt__")
assert hasattr(float, "__lt__")
assert hasattr(str, "__lt__")
assert hasattr(A, "__lt__")
assert hasattr(B, "__lt__")
assert my_max(2, 3) == 3
assert my_max(2.3, 4) == 4
assert my_max(2, 4.5) == 4.5
assert my_max(2.3, 4.5) == 4.5
assert my_max("abc", "def") == "def"
x = A(2)
y = A(3)
assert my_max(x, y) is y
x = B(2)
y = B(3)
assert my_max(x, y) is y
print "Done."
|
e29e11cb05e97bf9f49024d6fcc6facbebfe8cdc | omnidune/ProjectEuler | /Files/problem12.py | 1,001 | 3.84375 | 4 | # The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven triangle numbers:
# 1: 1
# 3: 1, 3
# 6: 1, 2, 3, 6
# 10: 1, 2, 5, 10
# 15: 1, 3, 5, 15
# 21: 1, 3, 7, 21
# 28: 1, 2, 4, 7, 14, 28
# We can see that 28 is the first triangle number to have over five divisors.
# What is the value of the first triangle number to have over n divisors?
def numoffactor(number):
# Returns the number of factors of the given int argument "number"
count = 0
for i in range(1, number+1):
if not number%i:
count += 1
return count
def divisibleTriangleNumber(n):
# Returns the first triangle number to have over n divisors
trinum = 0
incrimentor = 0
while numoffactor(trinum) < n + 1:
incrimentor += 1
trinum = trinum + incrimentor
return trinum
print(divisibleTriangleNumber(167))
|
6443588692765b3ae8e704ce4aa5c0dfb7b0e061 | wangsanshi123/tutorial | /python_basic/lesson1.py | 1,426 | 3.96875 | 4 | def hello():
print("hello world!")
pass
def genre_test():
"""基本数据类型"""
a = 1
b = "hello"
c = True
d = [1, 2, 3, 4]
e = (1, 2, 3, 4)
f = {"name": "jack", "age": 10}
print("type of a is:", type(a))
print("type of b is:", type(b))
print("type of c is:", type(c))
print("type of d is:", type(d))
print("type of e is:", type(e))
print("type of f is:", type(f))
pass
def int_float_str_test():
a = 1
print("a:", a)
print("a+1:", a + 1)
b = a + 1
print("b:", b)
b = b + 1
print("b:", b)
b += 1
print("b:", b)
c = a + 1.0
print("c:", c)
# d = a+"hello"
d = str(a) + "hello"
e = str(a) + "2"
print("d:", d)
print("e:", e)
pass
def str_test():
b = "hello"
print(b)
print(b[0])
print(b[-1])
pass
def list_test():
d = [1, 2, 3, 4]
print(d)
print(d[0])
print(d[-1])
print(d[0:2])
print(d[:2])
print(d[:-1])
print(d[0])
d[0] = "hello"
print(d[0])
print(d)
def tuple_test():
e = (1, 2, 3, 4)
print(e)
print(e[0])
pass
def dict_test():
f = {"name": "jack", "age": 10}
print(f)
print(f.keys())
print(f.values())
print(f.items())
pass
def set_test():
pass
if __name__ == '__main__':
""""""
# genre_test()
# int_float_str_test()
# str_test()
# dict_test()
|
5b2275c4ddd061fee0b422f87ac61f5988e64db2 | park950414/python | /第九章/pySum.py | 224 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 14 09:06:16 2017
@author: park
"""
import numpy as np
def npSum():
a = np.array([0,1,2,3,4])
b = np.array([9,8,7,6,5])
c = a**2 + b**3
return c
print(npSum())
|
9c349d006dbebc09125d94f97ee554cde773579f | AristidisKantas/HackerRank-Codes | /Counting-Valleys.py | 569 | 3.75 | 4 | def countingValleys(steps, path):
levelArr = [0]*steps
level = 0
isInValley = False
valleyCounter = 0
for i in range(steps):
if path[i] == 'U':
level += 1
elif path[i] == 'D':
level -= 1
levelArr[i] = level
for j in range(len(levelArr)):
if levelArr[j] < 0 and isInValley == False:
isInValley = True
if levelArr[j] == 0 and isInValley == True:
valleyCounter += 1
isInValley = False
return valleyCounter
|
1ae7d95629dcd2611779348c3e5dc418f0b8c82b | Zylophone/cracking | /is_present.py | 399 | 3.59375 | 4 | class Node:
__init__(self, value):
self.value = value
self.left = None
self.right = None
def isPresent (root, val):
if root is None:
return 0
if root == val:
return 1
eight = new Node(8)
thirty = new Node(30)
ten = new Node(10)
twenty = new Node(20)
eleven = new Node(11)
eleven.left = ten
eleven.right = twenty
ten.left = eight
twent.right = thirty
|
94d7c6a9a3bfa818028ed34552ddbddbd25fb016 | neelamy/Algorithm | /Graph Theory/Spanning Tree/Prim_Algo_Adj_List.py | 2,311 | 4.1875 | 4 | # Python program for Prim's Minimum Spanning Tree (MST) algorithm.
# The program is for adjacency list representation of the graph
#Complexity : O(V(V+E))
from collections import defaultdict
#Class to represent a graph
class Graph:
def __init__(self,vertices):
self.V= vertices #No. of vertices
self.graph = defaultdict(list) # default dictionary to store graph
# function to add an edge to graph
def addEdge(self,u,v,w):
self.graph[u].append((v,w))
self.graph[v].append((u,w))
# A utility function to find the vertex with minimum key value, from
# the set of vertices still in queue
def get_min(self,key,queue):
# Initialize min value and index as -1
minimum = float("Inf")
index =-1
#from the key array,pick one which has min value and is till in queue
for i in range(len(key)):
if key[i] < minimum and i in queue:
minimum = key[i]
index =i
return index
# Function to construct and print MST for a graph represented using adjacency
# list representation
def primMST(self):
# Initialize all key/distance as INFINITE
key = [float("Inf")] * self.V
# Always include first 1st vertex in MST
key[0] = 0 # Make key 0 so that this vertex is picked as first vertex
# Array to store constructed MST
parent = [-1] * self.V
parent[0] = 0 # First node is always root of MST
# Add all vertices in queue
queue = []
for i in range(self.V):
queue.append(i)
while queue:
# Pick the minimum key vertex from the set of vertices
# still in queue
u = self.get_min(key,queue)
# remove min element and print it
queue.remove(u)
print str(parent[u]) + "-" + str(u)
# Update key value and parent index of the adjacent vertices of
# the picked vertex. Consider only those vertices which are still in
# queue
for node,weight in self.graph[u]:
if node in queue and weight < key[node]:
key[node] = weight
parent[node] =u
# print total distance
print sum(key)
g = Graph(9)
g.addEdge(0, 1, 4)
g.addEdge(0, 7, 8)
g.addEdge(1, 2, 8)
g.addEdge(1, 7, 11)
g.addEdge(2, 3, 7)
g.addEdge(2, 8, 2)
g.addEdge(2, 5, 4)
g.addEdge(3, 4, 9)
g.addEdge(3, 5, 14)
g.addEdge(4, 5, 10)
g.addEdge(5, 6, 2)
g.addEdge(6, 7, 1)
g.addEdge(6, 8, 6)
g.addEdge(7, 8, 7)
#Print the solution
g.primMST()
|
39df42f8dfb68a99210e7ed245bbfbe781b38483 | Esentur/Python_course | /Base/lesson_19.py | 326 | 3.875 | 4 | #отладка
# a=0
# while True:
# a+=0.1
# # print(a)
# if (a>=1):
# exit(0)
# print('Hello')
#exercise
list=[3,5,-2,-8,0]
def findNegativeNum(arr):
negs=[]
for n in arr:
if n<0:
negs.append(n)
return negs
print(findNegativeNum(list))
print('Basic part completed')
|
6ab9604b28ab5a8a17af8c3e32a070dd0ce3d842 | larsnohle/57 | /31/thirtyOne.py~ | 805 | 3.96875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def get_positive_number_input(msg, to_float = False):
done = False
while not done:
try:
i = -1.0
if to_float == True:
i = float(input(msg))
else:
i = int(input(msg))
if i < 0:
print("Please enter a number > 0")
else:
done = True
except ValueError:
print("That was not a valid integer. Please try again!")
return i
def main():
age = get_positive_number_input("Age: ")
resting_heart_rate = get_positive_number_input("Resting heart rate: ")
target_heart_rate = (((220 - age) - resting_heart_rate) * intensity) + resting_heart_rate
### MAIN ###
if __name__ == '__main__':
main()
|
94f3f859ba8ebe4c91a5a933fe028a2a81771b2a | sidv/Assignments | /Lekshmi_Pillai_185386/August_18/binary.py | 358 | 3.859375 | 4 | #4.Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are #divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
binary = [1000,1111,1101,1010]
lst= []
for i in binary:
a = int(str(i),2)
if a % 5 ==0:
lst.append(i)
print(lst)
|
0d1d7f377969b6f2330d018e3c2e9baef6cfc448 | xzha0006/Leetcode | /Python/0547_FriendCircles.py | 790 | 3.59375 | 4 | class Solution:
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
if not M:
return 0
n = len(M)
id = [i for i in range(n)] #Initial id list. All nodes' parents are themselves.
count = n
def find(node):
while id[node] != node: #If node is not root node
node = id[node]
return node
def union(node0, node1):
res = 0
if find(node0) != find(node1):
id[find(node1)] = find(node0)
res = -1
return res
for i in range(n):
for j in range(i,n):
if i != j and M[i][j]:
count += union(i, j)
return count
|
0d6a863f61cd82830d55f5aed1be43d1660cdfe9 | turamant/mySOLID | /4_Interface_segregation.py | 1,592 | 4.3125 | 4 | ##################################################################################
# Interface Segregation Principle (Принцип разделения интерфейса).
#
#
##################################################################################
class Creature:
def __init__(self, name):
self.name = name
class SwimerInterface:
def swim(self):
print(f"Если у кота не реализован метод плавания, то будет взят из интерфейса")
class WalkerInterface:
def walk(self):
pass
class TalkerInterface:
def talk(self):
pass
class Human(Creature, SwimerInterface, WalkerInterface, TalkerInterface):
def __init__(self, name):
super(Human, self).__init__(name)
def swim(self):
print(f'I am {self.name} and I can swim!')
def walk(self):
print(f'I am {self.name} and I can walk!')
def talk(self):
print(f'I am {self.name} and i can talk!')
class Fish(Creature, SwimerInterface):
def __init__(self, name):
super(Fish, self).__init__(name)
def swim(self):
print(f'I am {self.name} and I can swim!')
class Cat(Creature, SwimerInterface, WalkerInterface):
def __init__(self, name):
super(Cat, self).__init__(name)
def walk(self):
print(f'I am {self.name} and I can walk!')
if __name__ == '__main__':
human = Human('person')
human.swim()
human.walk()
human.talk()
fish = Fish('fishka')
fish.swim()
cat = Cat('Barsik')
cat.swim()
cat.walk()
|
25ed420d94940060c00a010dbe2689457bca14c0 | ArkaprabhaChakraborty/Datastructres-and-Algorithms | /Python/stackusingqueuemodule.py | 976 | 3.953125 | 4 | #using LifoQueue from queue module
from queue import LifoQueue as lfq
#maxsize – Number of items allowed in the queue.
#empty() – Return True if the queue is empty, False otherwise.
#full() – Return True if there are maxsize items in the queue. If the queue was initialized with maxsize=0 (the default), then full() never returns True.
#get() – Remove and return an item from the queue. If queue is empty, wait until an item is available.
#get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
#put(item) – Put an item into the queue. If the queue is full, wait until a free slot is available before adding the item.
#put_nowait(item) – Put an item into the queue without blocking.
#qsize() – Return the number of items in the queue. If no free slot is immediately available, raise QueueFull.
stack = lfq(maxsize=3)
#qsize() shows the number of elements
print(stack.qsize())
stack.put('a')
stack.put('b')
print(stack.get())
|
ebdb64aecf14a3c44f2f5526abcffded71f25240 | eltondornelas/curso-python-lom | /secao3_python_intermediario/calculos.py | 567 | 3.859375 | 4 | import math
PI = math.pi
def dobra_lista(lista):
return [x * 2 for x in lista]
def multiplica(lista):
r = 1
for i in lista:
r *= i
return r
if __name__ == '__main__':
# perceba que se não fizer isso e rodar o aplicativo.py, todos esses prints serão mostrados lá também
# então quanto tem algum tipo de teste ou algoritmo que queira mostrar apenas se estiver rodando neste módulo, coloca essa condição
lista = [1, 2, 3, 4, 5]
print(dobra_lista(lista))
print(multiplica(lista))
print(PI)
# print(__name__)
|
9f6b66a6fe7cf8a20c748d34d082759face7821d | kumibrr/2DAM | /Sistemas de Gestión de Empresas/003_Examen/Ejercicio1.py | 302 | 3.5 | 4 | def Ejercicio1():
ingreso = input("Introduzca sus ingresos")
ipi = 0
if ingreso < 85528:
ipi = ingreso * 18 / 100
ipi = ipi + 0.2
elif ingreso > 85528:
ipi = 14839.2
ipi = ipi + (ingreso - 85528 * 32 / 100)
else:
ipi = 0
print(round(ipi)) |
95ea9cb86663b5f9e12f5ac815c6c10e3c049088 | chemxy/MazeRunnerAI | /versions/1.0/src/Player.py | 463 | 3.5625 | 4 | from Object import Object
class Player(Object):
def __init__(self,x ,y):
# character's width and height in pixels
#self.player_size = 50
# iniitial character x-y coordinates in pixels
self.x = x
self.y = y
#print("player initial location: " + str(self.x) + " " +str(self.y))
self.location = (self.x, self.y)
# character's idle animation count
self.idleCount = 0
self.life = 100 |
a8026a974f1ec48d977f28a92878ce6bdccc7c52 | TopskiyMaks/PythonBasic_Lesson | /lesson_9/task_1.py | 965 | 4.21875 | 4 | print('Задача 1. Календарь')
# Мы продолжаем разрабатывать удобный календарь для смартфона.
# Функцию определения високосного года мы добавили,
# но забыли ещё много разных очевидных вещей.
#
# Напишите программу,
# которая принимает от пользователя день недели в виде строки и выводит его номер на экран.
#
# Пример:
# Введите день недели: вторник
# Номер дня недели: 2
day = input('Введите день недели: ')
week = ['понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота', 'воскресенье']
for i, elem in enumerate(week):
if day == elem:
print(f'Номер дня недели: {i+1}')
|
634894165cc9b8e7d2a24d0e11ec0c863def7dd7 | mkawserm/PyOp | /src/example_one.py | 1,510 | 4.09375 | 4 | """
* Module : example_one
* Author : Kawser
* Website : http://kawser.org
* Git : https://github.com/mkawserm
*
* Date : 12/04/2014
* Time : 11:18 PM
*
*
* Objective : We shall calculate resistance (R1 and R2) of a voltage divider using Rational class
*
* Input :: V - Source Volt
* V2 - Desired Volt
* I2 - Desired current flow in ampere
* Output :: R1 and R2 resistance in Ohm
*
*
"""
from PyOp import Rational
def calculate_resistance():
V = Rational( raw_input("Enter input/source voltage (V) : ") )
V2 = Rational( raw_input("Enter output voltage (V2) : ") )
I2 = Rational( raw_input("Enter output current (I2) : ") )
R2 = V2/I2
R1 = ( (V-V2)*R2 )/ V2
V1 = ( R1/(R1+R2) ) * V
V2 = ( R2/(R1+R2) ) * V
I1 = V1/R1
print "======== Rational Format ==========="
print "R1 = %s ohm" % R1
print "I1 =%s amp" %I1
print "V1 = %s volt" % V1
print
print "R2 = %s ohm" % R2
print "I2 = %s amp" % I2
print "V2 = %s volt" % V2
print
print "======== Floating point format ======="
print "R1 = %s ohm" % float(R1)
print "I1 =%s amp" %float(I1)
print "V1 = %s volt" % float(V1)
print
print "R2 = %s ohm" % float(R2)
print "I2 = %s amp" % float(I2)
print "V2 = %s volt" % float(V2)
################################################################################
if __name__=="__main__":
calculate_resistance() |
97874269af88d987683e0aeaa1e7f8d39f626864 | backman-git/leetcode | /sol49.py | 710 | 4.09375 | 4 |
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
key points:
1.善用 for k,v in dTlb.items():
2. sorted(“cba”) 回傳['a','b','c']
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dTlb={}
for s in strs:
sortStr=''.join(sorted(s))
if sortStr in dTlb:
dTlb[sortStr].append(s)
else:
dTlb[sortStr]=[s]
res=[]
for k,v in dTlb.items():
res.append(v)
return res
sol =Solution()
ary = ["eat", "tea", "tan", "ate", "nat", "bat"]
print sol.groupAnagrams(ary) |
2a1f7273a5110ab20cc8ccb1a81e53931a877a28 | jstocks/dungeon | /dungeon_adventure.py | 36,321 | 3.78125 | 4 | from adventurer import Adventurer
from dungeon import Dungeon
import webbrowser
"""DungeonAdventure holds the logic of playing the game. Re/starts game, creates
adventurer and dungeon through respective classes, controls user input/options &
movement, and logic for winning/losing game"""
"""Hidden menu items can be accessed when asked for input:
- "vision"
- "map"
- "python" """
def start_game():
"""This method starts the game. Provides an introduction and how to play guide.
It also kicks off the game with character creation and dungeon / difficulty."""
intro()
how_to_play()
adventurer = create_player()
dungeon = difficulty()
play(dungeon, adventurer)
def restart_game():
"""This method restarts the game without intro / how to play guide."""
adventurer = create_player()
dungeon = difficulty()
play(dungeon, adventurer)
def play(dungeon, adventurer):
"""This method holds the logic for playing the game."""
user_input(dungeon, adventurer)
def intro():
"""This method provides an overview of the game"""
print("Welcome to the Dungeon of Doom! Prepare for the most difficult \n"
"challenge of your adventure-seeking life. Check your pride at the door,\n"
"and bring an extra ounce of courage as you face off against countless\n"
"pits and race against your own agony to capture the elusive....... \n\n"
"***** Four Pillars of Object-Oriented Programming *****\n")
def how_to_play():
"""This method describes the goal of the game, how to win, and the objects
encountered during the game"""
print("The goal of this game is to escape the dungeon maze after finding the\n"
"four oh-so-glorious pillars:\n\n"
" 1: Abstraction\n"
" 2: Encapsulation\n"
" 3: Inheritance\n"
" 4: Polymorphism\n\n"
"Be warned - you have limited health points [HP]. If you fall in a pit, you\n"
"will lose HP. Don't fret - there are also Healing Potions and Vision\n"
"Potions scattered about the dungeon to help you in your quest. Once you\n"
"collect all Four Pillars of OO, the exit door will unlock --- if you reach\n"
"the exit before your HP reaches a big fat zero, you win!\n\n"
"Move throughout the map by typing \'u\', \'d\', \'l\', or \'r\'\n"
"Don't bang your head against the walls \'|\' and \'-\'in the dungeon.\n\n"
"Check the status of your adventurer by typing \'s\'.\n"
"Check the map legend and user inputs by typing \'k\'.\n\n"
"Be strong in your journey...\n\"Even death is not to be feared by one who "
"has lived wisely\" --- Buddha\n")
def create_player():
"""This method asks user for Character Name input. This should reference the
Adventurer Class"""
player_name = input("Welcome to the bridge of death... What is your name?: ")
return Adventurer(player_name)
def difficulty():
"""This method will define the size of the dungeon array. 1 = 3x3, 2 = 5x5, 3 = 6x6"""
low = 1
high = 5
try:
level = int(input("What is your quest? Enter a difficulty from 1 (Easy) to 5 (Hard): "))
if low <= level <= high:
# create dungeon by array size based on level input
if level == 1:
nx, ny = 3, 3
if level == 2:
nx, ny = 4, 4
if level == 3:
nx, ny = 5, 5
if level == 4:
nx, ny = 8, 8
if level == 5:
nx, ny = 10, 10
ix, iy = 0, 0
game_board = Dungeon(nx, ny, ix, iy)
game_board.make_dungeon()
game_board.place_dungeon_items()
while game_board.traverse() is not True:
game_board.make_dungeon()
game_board.place_dungeon_items()
print_room(game_board)
return game_board
else:
print("\n\"Ahhhhhhhhhhhhh\" (That's the sound of you being thrown into\n"
"the gorge because you didn't enter an integer between 1-5.)\n\n"
"***GAME OVER***\n")
input("Press Enter to restart game...")
restart_game()
except ValueError:
print("\n\"Ahhhhhhhhhhhhh\" (That's the sound of you being thrown into\n"
"the gorge because you don't know your numbers.)\n\n***GAME OVER***\n")
input("Press Enter to restart game...")
restart_game()
def print_room(dungeon):
""" prints the dungeon as a visual """
x, y = dungeon.current_room()
def print_top_row(row, col):
# print top row
room = dungeon.room_at(row, col)
print("*", end='')
if col == 0:
print("*", end='')
else: # it's not border
if room.has_north_wall():
print("-", end='')
else:
print(" ", end='')
print("*")
def print_mid_row(row, col):
# print middle row
room = dungeon.room_at(row, col)
if row == 0:
print("*", end='')
else: # it's not border
if room.has_west_wall():
print("|", end='')
else:
print(" ", end='')
print(room.get_letter(), end='')
if row == int(dungeon.get_nx() - 1):
print("*")
else: # it's not border
if room.has_east_wall():
print("|")
else:
print(" ")
def print_bot_row(row, col):
# print third row
room = dungeon.room_at(row, col)
print("*", end='')
if col == (int(dungeon.get_ny()) - 1):
print("*", end='')
else:
if room.has_south_wall():
print("-", end='')
else:
print(" ", end='')
print("*")
print_top_row(x, y)
print_mid_row(x, y)
print_bot_row(x, y)
def show_vision_map(dungeon):
x, y = dungeon.current_room()
def print_first_row(row, col):
if col == 0:
print(" ")
return
if col > 0 and row == 0:
print(" *", end='')
# move to room 2
dungeon.move_to(row, col - 1) # up one col from initial room
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if col == 0:
print("**", end='')
elif room.has_north_wall():
print("-*", end='')
else:
print(" *", end='')
# room 3 (assuming an array of 3 or more cols)
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if col == 0:
print("**")
elif room.has_north_wall():
print("-*")
else:
print(" *")
else:
# room 1
dungeon.move_to((row - 1), col - 1)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print("*", end='')
if col == 0:
print("*", end='')
elif room.has_north_wall():
print("-", end='')
else:
print(" ", end='')
print("*", end='')
# room 2
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if col == 0:
print("*", end='')
elif room.has_north_wall():
print("-", end='')
else:
print(" ", end='')
print("*", end='')
# room 3
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
# case if out of bounds to right
if row == dungeon.get_nx():
print(" ")
else:
room = dungeon.room_at(row, col)
if col == 0:
print("*", end='')
elif room.has_north_wall():
print("-", end='')
else:
print(" ", end='')
print("*")
def print_second_row(row, col):
if col == 0:
print(" ")
return
if col > 0 and row == 0:
print(" *", end='')
# move to room 2, up from initial room
dungeon.move_to(row, col - 1)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# room 3 (assuming an array of more than 3 cols)
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='') #
if row == dungeon.get_nx():
print("*")
elif room.has_east_wall():
print("|")
else:
print(" ")
else:
# room 1
dungeon.move_to((row - 1), col - 1)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if row == 0:
print("*", end='')
elif room.has_west_wall():
print("|", end='')
else:
print(" ", end='')
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# room 2
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
temp = int(dungeon.get_nx())
if row == temp - 1:
print("*", end='')
elif room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# room 3
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
# case if out of bounds to right
if row == dungeon.get_nx():
print(" ")
else:
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
a = int(dungeon.get_nx())
if row == a - 1:
print("*")
elif room.has_east_wall():
print("|")
else:
print(" ")
def print_third_row(row, col):
if row == 0 and col == 0:
# top left corner
print(" *****")
elif col == 0 and row > 0:
# top row excluding left corner
print("*****", end='')
# move to right room
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
# if room doesn't exist
if row == dungeon.get_nx():
print(" ")
else:
print("**")
elif col > 0 and row == 0:
# first column
print(" *", end='')
# room 2
# row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_north_wall():
print("-", end='')
else:
print(" ", end='')
print("*", end='')
# room 3 (assuming an array of 3 or more cols)
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_north_wall():
print("-", end='')
else:
print(" ", end='')
print("*")
else:
# room 1 (move left 1 room)
dungeon.move_to((row - 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print("*", end='')
if col == 0:
print("*", end='')
elif room.has_north_wall():
print("-", end='')
else:
print(" ", end='')
print("*", end='')
# room 2 (was the initial room)
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_north_wall():
print("-", end='')
else:
print(" ", end='')
print("*", end='')
# room 3
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
# case if out of bounds to right
if row == dungeon.get_nx():
print(" ")
else:
room = dungeon.room_at(row, col)
if room.has_north_wall():
print("-", end='')
else:
print(" ", end='')
print("*")
def print_fourth_row(row, col):
# top left corner
if col == 0 and row == 0:
# first room
print(" *", end='')
# second room
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# third room
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|")
else:
print(" ")
elif col > 0 and row == 0: # (west dungeon border) assume array >= than 3
print(" *", end='')
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|")
else:
print(" ")
else: # room not at row 0 (east dungeon border)
# room 1 to left
dungeon.move_to((row - 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if row == 0:
print("*", end='')
elif room.has_west_wall():
print("|", end='')
else:
print(" ", end='')
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# room 2 (initial room)
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
temp = int(dungeon.get_nx())
if row == temp - 1:
print("*", end='')
elif room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# room 3 (right room)
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
if row == dungeon.get_nx():
print(" ")
else:
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
temp = int(dungeon.get_nx())
if row == temp - 1:
print("*")
elif room.has_east_wall():
print("|")
else:
print(" ")
def print_fifth_row(row, col):
if row == 0 and col == int(dungeon.get_ny()) - 1:
print(" *****")
# room at bottom right corner
elif row == (int(dungeon.get_nx()) - 1) and col == (int(dungeon.get_ny()) - 1):
print("***** ")
# room on bottom row
elif col == (int(dungeon.get_ny()) - 1):
print("*******")
else:
# room bordering west dungeon border
if row == 0:
print(" *", end='')
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*", end='')
else:
print(" *", end='')
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*")
else:
print(" *")
# room bordering east dungeon border
elif row == int(dungeon.get_nx() - 1):
print("*", end='')
# first room (to left)
dungeon.move_to((row -1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*", end='')
else:
print(" *", end='')
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*", end='')
else:
print(" *", end='')
print(" ")
else:
# no dungeon borders
print("*", end='')
# first room (to left)
dungeon.move_to((row - 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*", end='')
else:
print(" *", end='')
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*", end='')
else:
print(" *", end='')
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*")
else:
print(" *")
def print_sixth_row(row, col):
# room on bottom row
if col == (int(dungeon.get_ny()) - 1):
print(" ")
# room on west dungeon border
elif row == 0: # assumes array larger than 3
print(" *", end='')
# move down a room
dungeon.move_to(row, (col + 1))
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# move right a room
dungeon.move_to(row + 1, col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ")
elif row == 1: # assumes array larger than 3
print("*", end='')
# room 1 move down, to left
dungeon.move_to((row - 1), (col + 1))
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# room 2 move right a room
dungeon.move_to(row + 1, col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# room 3 move right a room
dungeon.move_to(row + 1, col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|")
else:
print(" ")
# room bordering east dungeon border
elif row == int(dungeon.get_nx() - 1):
# first room (down one, left one)
dungeon.move_to((row -1), (col + 1))
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_west_wall():
print("|", end='')
else:
print(" ", end='')
print(room.get_letter(), end='')
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_west_wall():
print("|", end='')
else:
print(" ", end='')
print(room.get_letter(), end='')
print("* ")
# second from last row, shows east dungeon border
elif row == int(dungeon.get_nx() - 2):
# first room (down one, left one)
dungeon.move_to((row -1), (col + 1))
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_west_wall():
print("|", end='')
else:
print(" ", end='')
print(room.get_letter(), end='')
# second room
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_west_wall():
print("|", end='')
else:
print(" ", end='')
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# third room
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
print("*")
else:
# middle rooms
# first room (down one, left one)
dungeon.move_to((row - 1), (col + 1))
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_west_wall():
print("|", end='')
else:
print(" ", end='')
print(room.get_letter(), end='')
# second room
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_west_wall():
print("|", end='')
else:
print(" ", end='')
print(room.get_letter(), end='')
if room.has_east_wall():
print("|", end='')
else:
print(" ", end='')
# third room
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
print(room.get_letter(), end='')
if room.has_east_wall():
print("|")
else:
print(" ")
def print_seventh_row(row, col):
orig_x = row
orig_y = col
# room on bottom row
if col == (int(dungeon.get_ny()) - 1):
print(" ")
# print dungeon border
elif col == (int(dungeon.get_ny()) - 2) and row == 0:
print(" *****")
elif col == (int(dungeon.get_ny()) - 2) and row == (int(dungeon.get_nx()) -1):
print("***** ")
elif row == 0:
print(" *", end='')
# first room (down one)
dungeon.move_to(row, (col + 1))
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*", end='')
else:
print(" *", end='')
# second room
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*")
else:
print(" *")
elif row == (int(dungeon.get_nx()) -1):
print("*", end='')
# first room (down one, left one)
dungeon.move_to((row - 1), (col + 1))
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*", end='')
else:
print(" *", end='')
# second room (room to the right)
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-* ")
else:
print(" * ")
else:
(print("*", end=''))
# first room (down one, left one)
dungeon.move_to((row - 1), (col + 1))
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*", end='')
else:
print(" *", end='')
# second room
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*", end='')
else:
print(" *", end='')
# third room
dungeon.move_to((row + 1), col)
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
if room.has_south_wall():
print("-*")
else:
print(" *")
dungeon.move_to(orig_x, orig_y)
print_first_row(x, y)
print_second_row(x, y)
print_third_row(x, y)
print_fourth_row(x, y)
print_fifth_row(x, y)
print_sixth_row(x, y)
print_seventh_row(x, y)
def scan_room(dungeon, adventurer):
"""
Determines if any items in room, and picks up or takes damage
"""
row, col = dungeon.current_room()
room = dungeon.room_at(row, col)
pillars = []
if room.get_healing_potion():
adventurer.pick_up_healing_potion()
room.set_healing_potion(False)
if room.get_vision_potion():
adventurer.pick_up_vision_potion()
room.set_vision_potion(False)
if room.get_pit():
adventurer.fell_into_pit()
game_over(dungeon, adventurer)
if room.get_exit():
game_over(dungeon, adventurer)
if room.get_pillar_a():
room.set_pillar_a(False)
pillars += "A"
if room.get_pillar_e():
room.set_pillar_e(False)
pillars += "E"
if room.get_pillar_i():
room.set_pillar_i(False)
pillars += "I"
if room.get_pillar_p():
room.set_pillar_p(False)
pillars += "P"
for item in pillars:
if item == "A":
adventurer.pick_up_pillar(item)
if item == "E":
adventurer.pick_up_pillar(item)
if item == "I":
adventurer.pick_up_pillar(item)
if item == "P":
adventurer.pick_up_pillar(item)
print_room(dungeon)
def user_input(dungeon, adventurer):
"""This method will allow the user to perform a set of tasks based on the room and
inventory the adventurer holds: Move, use healing/vision potion, view inventory, give up"""
keystroke = input("What would you like to do? Press \"1\" for all options: ")
# print all options
player = adventurer
x, y = dungeon.current_room()
room = dungeon.room_at(x, y)
if keystroke == "1":
options = []
if dungeon.is_valid_room(x, y) is True and room.has_north_wall() is False:
options.append("u")
if dungeon.is_valid_room(x, y) is True and room.has_south_wall() is False:
options.append("d")
if dungeon.is_valid_room(x, y) is True and room.has_east_wall() is False:
options.append("r")
if dungeon.is_valid_room(x, y) is True and room.has_west_wall() is False:
options.append("l")
if adventurer.has_healing_potion():
options.append("h")
if adventurer.has_vision_potion():
options.append("v")
# View other options
options.append("s")
options.append("k")
options.append("q")
print(options)
print_room(dungeon)
user_input(dungeon, adventurer)
# quit option
elif keystroke == "q":
a = input("Temptation to quit is the greatest just before you are about "
"to succeed.\n\nDo you really want to give up? (y or n): ")
if a == "y":
print("\nThere is a difference between giving up and knowing when "
"you had enough.\n\n***GAME OVER***\n")
input("Press Enter to restart....")
restart_game()
elif a == "n":
print("\nYou just can't beat the person who won't give up...\n")
print_room(dungeon)
print("\n")
user_input(dungeon, adventurer)
else:
print("That is not a valid command. Try again.")
# move adventurer
elif keystroke == "u":
x, y = dungeon.current_room()
if dungeon.is_valid_room(x, y) is True and room.has_north_wall() is False:
dungeon.move_to(x, y - 1)
else:
print("That is not a valid command. Try again. ")
print_room(dungeon)
user_input(dungeon, adventurer)
elif keystroke == "d":
x, y = dungeon.current_room()
if dungeon.is_valid_room(x, y) is True and room.has_south_wall() is False:
dungeon.move_to(x, y + 1)
else:
print("That is not a valid command. Try again. ")
print_room(dungeon)
user_input(dungeon, adventurer)
elif keystroke == "l":
x, y = dungeon.current_room()
if dungeon.is_valid_room(x, y) is True and room.has_west_wall() is False:
dungeon.move_to(x - 1, y)
else:
print("That is not a valid command. Try again. ")
print_room(dungeon)
user_input(dungeon, adventurer)
elif keystroke == "r":
x, y = dungeon.current_room()
if dungeon.is_valid_room(x, y) is True and room.has_east_wall() is False:
dungeon.move_to(x + 1, y)
else:
print("That is not a valid command. Try again. ")
print_room(dungeon)
user_input(dungeon, adventurer)
elif keystroke == "s":
print("Status:")
print(player)
print_room(dungeon)
user_input(dungeon, adventurer)
elif keystroke == "k":
print("\nMap Key:\n"
"i = entrance\n"
"o = exit\n"
"A = pillar a\n"
"E = pillar e\n"
"I = pillar i\n"
"P = pillar p\n"
"X = a pit of doom\n"
"V = vision potion\n"
"H = healing potion\n"
"M = multiple items (pillar, pit, potion(s)\n\n"
"User Options:\n"
"u = move up\n"
"d = move down\n"
"l = move left\n"
"r = move right\n"
"h = use healing potion\n"
"v = use vision potion\n"
"s = player status\n"
"q = quit\n")
# use healing potion
elif keystroke == "h":
if adventurer.has_healing_potion():
adventurer.use_healing_potion()
print_room(dungeon)
user_input(dungeon, adventurer)
else:
print("Should have packed a med-kit. You have no healing potions.\n")
print_room(dungeon)
user_input(dungeon, adventurer)
# use vision potion
elif keystroke == "v":
if adventurer.has_vision_potion():
adventurer.use_vision_potion()
show_vision_map(dungeon)
print_room(dungeon)
user_input(dungeon, adventurer)
else:
print("You are blind as a bat. You don't have any vision potions.\n")
print_room(dungeon)
user_input(dungeon, adventurer)
# hidden menu item to show map
elif keystroke == "map":
print(dungeon)
user_input(dungeon, adventurer)
# hidden menu item to show map
elif keystroke == "vision":
show_vision_map(dungeon)
user_input(dungeon, adventurer)
# easter egg
elif keystroke == "python":
webbrowser.open("https://youtu.be/X_-q9xeOgG4")
print_room(dungeon)
user_input(dungeon, adventurer)
else:
print("That is not a valid command. Try again.")
print_room(dungeon)
user_input(dungeon, adventurer)
scan_room(dungeon, adventurer)
user_input(dungeon, adventurer)
def print_dungeon(dungeon):
print(dungeon)
def game_over(dungeon, adventurer):
"""This method determines the end of the game --- 1) LOSE if hero runs out of HP
2) WIN if the adventurer collects all four pillars and finds the exit."""
if not adventurer.is_alive():
print("It is not merely just a flesh wound this time. You died.")
print(dungeon.original_map)
print("\n***GAME OVER***\n")
roll_credits()
input("Press Enter to restart game...")
restart_game()
if dungeon.exit_room() == dungeon.current_room() and adventurer.all_pillars_found():
print("\nHorace Mann once said, \"Be ashamed to die until you have \n"
"won some victory for humanity.\" And today, you won!\n\n"
"Congratulations! You defeated the Dungeon of Doom!\n")
print(dungeon.original_map)
roll_credits()
input("Press Enter to start a new game...")
start_game()
elif dungeon.exit_room() == dungeon.current_room() and not adventurer.all_pillars_found():
print("You need to find all four of the pillars to unlock the exit...\n"
"There are no shortcuts to any place worth going. Back in you go!\n")
else:
return
def roll_credits():
print("Created by Dee \"Python Slayer\" Turco, Kishan \"Code Killer\" Vekaria, "
"and Jeff \"Algo Assassin\" Stockman")
start_game()
|
24bc0c8cf9cca3c13724d0ca33d2f18951af3f56 | Mariia-Kosorotykova/python-education | /python_HW1/calculator/calc.py | 928 | 4.3125 | 4 | """This module works as a simple calculator."""
class Calculator:
"""This class performs 4 simple operations on numbers."""
@staticmethod
def addition(first_number, second_number):
"""This function takes 2 arguments and returns their sum"""
return first_number + second_number
@staticmethod
def subtraction(first_number, second_number):
"""This function takes 2 arguments and returns their difference"""
return first_number - second_number
@staticmethod
def multiplication(first_number, second_number):
"""This function takes 2 arguments and returns their product"""
return first_number * second_number
@staticmethod
def division(first_number, second_number):
"""This function takes 2 arguments and return their quotient"""
return first_number / second_number
calculation = Calculator()
print(calculation.addition(5, 3))
|
c7ee997189ad5dd9b43f2eec0a0670f978c5f6e4 | EricWord/PythonStudy | /10-dict/dict_demo5.py | 264 | 4.375 | 4 | # 字典推导式
dict1 = {"a": 100, "b": 200, "c": 300}
dict2 = {}
for k, v in dict1.items():
dict2[v] = k
print(dict2) # {100: 'a', 200: 'b', 300: 'c'}
# 字典推导式
dict3 = {v: k for k, v in dict1.items()}
print(dict3) # {100: 'a', 200: 'b', 300: 'c'}
|
f11524d94e0dd5412f0fe8c1b49485e7a793a773 | prachi-bindu/Leetcode | /BinArraySorting.py | 632 | 3.90625 | 4 | class BinArraySorting:
def __init__(self):
self.arr = []
def showArray(self):
print(self.arr)
def fillArray(self):
n = int( input("Enter the size of the array-") )
print("Enter the elements in the array-")
for i in range(n):
elem = int( input() )
self.arr.append(elem)
def sortArray(self):
print("2")
self.arr.sort()
self.showArray()
a = BinArraySorting()
#n = int( input("Enter the number of elements in array-") )
a.fillArray()
a.showArray()
a.sortArray()
#a.showArray() |
e449cf2818caa792dc8172e54b966abc4d57962a | pianowow/projecteuler | /138/138.py | 1,636 | 3.671875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: CHRISTOPHER_IRWIN
#
# Created: 28/11/2012
from math import sqrt
from time import clock
clock()
BHLs = []
halfb = 1.5
max = 2000000000
squares = set()
##for x in range(max):
## squares.add(x*x)
print('max:',max)
##while halfb < max:
## b = 2*halfb
## h1 = b-1
## h2 = b+1
## l1 = halfb*halfb + h1*h1
## l2 = halfb*halfb + h2*h2
## if l1 in squares:
## BHLs.append((b,h1,l1))
## print('base',b,'height',h1,'length',l1)
## if l2 in squares:
## BHLs.append((b,h2,l2))
## print('base',b,'height',h2,'length',l2)
## halfb += .5
##print(clock(), 'seconds')
#terms for b printed above follow the pattern of every third term of A121646 from oeis, negated
#so I decided to generate this sequence and check each one
t0 = 1
t1 = 1
t2 = 2
b = t2*t2-t1*t1
sumofLs = 0
while len(BHLs) < 12:
halfb = b/2
h1 = b-1
h2 = b+1
l1 = sqrt(halfb*halfb + h1*h1)
#l2 = sqrt(halfb*halfb+h2*h2)
l2 = sqrt(halfb*halfb + h2*h2)
if l1 % 1 == 0:
BHLs.append((b,h1,l1))
print('base',b,'height',h1,'length',l1)
sumofLs += int(l1)
print('sum of Ls so far:',sumofLs)
if l2 % 1 == 0:
BHLs.append((b,h2,l2))
print('base',b,'height',h2,'length',l2)
sumofLs += int(l2)
print('sum of Ls so far:',sumofLs)
t0,t1 = t1, t2
t2 = t0+t1
b = t2*t2-t1*t1
print(len(BHLs),'found')
print(sumofLs)
print(clock(), 'seconds') |
f437c155abe33882321282af57961b88241f19d2 | preston-scibek/Python | /calculate_pi.py | 375 | 3.6875 | 4 | from __future__ import division
from decimal import Decimal
def calculate_pi(n=1000):
""" calculate pi to n places
negative = False
pi = 0
for i in range(0, n):
if negative:
pi -= 4/(2*i + 1)
negative = False
else:
pi += 4/(2*i + 1)
negative = True
pi = Decimal(pi)
return pi
|
e945332f179b2d16530a652651b102e6395c1755 | predatory123/byhytest | /python_practice/python0603/test.py | 1,052 | 3.9375 | 4 | with open('cats.txt', 'a') as file_object:
print ('If you want to quit , please entert "q".')
while True:
cats_name = input('Please enter your cat\'s name:')
if cats_name == 'q':
break
file_object.write(cats_name + '\n')
with open('dogs.txt', 'a') as file_object:
print ('If you want to quit , please enter "q".')
while True:
dogs_name = input('Please enter your dog\'s name:')
if dogs_name == 'q':
break
file_object.write(dogs_name + '\n')
def count_name(filename):
"""计算一个文件中包含多少个名字"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
print ('Sorry , the file ' + filename + 'does not exist.')
else:
names = contents.split()
count_name = len(names)
print ('The file ' + filename + ' has about ' + str(count_name) + ' names.')
filenames = ['cats.txt', 'dogs.txt']
for filename in filenames:
count_name(filename)
|
52f647b3f234618345407beab2301d006f53b2a3 | behrom/wprowadzenie_do_jezyka_pythona | /laboratorium/Przygotowanie do koła/generatory_iteratory_wyjatki/zad3.py | 221 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def fib_gen():
x, y = 1, 1
while True:
x, y = y, x + y
yield x
fib = fib_gen()
summ = 0
for _ in xrange(30 + 1):
summ += fib.next()
print summ |
90a6f8adc2e33ff423366198e378d600de628c8e | martinazaki/Uni-Work | /COMP1531/20T1-cs1531-lab05/encapsulate.py | 402 | 3.859375 | 4 |
import datetime
class Student:
def __init__(self, firstName, lastName, birthYear):
self.name = firstName + " " + lastName
self.birthYear = birthYear
def name(self):
return self.name
def age(self):
return datetime.datetime.now().year - self.birthYear
if __name__ == '__main__':
s = Student("Rob", "Everest", 1961)
print(f"{s.name()} is {s.age()} old")
|
909c637bf2f4d7b70329526febebf36d50abd841 | jaehui327/PythonProgramming | /Lab0320/Lab03_TurtleGraphic.py | 329 | 4.03125 | 4 | import turtle
t = turtle.Pen()
while True:
direction = input("왼쪽은 left, 오른쪽은 right, 멈추려면 stop을 입력하세요: ")
if direction == "left":
t.left(60)
t.forward(50)
elif direction == "right":
t.right(60)
t.forward(50)
elif direction == "stop":
break
|
a2cb187ec0bb6490006bd8eea196dbb55b4a71e2 | vicb1/python-reference | /code/spark/python-spark-tutorial-master/sparkSql/StackOverFlowSurvey.py | 2,185 | 3.703125 | 4 | from pyspark.sql import SparkSession
AGE_MIDPOINT = "age_midpoint"
SALARY_MIDPOINT = "salary_midpoint"
SALARY_MIDPOINT_BUCKET = "salary_midpoint_bucket"
if __name__ == "__main__":
session = SparkSession.builder.appName("StackOverFlowSurvey").getOrCreate()
dataFrameReader = session.read
responses = dataFrameReader \
.option("header", "true") \
.option("inferSchema", value = True) \
.csv("in/2016-stack-overflow-survey-responses.csv")
print("=== Print out schema ===")
responses.printSchema()
responseWithSelectedColumns = responses.select("country", "occupation",
AGE_MIDPOINT, SALARY_MIDPOINT)
print("=== Print the selected columns of the table ===")
responseWithSelectedColumns.show()
print("=== Print records where the response is from Afghanistan ===")
responseWithSelectedColumns\
.filter(responseWithSelectedColumns["country"] == "Afghanistan").show()
print("=== Print the count of occupations ===")
groupedData = responseWithSelectedColumns.groupBy("occupation")
groupedData.count().show()
print("=== Print records with average mid age less than 20 ===")
responseWithSelectedColumns\
.filter(responseWithSelectedColumns[AGE_MIDPOINT] < 20).show()
print("=== Print the result by salary middle point in descending order ===")
responseWithSelectedColumns\
.orderBy(responseWithSelectedColumns[SALARY_MIDPOINT], ascending = False).show()
print("=== Group by country and aggregate by average salary middle point ===")
dataGroupByCountry = responseWithSelectedColumns.groupBy("country")
dataGroupByCountry.avg(SALARY_MIDPOINT).show()
responseWithSalaryBucket = responses.withColumn(SALARY_MIDPOINT_BUCKET,
((responses[SALARY_MIDPOINT]/20000).cast("integer")*20000))
print("=== With salary bucket column ===")
responseWithSalaryBucket.select(SALARY_MIDPOINT, SALARY_MIDPOINT_BUCKET).show()
print("=== Group by salary bucket ===")
responseWithSalaryBucket \
.groupBy(SALARY_MIDPOINT_BUCKET) \
.count() \
.orderBy(SALARY_MIDPOINT_BUCKET) \
.show()
session.stop()
|
893a9268161d88603f63ca9a6f7393b319bbc055 | bobmwaniki/Andela_BootCamp_Labs | /Week_1/Day_2/http_and_web_lab.py | 1,265 | 4.375 | 4 | import requests
import json
# This short program is a simple command line python application that takes the name of a city and prints out the current weather of the city
# It uses an API from http://openweathermap.org/
api_key = '92f135e73e13bdd8f59b57347820f8af'
def get_weather(city):
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=' + api_key)
weather_info = r.json()
return weather_info
while True:
desired_city = input('Please enter a city name and I will give you the current weather.\nPress enter without any text to exit: ').lower()
if desired_city == '':
break
else:
city_weather = get_weather(desired_city)
if city_weather['name'].lower() == desired_city.lower():
print ('\nThe weather in ' + city_weather['name'] + ', ' + city_weather['sys']['country'] + ' is currently: ' + city_weather['weather'][0]['description'])
print ('Here is some more information on '+ city_weather['name'] + ' (Powered by openweathermaps.org)')
print ('Temperature (in Celsius): ' + str(int(city_weather['main']['temp'] - 273 )))
print ('Humidity: ' + str(city_weather['main']['humidity']))
print ('Pressure: ' + str(city_weather['main']['pressure']))
print ()
else:
print("Sorry. I couldn't get information for that city.\n") |
326287c1f68cb6f394e0b053f7053a14b0a52e04 | BabitaAnandKrishna/SumArray | /Mini_Project.py | 373 | 3.703125 | 4 | PRICE = 200
discount_10 = ['STUDENT10','SPRING10','MEMBER123']
buyer_code = input("Please type your discount code: ")
print('processing....\n')
if buyer_code in discount_10:
final_price = PRICE * 0.9
print("10% discount applied \n")
else:
final_price = PRICE
print("No discount applied \n")
print("Please pay pound{} at checkout".format(final_price))
|
e6556ab4f636904a0e19c578791001dd9e5aaa4a | rzolotarev/Graphs | /Graph/adjacencyMatrixGraph.py | 1,545 | 3.546875 | 4 | import numpy as np
from .abstract import Graph
class AdjacencyMatrixGraph(Graph):
def __init__(self, numVertices, directed=False):
super(AdjacencyMatrixGraph, self).__init__(numVertices, directed)
self.matrix = np.zeros((numVertices, numVertices))
def add_edge(self, v1, v2, weight = 1):
if v1 >= self.numVertices or v2 >= self.numVertices or v1 < 0 or v2 < 0:
raise ValueError("Vertices %d and %d are out of bounds" % (v1, v2))
if weight < 1:
raise ValueError("An edge cannot have weight < 1")
self.matrix[v1][v2] = weight
if self.directed == False:
self.matrix[v2][v1] = weight
def get_adjacent_vertices(self, v):
if v < 0 or v >= self.numVertices:
raise ValueError("Cannot access vertex %d" %v)
adjacent_vertices = []
for i in range(self.numVertices):
if self.matrix[v][i] > 0:
adjacent_vertices.append(i)
return adjacent_vertices
def get_indegree(self, v):
if v < 0 or v >= self.numVertices:
raise ValueError("Cannot access vertex %d" %v)
indegree = 0
for i in range(self.numVertices):
if self.matrix[i][v] > 0:
indegree = indegree + 1
return indegree
def get_edge_weight(self, v1, v2):
return self.matrix[v1][v2]
def display(self):
for i in range(self.numVertices):
for v in self.get_adjacent_vertices(i):
print(i, "-->", v) |
3c3d9f1da15f6ac04cbe07a7431e9c35479af91e | ShishirNanoty/Homework9 | /HW9.py | 1,824 | 3.71875 | 4 | class Vehicle():
def __init__(self,make = 'NA',model = 'NA',year = 1900,weight =0, maint = False,trips = 0):
self.make = make
self.model = model
self.year = year
self.weight = weight
self.maint = maint
self.trips = trips
def setMake(self, make):
self.make = make
def setModel(self, model):
self.model = model
def setYear(self, year):
self.year = year
def setWeight(self, weight):
self.weight = weight
def __str__(self):
return 'Make>>' + self.make +"\n" + 'Model>>' + self.model + "\n" + 'Year>>' + str(self.year) +"\n"+ 'Weight>>' + str(self. weight) + '\n' + 'Maint status>>' + str(self.maint) + '\n' + 'Trips since maint>>' + str(self.trips) + '\n'
class Cars(Vehicle):
def __init__(self,make,model,year,weight, maint = False,trips = 0):
Vehicle.__init__(self,make,model,year,weight, maint,trips)
self.isDriving = False
def Drive(self):
self.isDriving = True
def Stop(self):
self.isDriving = False
self.trips += 60
if self.trips >= 100:
self.maint = True
def Repair(self):
self.maint = False
self.trips = 0
v1 = Cars('Tata', 'Indica', 2010, 1000)
v2 = Cars('BMW', 'XB001', 2017, 1500)
v3 = Cars('Ford', 'KL200', 1995, 1300)
print('Initial state for Car1:\n', v1)
print('Initial state for Car2:\n', v2)
print('Initial state for Car3:\n', v3)
v1.Drive()
v1.Stop()
v1.Drive()
v1.Stop()
# print('Final State for Car1:\n',v1)
v2.Drive()
v2.Stop()
# print('Final State Car2:\n',v2)
v1.Drive()
v2.Drive()
v1.Stop()
v2.Stop()
print('State for Car1:\n',v1)
print('State for Car2:\n',v2)
v1.Repair()
v2.Repair()
print('Final State after maintenance Car1:\n',v1)
print('Final State after maintenance Car2:\n',v2)
|
6244198908f10747599c4894761768753922010e | the-brainiac/twoc-problems | /day6/program_3.py | 256 | 3.5625 | 4 | l = list(map(int,input('Enter elements of list: ').split()))
print('List is : ',l)
l.sort()
print(l)
l1=[]
for i in range(len(l)):
if l[i]>0:
l1=l[i:]
break
print(l1)
for i in range(len(l1)):
if l1[i]!=i+1:
print('missing number is :',i+1)
break
|
ca983200c69927a9548932dd9aa7b16d1a3ede9e | DesireeMcElroy/time-series-exercises | /prepare.py | 1,955 | 3.640625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import acquire
import requests
import os
from datetime import timedelta, datetime
def prep_items(df):
'''
This function takes in dataframe and drops unnecessary columns, adds a month, weekday and sales_total column
'''
# drop extra columns
df.drop(columns=['Unnamed: 0_x', 'Unnamed: 0_y', 'Unnamed: 0'], inplace=True)
# change date column to datetime
df.sale_date = pd.to_datetime(df.sale_date)
# change date to index
df = df.set_index('sale_date').sort_index()
# create month and column year
df['month'] = df.index.month
df['weekday'] = df.index.day_name()
# create sales total column
df['sales_total'] = df.sale_amount*df.item_price
return df
def prep_germany(df):
'''
This function takes in a dataframe and sets the date as index, creates and month and year column,
and fills all the nulls with the mean average of that column
'''
# convert Date column to datetime
df.Date = pd.to_datetime(df.Date)
# set date column as index
df = df.set_index('Date').sort_index()
# make a month and year column
df['month'] = df.index.month
df['year'] = df.index.year
# fill nulls with mean average
values = {'Consumption': df.Consumption.mean(),
'Wind': df.Wind.mean(),
'Solar': df.Solar.mean(),
'Wind+Solar': df['Wind+Solar'].mean()}
df.fillna(value=values, inplace=True)
return df
def split_time_series(df):
'''
This function takes in a dataframe and (based off time series) and returns a train and test df
'''
train_size = .70
n = df.shape[0]
test_start_index = round(train_size * n)
train = df[:test_start_index] # everything up (not including) to the test_start_index
test = df[test_start_index:] # everything from the test_start_index to the end
return train, test |
89d6f31d2aa048f900e56f8a1c17c45f1d9ea403 | smitches/Python | /CS 303/DNA.py | 1,388 | 3.75 | 4 | # File: DNA.py
# Description: This program finds longest similar strand
# Student Name: Brian Smith-Eitches
# Student UT EID: bts867
# Course Name: CS 303E
# Unique Number: 51195
# Date Created: October 26, 2016
# Date Last Modified: October 26, 2016
def main():
in_file=open("./dna.txt","r")
num_pairs=in_file.readline()
num_pairs=num_pairs.strip()
num_pairs=int(num_pairs)
for i in range(num_pairs):
print('Pair', i+1, end='')
print(":", end=' ')
st1=in_file.readline()
st2=in_file.readline()
st1=st1.strip()
st2=st2.strip()
st1=st1.upper()
st2=st2.upper()
if len(st1)>len(st2):
dna1=st1
dna2=st2
else:
dna1=st2
dna2=st1
maxlen=0
wnd=len(dna2)
flag=False
while wnd>1:
start_idx=0
while start_idx+wnd<=len(dna2):
sub_strand=dna2[start_idx:start_idx+wnd]
if dna1.count(sub_strand)>0:
maxlen=len(sub_strand)
print(sub_strand)
print(' ', end='')
flag=True
start_idx+=1
if maxlen>0:
break
wnd-=1
if not flag:
print('No Common Sequence Found')
print()
in_file.close()
main()
|
8f7cb00da84973464271784ab92c370afc2fcc3b | phongluudn1997/leet_code | /three_number_sum.py | 793 | 3.875 | 4 | def usingTwoPointer(array, target):
sorted_array = sorted(array)
result = list()
for index in range(0, len(sorted_array) - 2):
current_number = sorted_array[index]
left = index + 1
right = len(sorted_array) - 1
while left < right:
current_sum = current_number + sorted_array[left] + sorted_array[right]
if current_sum == target:
result.append([current_number, sorted_array[left], sorted_array[right]])
left += 1
right -= 1
elif current_sum < target:
left += 1
else:
right -= 1
return result
if __name__ == '__main__':
array = [12, 3, 1, 2, -6, 5, -8, 6]
result = usingTwoPointer(array, 0)
print(result)
|
e5a09ab05f465a7c2f28a81eb7085729f4479de7 | DeanHe/Practice | /LeetCodePython/StoneGameII.py | 1,766 | 3.75 | 4 | """
Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.
Alice and Bob take turns, with Alice starting first. Initially, M = 1.
On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X).
The game continues until all the stones have been taken.
Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.
Example 1:
Input: piles = [2,7,9,4,4]
Output: 10
Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger.
Example 2:
Input: piles = [1,2,3,4,5,100]
Output: 104
Constraints:
1 <= piles.length <= 100
1 <= piles[i] <= 10^4
"""
from functools import cache
from typing import List
class StoneGameII:
def stoneGameII(self, piles: List[int]) -> int:
max_val = 10 ** 7
n = len(piles)
suffix_sum = piles.copy()
for i in range(n - 2, -1, -1):
suffix_sum[i] += suffix_sum[i + 1]
@cache
def dfs(i, M):
if i == n:
return 0
if i + 2 * M >= n:
return suffix_sum[i]
nxt_player_min = max_val
for x in range(1, 2 * M + 1):
nxt_player_min = min(nxt_player_min, dfs(i + x, max(M, x)))
return suffix_sum[i] - nxt_player_min
return dfs(0, 1) |
b1bfe69687432cb7e9a0cf91a6a74057e5c8cb20 | JunyoungJang/Python | /Introduction/01_Introduction_python/07 Data container type/1 Data container type - List/9 List methods/append, insert, remove.py | 164 | 3.625 | 4 | x = [2, 3]
x.append(4)
print x # [2, 3, 4]
x.insert(2, 'Wow')
print x # [2, 3, 'Wow', 4]
x.remove('Wow')
print x # [2, 3, 4]
|
42ffbdd7004ec2295fd34d7198e88f0b1f741d8e | Zohu0/Python-Codes-For-Beginners | /Sum of its preevious digit.py.py | 147 | 4.09375 | 4 | num= int(input("Enter Any Number: "))
add= 0
for i in range(0, num+1):
add= add+i
print(f"The Sum Of Previous Numbers Of {num} is {add}") |
060f1649a97fa59e835904ebe93198aa64348c18 | simiss98/PythonCourse | /UNIT_1/Module3.2/Required_Code_MOD3_IntroPy.py | 854 | 4 | 4 | # [ ] create, call and test
# then PASTE THIS CODE into edX
def order_price(weight):
# set values for maximum and minimum order variables
maximum = 1000.000
minimum = 0.100
# set value for price variable
price = 7.99
# check order_amount and give message checking against over maximum under minimum
if weight < maximum and minimum < weight:
# else within maximum and minimum give message with calculated price
print("Your order costs $", price * weight)
elif weight > maximum:
print(weight, " is more than currently available")
elif weight < minimum:
print(weight, " is below minimum order amount")
else:
print("not sure what is your weight")
# get order_amount input and cast to a number
print(order_price(weight=float(input("Enter cheese order weight: example 0.400"))))
|
e2bf022866960850ddd933b60f7cbadcf5a234fe | mo7amed115/Titanic | /Titanic.py | 5,903 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
conda --version
# ### Overview
# The data has been split into two groups:
# * training set (train.csv)
# * test set (test.csv)
# The training is set used to build The machine learning models.
#
# The test set is used to see how well The model performs on unseen data. For the test set, We will predict if this Passenger is Survived or Sinked
#
# The gender_submission.csv, a set of predictions that assume all and only female passengers survive, as an example of what a submission file should look like.
# ### Data Describe : -
# #### survival ====> Survival
# * 0 = No
# * 1 = Yes
# #### pclass ====> Ticket class
# * 1 = 1st
# * 2 = 2nd
# * 3 = 3rd
# #### sex ====> Sex
# #### Age ====> Age in years
# #### sibsp ====> # of siblings / spouses aboard the Titanic
# #### parch ====> # of parents / children aboard the Titanic
# #### ticket ====> Ticket number
# #### fare ====> Passenger fare
# #### cabin ====> Cabin number
# #### embarked ====> Port of Embarkation
# * C = Cherbourg
# * Q = Queenstown
# * S = Southampton
#
# In[2]:
# Importing the Important Library :
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# In[3]:
# Importing The Training Dataset :
train_data = pd.read_csv("data/train.csv")
train_data.head()
# In[4]:
train_data.shape
# In[5]:
# general view about missing data on Training Dataset:
train_data.isna().sum()
# In[6]:
# Fill The missing training data on Age with mean :
from sklearn.impute import SimpleImputer
imp = SimpleImputer(strategy='mean')
train_data['Age'] = imp.fit_transform(np.array(train_data['Age']).reshape(-1,1)).astype(int)
# In[7]:
train_data.isna().sum()
# In[8]:
# drop unnecessary Columns :
train_data = train_data.drop(['PassengerId','Name' , 'Fare' , 'Ticket' , "Cabin"], axis=1)
train_data.head()
# In[9]:
train_data.shape
# In[10]:
# Convert string value with numerical :
from sklearn.preprocessing import LabelEncoder
en = LabelEncoder()
train_data['Sex'] = en.fit_transform(train_data['Sex'])
train_data['Embarked'] = en.fit_transform(train_data['Embarked'])
train_data.head()
# In[11]:
# Split the Training Dataset to Features and Target :
X_train = train_data.drop('Survived' , axis = 1)
y_train = train_data.Survived
print(f" The Shape of X_train = {X_train.shape}\n The shape of y_train = {y_train.shape} ")
# In[12]:
train_data.head()
# In[13]:
sns.set_theme = "ticks"
sns.barplot(x = y_train , y = train_data["Age"])
plt.show()
# In[14]:
# Importing The Test Dataset :
test_data = pd.read_csv("data/test.csv")
test_data.head()
# In[15]:
# general view about missing data on Testing Dataset :
test_data.isna().sum()
# In[16]:
# Fill The missing testing data on Age with mean :
from sklearn.impute import SimpleImputer
imp = SimpleImputer(strategy='mean')
test_data['Age'] = imp.fit_transform(np.array(test_data["Age"]).reshape(-1,1)).astype(int)
# In[17]:
test_data.isna().sum()
# In[18]:
# drop unnecessary Columns :
test_data = test_data.drop(['PassengerId','Name' , 'Fare' , 'Ticket' , "Cabin"], axis=1)
test_data.head()
# In[19]:
# Convert string value with numerical :
from sklearn.preprocessing import LabelEncoder
en = LabelEncoder()
test_data['Sex'] = en.fit_transform(test_data['Sex'])
test_data['Embarked'] = en.fit_transform(test_data['Embarked'])
test_data.head()
# In[20]:
# Importing The Anothe Testing Dataset :
test_data2 = pd.read_csv('data/gender_submission.csv')
test_data2.head()
# In[21]:
test_data2.isna().sum()
# In[22]:
# Split the Testing Dataset to Features and Target :
X_test = test_data
y_test = test_data2['Survived']
# In[23]:
print(f"""
At The final :\n
The Shape of X_train : {X_train.shape} .
The Shape of y_train : {y_train.shape} .
The Shape of X_test : {X_test.shape} .
The Shape of y_test : {y_test.shape} .
""")
# In[24]:
# It is a Collection of Machine Learning Algorithms To Estimate And Select The Best Model.
# Classification :
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix
models = {'Logestic_Regression' : LogisticRegression() ,
'KNN' : KNeighborsClassifier() ,
'Random_Forest_Classifier' : RandomForestClassifier() ,
'SVC' : SVC() ,
'Decision_Tree' : DecisionTreeClassifier()
}
def fit_and_score(models , X_train , X_test , y_train , y_test) :
model_scores = {}
model_confusion = {}
for name , model in models.items() :
# fitting the data :
model.fit(X_train , y_train)
model_scores[name] = model.score(X_test , y_test)
y_predict = model.predict(X_test)
model_confusion[name] = confusion_matrix(y_test , y_predict)
return model_scores , model_confusion
# In[25]:
# Calling the Function :
fit_and_score(models = models ,
X_train = X_train,X_test = X_test,
y_train = y_train,y_test = y_test )
# ### Great .....
# #### The Best Machine Learning Algorithm With a Best Accuracy : Logestic_Regression .
# In[26]:
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report , accuracy_score , confusion_matrix
lr = LogisticRegression()
lr.fit(X_train , y_train)
y_pred = lr.predict(X_test)
cm = confusion_matrix(y_test , y_pred)
heat = sns.heatmap(cm)
print(f"""
The Score Of Model : {lr.score(X_test , y_test)} .
The accuracy Score : {accuracy_score(y_test , y_pred)} .
The Classification Report \n {classification_report(y_test , y_pred)}
""")
print(f"The Confusion Matrix : {cm}")
plt.show()
# In[ ]:
|
69f42481a13f1168453670063c73d595d11fefa3 | KeleiAzz/Project-Euler | /4.Largest palindrome product.py | 377 | 3.578125 | 4 | def ispalindrome(x):
digit=[]
t = 1
while t<x:
digit.append(x/t%10)
t*=10
temp=digit[::-1]
#print digit
#print temp
if temp == digit:
return True
else:
return False
result=[]
for i in range(100,1000,1):
for j in range(100,1000,1):
if ispalindrome(i*j):
result.append(i*j)
|
7fbf954d989e1b67e7ea8730ae76f09f578ec3a4 | wangyijie11/pypractice | /base/数据类型-字典2.py | 239 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
dic = {"num": "1001", "account": "wangyj", "username": "小何", "age": "20"}
dic["age"] = 22
print(dic)
del dic["age"]
print(dic)
dic["sex"] = "male"
print(dic)
len(dic)
str(dic)
type(dic) |
d6350124e2f8417990b3db7add58ff87a76ab10e | espresso6615/myPy | /qe.py | 582 | 3.78125 | 4 | import math
a = float(input("a?"))
b = float(input("b?"))
c = float(input("c?"))
while a==0:
print("2차방정식이 아닙니다!!!")
a = float(input("a?"))
b = float(input("b?"))
c = float(input("c?"))
if a!=0:
print("2차방정식이 맞습니다^^")
D = b*b-4*a*c
if D > 0:
x1 = -b+math.sqrt(D)/2*a
x2 = -b-math.sqrt(D)/2*a
print("해가 2개입니다", x1,x2)
if D == 0 :
x = -b/2*a
print("해가 1개입니다", x)
if D < 0:
print("해가 없습니다!")
|
fcbc41299a56e8c91fcc0148399fe63c1df12bb7 | dobby-dobster/random-log-line-printer | /main.py | 523 | 3.546875 | 4 | #!/usr/bin/env python
import random
def GenerateRandomNumbers():
RandomNumbers = [n for n in random.sample(range(1, 11), 5)]
print("Random line numbers: {}").format(RandomNumbers)
return RandomNumbers
def main():
RandomNumbers = GenerateRandomNumbers()
count = 0
for line in open("log.txt"):
count += 1
for item in RandomNumbers:
if count == item:
print("Line number {0}: {1}".format(item, line))
if __name__ == '__main__':
main()
|
9f60d3d310f4955763cf150a8e840053857c7c65 | vickiedge/cp1404practicals | /prac_01/electricity_bill_estimator.py | 285 | 3.96875 | 4 |
cents_per_kWh = int(input("Enter cents per kWh: "))
daily_use = float(input("Enter daily use in kWh: "))
billing_days = int(input("Enter number of billing days: "))
estimated_bill = cents_per_kWh / 100 * daily_use * billing_days
print("Estimated bill: ${:.2f}".format(estimated_bill)) |
67c784919e77d5990f0124e4c68c5b1d2975a593 | Santhosh-23mj/Simply-Python | /EXIF Extract/02_DwnldImage.py | 601 | 3.578125 | 4 | #!/usr/bin/python3
"""
A EXIF data extracter from images in a website
Module 2 - Download all images and store to a file
"""
import urllib
from os.path import basename
def downloadImage(imgTags):
try:
print("[+] Downloading Image......")
imgSrc = imgTags['src']
imgReq = urllib.request.Request(imgSrc)
imgContent = urllib.request.urlopen(imgReq)
imgFilename = basename(urllib.parse.urlsplit(imgSrc)[2])
with open(imgFilename,'wb') as imgFile:
imgFile.write(imgContent)
return imgFilename
except:
return
|
1517e1f8d01f6b79b812bc93ef8df385f6d5466b | iopkelvin/Leetcode-problems | /frequencySort.py | 399 | 4 | 4 | def frequencySort(nums):
record_dict = {}
for i in nums:
if i not in record_dict:
record_dict[i] = 1
else:
record_dict[i] += 1
print('dict ', record_dict)
print('nums ', nums)
print('sort ', sorted(nums, key=lambda x: (record_dict[x], -x)))
return
if __name__ == "__main__":
nums = [1,1,1,2,2,2,3]
print(frequencySort(nums)) |
a240b0974995afc3d2266022e035cdf2ce8c4c88 | pdezonia/space-game | /code/enemy_ai.py | 712 | 3.78125 | 4 | """
|<-------------------------------------------------------------------------->|
|<------------------------------------------------------------------->|
enemy_ai.py is a class definition for the computer controller of
enemy ships. It takes the its own pose and velocity and the postion of
the player, civilian ships, and player allied ships. The AI seeks to
stay close enough to its target to be within vision range, based on
the screen size.
"""
from math import *
import pygame
import cfg
class EnemyAI():
def __init__(self, difficulty):
"""
Initialize trailing distance, attack frequency, and aim delay.
"""
self.target_dist = cfg.screen_height/2
pass |
201b569e282db399f18e1564e984f137c9361af1 | OwenPriceSkelly/ProjectEuler | /p9_pythagoreanTriples.py | 502 | 4.1875 | 4 | #!/usr/bin/env python3
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
# i.e. find a triple that sums to n, and return the product
def pythagoreanTriple(n):
triples = []
# generate pythagorean triples:
for c in range(n):
for b in range(c):
for a in range (b):
if a**2 + b**2 == c**2 and a + b + c == n:
print([a,b,c])
return
return
pythagoreanTriple(1000)
|
522a6c548c9fd679ae6a8f0c2591023895bb4c5c | RipeFruit08/orienteering | /orienteering.py | 13,503 | 3.546875 | 4 | from PIL import Image
import Terrain
import State
import heapq
import time
import sys
import Pixel
pix = None
elevations = []
"""
Generates successors for a given state.
In this situation, a state represents a cell on the map and therefore will have at most
8 different successors. This function calls MakeSuccessor which will handle invalid successors
(i.e. Successors that have x,y coordinate out of bounds or states with terrain out bounds)
:param: the state being used to generate successors
"""
def GetSuccessors(state):
succ = []
x = state.x
y = state.y
gX = state.goalX
gY = state.goalY
# successors to the right
s = MakeSuccessor(x+1, y-1, gX, gY)
if s != None: succ.append(s)
s = MakeSuccessor(x+1, y, gX, gY)
if s != None: succ.append(s)
s = MakeSuccessor(x+1, y+1, gX, gY)
if s != None: succ.append(s)
# above and below
s = MakeSuccessor(x, y+1, gX, gY)
if s != None: succ.append(s)
s = MakeSuccessor(x, y-1, gX, gY)
if s != None: succ.append(s)
# successors to the left
s = MakeSuccessor(x-1, y-1, gX, gY)
if s != None: succ.append(s)
s = MakeSuccessor(x-1, y, gX, gY)
if s != None: succ.append(s)
s = MakeSuccessor(x-1, y+1, gX, gY)
if s != None: succ.append(s)
return succ
"""
Generates a successor based on x, y, gX, and gY
:param: x the x coordinate of successor
:param: y the y coorinaate of successor
:param: gX the x coordinate of the goal
:param: gY the y coordinate of the goal
:return: None if the x or y coordinates are invalid or if the terrain at that successor is out of bounds
otherwise, State object representing the successor is return
"""
def MakeSuccessor(x,y, gX, gY):
if (x < 0 or x >= MAX_X() or y < 0 or y >= MAX_Y()):
return None
ele = elevations[x][y]
ter = Terrain.GetTerrainVal(pix[x,y])
if ter == Terrain.OutOfBounds():
return None
s = State.State(ele,ter,x,y,gX,gY)
return s
"""
Maximum x coordinate value
"""
def MAX_X():
return 395
"""
Maximum y coordinate value
"""
def MAX_Y():
return 500
"""
Checks if a State object, ele, is contained in a list of states, lst
:param: lst, the list of state objects
:param: ele, the state object in question
:return: True if ele is in lst, False otherwise
"""
def contains(lst, ele):
for s in lst:
if s.x == ele.x and s.y == ele.y:
return True
return False
"""
Runs A* search on an initial state, init
:param: init, the initial state
:return: a list of state objects leading from the goal to init
NOTE that the path that gets returned is in reverse order
"""
def A_star(init):
#a* search
pq = []
costs = {}
visited = []
print(init)
costs[init] = 0
heapq.heappush(pq, (init.priority, init))
path = []
parents = {}
parents[init] = None
while True:
state = heapq.heappop(pq)[1]
if (state.isGoal()):
print("finished")
# build path
while(state != None):
path.append(state)
state = parents[state]
return path
break
for s in GetSuccessors(state):
if not contains(visited, s):
#print(s)
visited.append(s)
speed = 1
if (float(s.elevation) > float(state.elevation)):
speed = float(s.elevation) / float(state.elevation) # slower uphill
# movement in the y direction
if (s.x == state.x):
costs[s] = costs[state] + (1/(s.terrain * speed))*Pixel.Latitude()
# movement in the x direction
elif (s.y == state.y):
costs[s] = costs[state] + (1/(s.terrain * speed))*Pixel.Longitude()
# otherwise, diagonal movement
else:
costs[s] = costs[state] + (1/(s.terrain * speed))*Pixel.Diag()
heapq.heappush(pq, (costs[s] + s.priority, s))
parents[s] = state
"""
Takes a list of State objects, lst, and produces 'human readable' output to get
from the first point to the last point
:param: lst, a list of State objects
:return: None, this function prints the human readable output
"""
def hr_output(lst, nth):
prev = lst[0]
dir = 0 # direction
cnt = 0 # number of times to move in that direction
for i in range(len(lst)-1):
next = lst[i+1]
# if x and y are changing -> moving diagonally
if (prev.x != next.x and prev.y != next.y):
# moving northwest
if (next.x < prev.x and next.y > prev.y):
tmp = 1
if dir == tmp:
cnt += 1
else:
hr_print(dir, cnt)
cnt = 1
dir = tmp
# moving northeast
elif (next.x > prev.x and next.y > prev.y):
tmp = 3
if dir == tmp:
cnt += 1
else:
# print out
hr_print(dir, cnt)
cnt = 1
dir = tmp
# moving southwest
elif (next.x < prev.x and next.y < prev.y):
tmp = 6
if dir == tmp:
cnt += 1
else:
# print out
hr_print(dir, cnt)
cnt = 1
dir = tmp
# moving southeast
elif (next.x > prev.x and next.y < prev.y):
tmp = 8
if dir == tmp:
cnt += 1
else:
# print out
hr_print(dir, cnt)
cnt = 1
dir = tmp
# x stays the same -> moving latitudinally (up/down)
elif (prev.x == next.x):
# moving north
if (next.y > prev.y):
tmp = 2
if dir == tmp:
cnt += 1
else:
hr_print(dir,cnt)
cnt = 1
dir = tmp
# moving south
elif (next.y < prev.y):
tmp = 7
if dir == tmp:
cnt += 1
else:
hr_print(dir,cnt)
cnt = 1
dir = tmp
# y stays the same -> moving longitudinally (left/right)
elif (prev.y == next.y):
# moving east
if (next.x > prev.x):
tmp = 5
if dir == tmp:
cnt += 1
else:
hr_print(dir,cnt)
cnt = 1
dir = tmp
# moving west
elif (next.x > prev.x):
tmp = 4
if dir == tmp:
cnt += 1
else:
hr_print(dir,cnt)
cnt = 1
dir = tmp
prev = next
print("Now at control " + str(nth))
print()
"""
prints the 'direction' that you are moving based on dir, cnt
:param: dir integer (1-8) representing the direction you are moving
:param: cnt the number of units to move
:return: nothing, this function prints
"""
def hr_print(dir, cnt):
# no direction was set
if dir == 0:
return
str_dir, multiplier = get_direction(dir)
print("Move " + str(round(multiplier * cnt,1)) + "m in " + str_dir)
"""
Returns the 'direction' that you are moving based on val
:param: val integer (1-8) representing what direction you are moving
"""
def get_direction(val):
switcher = {
1: ("Northwest", Pixel.Diag()),
2: ("North", Pixel.Latitude()),
3: ("Northeast", Pixel.Diag()),
4: ("West", Pixel.Longitude()),
5: ("East", Pixel.Longitude()),
6: ("Southwest",Pixel.Diag()),
7: ("South", Pixel.Latitude()),
8: ("Southeast", Pixel.Diag())
}
return switcher.get(val)
"""
Update pixel mapping based on a particular season
:param: mode int representing which seasons
0 -> summer, no change necessary
1 -> fall, easy movement forests & adjacent cells become slightly harder
2 -> winter, all water that is within 7 pixels of non-water is now ice (slightly easier than rough meadow)
3 -> spring, any pixel within 15 pixels of water without gaining more than 1m in elevation is underwater
:return: nothing, this function modifies the global pixel array
"""
def change_season(mode):
if (mode == 1):
do_fall()
elif (mode == 2):
do_winter()
elif (mode == 3):
do_spring()
else:
return
"""
returns a list of tuples corresponding to the neighbors the tuple coord
:param: coord a tuple representing an x,y coordinate
:return: a list containing tuples representing all valid neighbors of coord
"""
def pixel_neighbors(coord):
x, y = coord
neighbors = []
# neighbors to the right
c = make_neighbor(x+1, y-1)
if c != None: neighbors.append(c)
c = make_neighbor(x+1, y)
if c != None: neighbors.append(c)
c = make_neighbor(x+1, y+1)
if c != None: neighbors.append(c)
# neighbors above and below
c = make_neighbor(x, y+1)
if c != None: neighbors.append(c)
c = make_neighbor(x, y-1)
if c != None: neighbors.append(c)
# neighbors to the left
c = make_neighbor(x-1, y-1)
if c != None: neighbors.append(c)
c = make_neighbor(x-1, y)
if c != None: neighbors.append(c)
c = make_neighbor(x-1, y+1)
if c != None: neighbors.append(c)
return neighbors
"""
returns a tuple representing a coordinate that is not in the out of bounds cell
and has indices that are not out of bounds
:param: x an integer representing an x coordinate
:param: y an integer representing a y coordinate
:return: a tuple, or None if the resulting tuple is invalid
"""
def make_neighbor(x, y):
# validates out of bound indices
if (x < 0 or x >= MAX_X() or y < 0 or y >= MAX_Y()):
return None
ter = Terrain.GetTerrainVal(pix[x,y])
# filters out of bound neighbors
if ter == Terrain.OutOfBounds():
return None
# must be a valid neighbor at this point
return (x,y)
"""
Updates the global pixel array to compensate for the fall season
In the fall, easy movement forest and adjacent cells become harder to traverse
This simulates the fact that in the fall leaves fall obscuring paths
:return: None
"""
def do_fall():
print("do fall was called")
newColor = (128, 128, 128, 255)
oldColor = (255,255,255,255)
print(Terrain.GetTerrainVal((255,255,255,255)))
s = time.time()
for x in range(MAX_X()):
for y in range(MAX_Y()):
if (pix[x,y] == oldColor):
for tup in pixel_neighbors((x,y)):
i, j = tup
t_val = Terrain.GetTerrainVal(pix[i,j])
if pix[i,j] != pix[x,y] and t_val != Terrain.Water() and t_val != Terrain.ImpassibleVeg() and t_val != Terrain.RoughMeadow():
pix[i,j] = newColor
pix[x,y] = newColor
e = time.time()
print(e - s)
"""
Updates the global pixel array to compensate for the winter season
In the winter, all water that is within 7 pixels of land becomes icy
In this implementation icy cells are treated to be about on par with
rough meadows in terms of difficulty. All qualifying cells turn light blue
"""
def do_winter():
print("do winter was called")
newColor = (113, 237, 255, 255)
oldColor = (0,0,255,255)
s = time.time()
for x in range(MAX_X()):
for y in range(MAX_Y()):
if (pix[x,y] == oldColor): # found water
ice_flag = False
for tup in pixel_neighbors((x,y)):
i,j = tup
if (pix[i,j] != oldColor and pix[i,j] != newColor): # if any neighbor is land
ice_flag = True
break
if (ice_flag): # make ice cells
# DLT
winter_DLT(x,y)
pix[x,y] = newColor
e = time.time()
print(e-s)
"""
runs a Depth Limited Traversal from pixel at x,y coloring each
pixel visited light blue, stopping if a non water is seen or
if the depth is reached
:param: x the x coordinate of the originating cell
:param: y the y coordinate of the originating cell
:param: d the depth limited
"""
def winter_DLT(x, y, d = 7):
t_val = Terrain.GetTerrainVal(pix[x,y])
if (t_val != Terrain.Water()):
return
if (d == 0):
return
pix[x,y] = (113, 237, 255, 255)
for tup in pixel_neighbors((x,y)):
i,j = tup
winter_DLT(i,j, d-1)
def do_spring():
print("spring was called")
newColor = (113, 237, 255, 255)
oldColor = (0,0,255,255)
s = time.time()
for x in range(MAX_X()):
for y in range(MAX_Y()):
if (pix[x,y] == oldColor): # found water
underwater = False
for tup in pixel_neighbors((x,y)):
i,j = tup
if (pix[i,j] != oldColor and pix[i,j] != newColor): # if any neighbor is land
underwater = True
break
if (underwater): # make ice cells
# DLT
spring_DLT(x,y,float(elevations[y][x]))
#pix[x,y] = newColor
# bit of a hack, iterate through pixels again and change all "ice" to water to more
# appropriately show that it is underwater
for x in range(MAX_X()):
for y in range(MAX_Y()):
if (pix[x,y] == newColor):
pix[x,y] = oldColor
e = time.time()
def spring_DLT(x, y, base, d = 15):
t_val = Terrain.GetTerrainVal(pix[x,y])
e_val = float(elevations[y][x])
diff = e_val - base
if (diff > 1):
return
if (d == 0):
return
pix[x,y] = (113, 237, 255, 255)
for tup in pixel_neighbors((x,y)):
i,j = tup
t_val = Terrain.GetTerrainVal(pix[i,j])
if (t_val != Terrain.Water() and t_val != Terrain.Ice()):
spring_DLT(i,j, base, d-1)
def main():
global pix
global elevations
img = Image.open('elevations_pixels.PNG')
pix = img.load()
with open('elevations.txt') as f:
elevations = [ line.split() for line in f ]
img.show()
#do_fall()
#do_winter()
#do_spring()
#img.show()
#return
print("done")
print(len(elevations))
points = []
if (len(sys.argv) > 2):
print("argument was passed!")
with open(sys.argv[1]) as f:
points = [tuple([int(i) for i in line.split()]) for line in f]
season = int(sys.argv[2])
change_season(season)
paths = []
stime = time.time()
for i in range(len(points)-1):
start = points[i]
end = points[i+1]
init = State.State(elevations[start[0]][start[1]], Terrain.GetTerrainVal(pix[start[0],start[1]]), start[0], start[1], end[0], end[1])
paths.append(A_star(init))
etime = time.time()
counter = 1
for path in paths:
path.reverse()
hr_output(path, counter)
counter += 1
for s in path:
pix[s.x,s.y] = (255,0,0,255)
print(etime - stime)
img.show()
img.close()
#print(points)
# no file parameter passed, defaults to using points for brown path
else:
print("Usage: python3 orienteering.py file [season mode bit]")
print("\tSEASON MODE BITS")
print("\t0 -> summmer")
print("\t1 -> fall")
print("\t2 -> winter")
print("\t3 -> spring")
points = [(230, 327),(276, 279),(303, 240),(306, 286),(290, 310),(304, 331),(306, 341),(253, 372),(246, 355),(288, 338),(282, 321),(243, 327),(230, 327)]
if __name__ == "__main__":
main()
|
690d9f99a2ec2fbd896cce76ffb23e7385071634 | matt23177/Simple-Python-Game | /game.py | 709 | 3.828125 | 4 | import random
def start():
print('Hello! The objective of the game is to collect money')
a = input("Do you want to play?")
if a.lower() in ('y', 'yes'): #If user inputs one of the following, game starts with 0 money.
Game(0)
def Game(money):
number = random.randint(1,51) #generate a random number
pick = input("Do you want to pick money?")
if pick.lower() in ('y', 'yes'):
money += number
print(f"You caught {number} bucks\nYou currently have {money} bucks")
Game(money)
else:
invest = input("Want to double your earnings?")
if invest.lower() in ('y', 'yes'):
print(f"You just got {money}!")
money *= 2
Game(money)
start()
|
d53fe0c76a81aaeea46a5a7d62437546adcea2aa | ArBond/ITStep | /Python/lessons/lesson10_function/main5.py | 940 | 4.59375 | 5 | # 5. Напишите функцию capitalize(), которая принимает слово из маленьких латинских букв
# и возвращает его же, меняя первую букву на большую. Например, print(capitalize('word')) должно печатать слово Word.
# На вход подаётся строка, состоящая из слов, разделённых одним пробелом. Слова состоят из маленьких латинских букв.
# Напечатайте исходную строку, сделав так, чтобы каждое слово начиналось с большой буквы.
# При этом используйте вашу функцию capitalize().
def capitalize(srting):
print(srting.title())
srting = str(input("Vvedite slova malen'kimi bykvami cherez probel: "))
capitalize(srting) |
29efaa4cb0c7adbd42c7c7a258b46114f10faa6e | lloyd108/python_start | /09-Coroutine/myIter.py | 603 | 3.921875 | 4 | from collections import Iterable, Iterator
l1 = [i for i in range(10)]
print(isinstance(l1, Iterator))
print(isinstance(l1, Iterable))
s1 = "This a simple string."
print(isinstance(s1, Iterator))
print(isinstance(s1, Iterable))
s1_iter = iter(s1)
print(isinstance(s1_iter, Iterator))
print(isinstance(s1_iter, Iterable))
print(s1_iter.__next__())
print(next(s1_iter), next(s1_iter))
def my_func():
print("step1")
yield 1
print("step2")
yield 2
print("step3")
yield 3
return None
a = my_func()
a1 = next(a)
a2 = next(a)
a3 = next(a)
# a4 = next(a)
print(a1, a2, a3)
|
6bdb955d481d3363c175b9c490ec40c0b09890d6 | cuberisu/College | /2021-1/4.py | 473 | 3.703125 | 4 | #casting
print("안녕" + "잘 지내니")
# print("너 혹시 몇 살이니?" + 19 + "살이야") # 형식에러: 문자형만 문자형에 연결 가능.
#"문자열과 숫자형은 연결할 수 없다."
print("너 혹시 몇 살이니?"+ str(19) + "살이야") # 숫자형 19를 문자형으로 변환
x = 19 # 숫자형
y = "19" # 문자형
print(str(x) + y) # x를 문자형으로 변환 (캐스팅)
print(x + int(y)) # y를 숫자형으로 변환 |
03f8adb98b68d7dc9119f11281b93f8af806bc6a | camillevidalpy/algorithmie-data | /tp/TP3_COLLECTIONS_correction.py | 5,207 | 4.09375 | 4 | """
Structures de données Listes, Tuples et dictionnaires
"""
"""
Exercice 1
"""
t = [1, 2, 3, 4, 5]
a = t[0] + t[3] # 1 + 4 ==> 5
b = t[-1]
c = t[3:]
a = a + t[-2]
print(type(t)) # t est une liste
# Afficher les valeurs de a, b et c:
print(a)
print(b)
print(c)
# Soit `i` un entier quelconque: t[-i] renvoie les i derniers éléments de la liste
# Soit `j` un entier quelconque, que renvoie l'instruction t[j:] renvoie les éléments dont l'indice est plus grand que j
# t[-30] renvoie une erreur car 30 est supérieur à la taille de la liste
abc = ["A", "B", "C", "D", "E"]
# Affiche D
print(abc[3])
# Affiche les 3 dernières lettres
print(abc[-3])
"""
Exercice 2
"""
# On considère le programme suivant:
liste = [1, 4, 1, 2, 1, 5, 3, 1, 12]
a = len(liste)
b = liste[0]
liste.append(0)
c = len(liste)
d = liste[-1]
print(a)
print(b)
print(c)
print(d)
# len(liste) renvoie la taille de la liste
# Soit `i` un entier quelconque, liste.append(i) ajoute l'élément i à la fin de la liste
# Ajouter les entiers suivants à la liste: `2`, `9`, `1`
liste.append(2)
liste.append(9)
liste.append(1)
liste_2 = [3, 6, 8]
# Ajouter les éléments de `liste_2` à la liste.
liste.extend(liste_2)
# Supprimer tous les `1` de la liste
while liste.count(1) > 0 :
liste.remove(1)
# Quelle méthode permet de trier une liste ?
help(list())
# ---> méthode sort()
# Trier la liste
liste.sort()
# Afficher le minimum et le maximum de la liste (sans utiliser de fonction).
min_liste = 0
max_liste = 0
for element in liste:
if element > max_liste:
max_liste = element
if element < min_liste:
min_liste = element
print("Minimum", min_liste, "Maximum", max_liste)
print("Minimum", min(liste), "Maximum", max(liste))
# A l'aide d'une boucle `for`, calculer la somme des éléments de la liste.
somme_liste = 0
for element in liste:
somme_liste += element
print("Somme", somme_liste)
print("Somme", sum(liste)) # ATTENTION: la méthode sum ne fonctionne que si tous les éléments de la liste sont du même type
"""
Exercice 3: moyenne de la classe
"""
grades = [8, 12, 15, 6, 10, 19, 18, 7, 13, 15, 8, 15, 17, 13, 12, 15, 16, 9, 10, 3, 19, 20, 15]
# Afficher l'écart entre le max et le min de la liste `grades`
min_grades = min(grades)
max_grades = max(grades)
print(max_grades - min_grades)
# Afficher le nombre d'élèves
print(len(grades))
# # Un élève était absent, il a rattrapé le controle et obtenu la note de 14. Rajouter cette note à la liste des notes.
grades.append(14)
print(grades)
#Il y a eu une faute de frappe sur la cinquième note. L'élève a eu en réalité 13. Modifier sa note.
grades[4] = 13
print(grades)
# Quelle est la moyenne de la classe?
moyenne = sum(grades)/(len(grades))
print (moyenne)
# Quelle est la médiane de la classe?
sorted_grades = sorted(grades)
nb_eleves = len(grades)
moitie = int(nb_eleves / 2)
print(sorted_grades[moitie])
"""
(Bonus) Un élève doit obtenir une note supérieure ou égale à 10 pour valider la matière.
Un élève qui a obtenu entre 8 et 10 peut effectuer une session de rattrapage
Combien de personnes ont validé la matière?
Combien de personnes peuvent aller aux rattrapages?
Combien de personnes ont échoué (note strictement inférieure à 8)?
"""
nb_personnes_valider = 0
nb_personnes_rattrapage = 0
nb_personnes_echouer = 0
for note in grades:
if note >= 10:
nb_personnes_valider = nb_personnes_valider + 1
elif note >= 8:
nb_personnes_rattrapage += 1
else:
nb_personnes_echouer += 1
print(nb_personnes_valider)
print(nb_personnes_rattrapage)
print(nb_personnes_echouer)
"""
Exercice 4: dictionnaires
"""
awesome_couples = {
'Batman': 'Robin',
'Harley Quinn': 'Poison Ivy',
'Iron man': 'War machine',
'Phenix' : 'Cyclope',
'Bob sponge square': 'Patrick'
}
a = awesome_couples['Phenix'] # On récupère la valeur de la clé Phenix
bob = 'Bob sponge square'
b = (bob, 'Patrick') in awesome_couples.items() # "Le couple (Bob sponge square, Patrick starfish) est-il dans le dico?
awesome_couples['Ant man'] = 'the Wasp' # ajout du couple (Ant-Man, the Wasp)
del awesome_couples['Bob sponge square'] # suppression de la clé Bob sponge square
c = bob in awesome_couples # La clé Bob sponge square est-elle dans le dico?
d = awesome_couples.get(bob, 'unknown') # On récupère la valeur de la clé Phenix, si on ne la trouve pas on prend comme valeur 'unknown'
e = awesome_couples.get('Ant man', 'toto') # On récupère la valeur de la clé Ant man, si on ne la trouve pas on prend comme valeur 'toto'
print(a)
print(b)
print(c)
print(d)
print(e)
"""
Afficher le texte suivant à l'écran:
```
L'acolyte de Batman est Robin
L'acolyte de Harley Quinn est Poison Ivy
L'acolyte de Iron man est War machine
L'acolyte de Phenix est Cyclope
L'acolyte de Ant man est the Wasp
```
"""
for (k, v) in awesome_couples.items():
print("L'acolyte de", k, " est", v)
# Remplacer la valeur de clé `Phenix` par `Jean Grey`
print("Dico avant modif:", awesome_couples)
awesome_couples["Jean Grey"] = awesome_couples["Phenix"]
del awesome_couples["Phenix"]
print("Dico après modif:", awesome_couples)
|
37acf7b7bcf8fea745a7c1fc8dd6ec8c782d68f4 | frnkvsk/python100days | /day22_pong/draw_number.py | 8,056 | 3.640625 | 4 | from turtle import Turtle
class DrawScore:
def __init__(self, num, x, y):
self.segments = [[] for _ in range(5)]
self.create_segments(x, y)
self.draw_number(num)
def create_segments(self, x, y):
for i in range(0, 5):
for j in range(0, 3):
t = Turtle('square')
t.shapesize(stretch_wid=.5, stretch_len=.5)
t.goto(x + (j * 10), y - (i * 10))
self.segments[i].append(t)
def draw_number(self, num):
if num == 0:
self.segments[0][0].color('white')
self.segments[0][1].color('white')
self.segments[0][2].color('white')
self.segments[1][0].color('white')
self.segments[1][1].color('black')
self.segments[1][2].color('white')
self.segments[2][0].color('white')
self.segments[2][1].color('black')
self.segments[2][2].color('white')
self.segments[3][0].color('white')
self.segments[3][1].color('black')
self.segments[3][2].color('white')
self.segments[4][0].color('white')
self.segments[4][1].color('white')
self.segments[4][2].color('white')
elif num == 1:
self.segments[0][0].color('black')
self.segments[0][1].color('black')
self.segments[0][2].color('white')
self.segments[1][0].color('black')
self.segments[1][1].color('black')
self.segments[1][2].color('white')
self.segments[2][0].color('black')
self.segments[2][1].color('black')
self.segments[2][2].color('white')
self.segments[3][0].color('black')
self.segments[3][1].color('black')
self.segments[3][2].color('white')
self.segments[4][0].color('black')
self.segments[4][1].color('black')
self.segments[4][2].color('white')
elif num == 2:
self.segments[0][0].color('white')
self.segments[0][1].color('white')
self.segments[0][2].color('white')
self.segments[1][0].color('black')
self.segments[1][1].color('black')
self.segments[1][2].color('white')
self.segments[2][0].color('white')
self.segments[2][1].color('white')
self.segments[2][2].color('white')
self.segments[3][0].color('white')
self.segments[3][1].color('black')
self.segments[3][2].color('black')
self.segments[4][0].color('white')
self.segments[4][1].color('white')
self.segments[4][2].color('white')
elif num == 3:
self.segments[0][0].color('white')
self.segments[0][1].color('white')
self.segments[0][2].color('white')
self.segments[1][0].color('black')
self.segments[1][1].color('black')
self.segments[1][2].color('white')
self.segments[2][0].color('white')
self.segments[2][1].color('white')
self.segments[2][2].color('white')
self.segments[3][0].color('black')
self.segments[3][1].color('black')
self.segments[3][2].color('white')
self.segments[4][0].color('white')
self.segments[4][1].color('white')
self.segments[4][2].color('white')
elif num == 4:
self.segments[0][0].color('white')
self.segments[0][1].color('black')
self.segments[0][2].color('white')
self.segments[1][0].color('white')
self.segments[1][1].color('black')
self.segments[1][2].color('white')
self.segments[2][0].color('white')
self.segments[2][1].color('white')
self.segments[2][2].color('white')
self.segments[3][0].color('black')
self.segments[3][1].color('black')
self.segments[3][2].color('white')
self.segments[4][0].color('black')
self.segments[4][1].color('black')
self.segments[4][2].color('white')
elif num == 5:
self.segments[0][0].color('white')
self.segments[0][1].color('white')
self.segments[0][2].color('white')
self.segments[1][0].color('white')
self.segments[1][1].color('black')
self.segments[1][2].color('black')
self.segments[2][0].color('white')
self.segments[2][1].color('white')
self.segments[2][2].color('white')
self.segments[3][0].color('black')
self.segments[3][1].color('black')
self.segments[3][2].color('white')
self.segments[4][0].color('white')
self.segments[4][1].color('white')
self.segments[4][2].color('white')
elif num == 6:
self.segments[0][0].color('white')
self.segments[0][1].color('white')
self.segments[0][2].color('white')
self.segments[1][0].color('white')
self.segments[1][1].color('black')
self.segments[1][2].color('black')
self.segments[2][0].color('white')
self.segments[2][1].color('white')
self.segments[2][2].color('white')
self.segments[3][0].color('white')
self.segments[3][1].color('black')
self.segments[3][2].color('white')
self.segments[4][0].color('white')
self.segments[4][1].color('white')
self.segments[4][2].color('white')
elif num == 7:
self.segments[0][0].color('white')
self.segments[0][1].color('white')
self.segments[0][2].color('white')
self.segments[1][0].color('black')
self.segments[1][1].color('black')
self.segments[1][2].color('white')
self.segments[2][0].color('black')
self.segments[2][1].color('black')
self.segments[2][2].color('white')
self.segments[3][0].color('black')
self.segments[3][1].color('black')
self.segments[3][2].color('white')
self.segments[4][0].color('black')
self.segments[4][1].color('black')
self.segments[4][2].color('white')
elif num == 8:
self.segments[0][0].color('white')
self.segments[0][1].color('white')
self.segments[0][2].color('white')
self.segments[1][0].color('white')
self.segments[1][1].color('black')
self.segments[1][2].color('white')
self.segments[2][0].color('white')
self.segments[2][1].color('white')
self.segments[2][2].color('white')
self.segments[3][0].color('white')
self.segments[3][1].color('black')
self.segments[3][2].color('white')
self.segments[4][0].color('white')
self.segments[4][1].color('white')
self.segments[4][2].color('white')
elif num == 9:
self.segments[0][0].color('white')
self.segments[0][1].color('white')
self.segments[0][2].color('white')
self.segments[1][0].color('white')
self.segments[1][1].color('black')
self.segments[1][2].color('white')
self.segments[2][0].color('white')
self.segments[2][1].color('white')
self.segments[2][2].color('white')
self.segments[3][0].color('black')
self.segments[3][1].color('black')
self.segments[3][2].color('white')
self.segments[4][0].color('white')
self.segments[4][1].color('white')
self.segments[4][2].color('white')
|
b7a6532244f11867a266a56fba683a190cd841d2 | jemtca/CodingBat | /Python/String-1/make_abba.py | 232 | 4.03125 | 4 |
# given two strings, a and b, return the result of putting them together in the order abba
def make_abba(a, b):
return a + b + b + a
print(make_abba('Hi', 'Bye'))
print(make_abba('Yo', 'Alice'))
print(make_abba('What', 'Up'))
|
f4913d81f2eced840f9ac8402fc0d450cb66451b | cgoeke/python-crash-course | /exercises/chapter-10/programming_poll.py | 471 | 4.34375 | 4 | # 10-5. Programming Poll: Write a while loop that asks people why they like
# programming. Each time someone enters a reason, add their reason to a file
# that stores all the responses.
filename = 'programming_poll.txt'
while True:
print("\nEnter 'q' to exit the program.")
reason = input("Why do you like programming? ")
if reason == 'q':
break
else:
with open(filename, 'a') as file_object:
file_object.write(reason + "\n") |
94fd5b32d4186917f525f24f55db37e3390f7e92 | TheLunchtimeAttack/matasano-challenges | /python/matasano/set1/c2.py | 950 | 3.75 | 4 | from matasano.util.converters import *
from matasano.util.byte_xor import xor
def hex_string_xor(hex1string, hex2string):
"""
A complete function for reading in two hex strings and outputting a string of the xor of the two inputs
:param hex1_string: a string of ASCII encoded hex characters
:param hex2_string: a string of ASCII encoded hex characters
:return: a string of ASCII encoded hex characters
"""
assert type(hex1string) == str
assert type(hex2string) == str
hex1bytes = hex_to_bytestr(hex1string)
hex2bytes = hex_to_bytestr(hex2string)
outputbytes = xor(hex1bytes, hex2bytes)
print(outputbytes)
outputstring = bytestr_to_hex(outputbytes)
return outputstring
if __name__ == "__main__":
hexinput1 = "1c0111001f010100061a024b53535009181c"
hexinput2 = "686974207468652062756c6c277320657965"
xor = hex_string_xor(hexinput1, hexinput2)
print(xor)
|
76b2c73047d70c101b74139d2410078c4ef3b0e6 | Richarjw/Rose-Hulman-CSSE120 | /Tkinter_ttk/src/m99.py | 857 | 3.78125 | 4 | """
Try out Tkinter and ttk!
"""
import rosegraphics as rg
import tkinter
from tkinter import ttk
def main():
# Make a window.
# Put a Frame on it.
# Put a Button on the frame.
# Make your Button do something simple.
# Add a Label and an Entry.
# Make your Button do something with the Label and Entry.
window = rg.RoseWindow(500, 500)
root = tkinter.Tk()
frame = ttk.Frame(root, padding=(50, 20), relief='raised')
frame.grid()
change_something = ttk.Button(frame, text='This Changes Something')
# ----------------------------------------------------------------------
# If this module is running at the top level (as opposed to being
# imported by another module), then call the 'main' function.
# ----------------------------------------------------------------------
if __name__ == '__main__':
main()
|
f4acbb13817bb6f1c1f98881894fe5b10aeb7e56 | minhnhoang/hoangngocminh-fundamental-c4e23 | /session2/homework2/serious_exc1.py | 384 | 4.15625 | 4 | height = int(input("Your heith (cm): "))
m = int(input("Your weight (kg): "))
h = height/100
bmi = round(m / (h*h),1)
print("Your BMI:", bmi)
if bmi < 16:
print("You are severely underweight!")
elif bmi < 18.5:
print("You are underweight!")
elif bmi < 25:
print("You are of normal weight!")
elif bmi < 30:
print("You are overweight!")
else:
print("You are obese!") |
03a61844f6dce5cc05d3a8132436288bc6375519 | wertqyuio/leetcode-problems | /1374_generate_string_with_odd_counts.py | 1,227 | 3.765625 | 4 | class Solution:
def generateTheString(self, n: int) -> str:
# note there are a few cases
# first case is when n == 1
# second case is when n is divisible by 2
# third case is when n is not divisible by 2
# there is easy solution where there's odd or even
# also learned about bitwise & where returns smaller corresponding
# i.e. if 4 & 28 then returns 4
def _return_odd_pair(num):
if not (num//2 % 2):
return (num//2-1,num//2)
else:
return (num//2,num//2)
answer = ""
if n == 1:
return "a"
elif not n % 2:
number_of_loops = _return_odd_pair(n)
for i in range(number_of_loops[0]):
answer += "bc"
for j in range(number_of_loops[0], number_of_loops[1]):
answer += "cc"
else:
answer = "a"
number_of_loops = _return_odd_pair(n-1)
print(number_of_loops)
for i in range(number_of_loops[0]):
answer += "bc"
for j in range(number_of_loops[0],number_of_loops[1]):
answer += "cc"
return answer
|
e41abfb54dd192eb8e6850aba9a8cac7ef69b921 | Boombarm/onlinejudge | /Python/src/uri_beecrowd/ADHOC/P3408_Ignore_the_Letters.py | 170 | 3.75 | 4 | import re
n = int(input())
answer = 0
for i in range(n):
text = input()
nums_arr = re.findall("[0-9]+", text)
num = int("".join(nums_arr))
answer += num
print(answer) |
f1730811a404b9b297d7e9df28884eb8124f6a21 | chix08/Code | /countingsort.py | 495 | 3.671875 | 4 | '''
k = Range
n = length
arr = array
'''
arr = [9,8,7,6,5,4,3,2,1,0]
def sortarray(acount, actualarr, n):
a = [0 for i in range(n)]
for i in actualarr:
a[acount[i] - 1] = i
acount[i] -= 1
return a
def countnum(k, arr):
a = [0 for i in range(k)]
for i in arr:
a[i] = a[i] + 1
for i in range(k - 1):
a[i + 1] = a[i] + a[i + 1]
b = sortarray(a, arr, len(arr))
return b
length = len(arr)
k = 10
b = countnum(k, arr)
print(b)
|
07f98d8fbaa787454ef49e996fe16725e02ace45 | Rahul4269/Django | /Django Day3.py | 276 | 4.09375 | 4 | '''s="this is python"
for x in iter(s):
print(x)
s = "this is python"
itr=iter(s)
print(next(itr))
print(next(itr))'''
s="this is python"
for x in iter(s):
print(x)
s = "this is python"
itr=iter(s)
for i in range (0,len(s)):
print(next(itr))
|
97a32b150f4a8c39a393e8e0014b8ca7f4178c8e | lewis-munyi/MSOMA-Boot-camp | /exponentials.py | 385 | 4.03125 | 4 | key = 0
while key == 0:
choice = int(input("1. Proceed\n2. Exit\n"))
if choice == 1:
base = input("Enter the base:\n")
exponent = input("Enter the exponent:\n")
output = int(base) ** int(exponent)
print(str(base) + " to the power of " + str(exponent) + " is " + str(output) + "\n\n")
pass
else:
key = 1
pass
pass
|
595f927878c79c94ca67f5c12aea0ae914948786 | ShirleyMwombe/Training2 | /higher order functions.py | 1,248 | 4.3125 | 4 | # Higher Order Function = a function that either:
# 1. accepts a function as an argument
# or
# 2. returns a function
# (In python, functions are also treated as objects)
def loud(text):
return text.upper()
def quiet(text):
return text.lower()
def hello(func): # accepts loud function as func # higher order function
text = func('Hello') # loud renamed to func, accepts Hello as an argument
print(text)
hello(loud) # calling the hello function with loud function as an argument
hello(quiet) # calling the hello function with quiet function as an argument
# example 2
def divisor(x):
def dividend(y): # function skipped at first because it's not called yet
return y/x
return dividend # divisor accepts value of x and returns dividend function
divide = divisor(3) # calls divisor functions and assigns value of 3 to x (value of x is 3)
# divisor returns dividend function, which is hence assigned to dividend variable
# therefore divide=dividend()
print(divide(15)) # same value as print(dividend(10) # assigns 15 to y
|
29789cbecc3d5f4ed6f2fbd576a8d4182cf89fb3 | underseatravel/AlgorithmQIUZHAO | /Week_06/557_reverse_words_in_a_string3.py | 239 | 4 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 10:54
# @Author : weiyu
# @File : 557_reverse_words_in_a_string3.py
class Solution:
def reverseWords(self, s):
return " ".join(c[::-1] for c in s.split())
|
f169abf6d2d27314309212942368889b20a54a25 | tzpBingo/github-trending | /codespace/python/tmp/piecewise.py | 292 | 3.953125 | 4 | """
分段函数求值
3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1)
Version: 0.1
Author: 骆昊
Date: 2018-02-28
"""
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))
|
f87f6a605e6c2ae6dc83035abdce201272733b2b | tdnzr/project-euler | /Euler145.py | 1,147 | 4.125 | 4 | # Solution to Project Euler problem 145.
# The following solution works, but it's glacially slow.
# It got the correct result after ~1250s on my machine.
def all_digits_odd(n):
"""Returns True if n contains only odd digits, False otherwise."""
# Because we have to turn n into a string to loop over it,
# this test for oddness is much faster than converting each
# digit-string back into an integer and taking it modulo 2.
for digit in str(n):
if digit in {"0", "2", "4", "6", "8"}:
return False
else:
return True
def run():
count_reversible = 0
for i in range(1_000_000_000): # numbers below one billion
# Skip numbers which end in a zero - their reverse
# would have a leading zero, which isn't allowed.
if i % 10 == 0:
continue
# Otherwise, reverse i, add i and reverse_i together,
# and test whether all digits in this sum are odd.
reverse_i = int(str(i)[::-1])
if all_digits_odd(i + reverse_i):
count_reversible += 1
return count_reversible
if __name__ == "__main__":
print(run())
|
8eca0f4c31bd309ac87bf7217baccd322373eb37 | dvardoo/randdict4 | /randdict4.py | 1,241 | 3.71875 | 4 | import random
import string
# -*- coding: utf-8 -*-
#Function for getting a random passphrase
#Choses 4 random words from wordlist and concatenates as passphrase.
def passwd():
with open('/usr/share/dict/american-english', 'r') as allWords:
wordList = allWords.read()
wordList = wordList.split()
#Collects 4 random words and joins these to get the passphrase.
for word in wordList:
randWord1 = random.choice(wordList)
randWord2 = random.choice(wordList)
randWord3 = random.choice(wordList)
randWord4 = random.choice(wordList)
randPasswd = '{0}{1}{2}{3}'.format(randWord1,randWord2,randWord3,randWord4)
#Checks if password is longer then 20 characters, if not it runs again.
if len(randPasswd) > 20:
print('*' * len(randPasswd) + '*****','\n',
'Random words are:\n', randWord1.capitalize(), randWord2.capitalize(), randWord3.capitalize(), randWord4.capitalize())
print('*' * len(randPasswd) + '*****','\n',
'Random passphrase is:\n',randPasswd, '\n Passphrease length:', len(randPasswd), 'characters')
print('*' * len(randPasswd) + '*****')
else:
print('Short random passphrase, run again')
passwd()
|
b75e0de3aafbebffbfd21b3ddaa53ad467eaf885 | ymzkd/LearningFlask | /Response/kakezan.py | 930 | 3.734375 | 4 | from flask import Flask, request
# Flaskオブジェクトの生成
app = Flask(__name__)
# ルート( / )へアクセスがあった時 --- (*1)
@app.route("/", methods=["GET", "POST"])
def root():
if request.method == "GET":
return """
<html><body>
<form action="/" method="POST">
<input type="text" name="a"> ×
<input type="text" name="b">
<input type="submit" value="計算">
</form>
"""
else: # POST時
a = int(request.form.get("a"))
b = int(request.form.get("b"))
r = a * b
return """
<html><body>
答えは{}です。
<form action="/" method="POST">
<input type="text" name="a"> ×
<input type="text" name="b">
<input type="submit" value="計算">
</form>
""".format(str(r))
# サーバーを起動
if __name__ == "__main__":
app.run(debug=True)
|
396dd6af844be9e77e766d909fb121c96c3fef87 | lucasjct/python_curso_em_video | /Mundo_2/if_elif/ex42.py | 576 | 4.125 | 4 | l1 = int(input('Digite um número: '))
l2 = int(input('Digite outro número: '))
l3 = int(input('Digite só mais um número: '))
if l1+l2 >= l3 and l2+l3 >= l1 and l3+l1 >= l2:
print('Estas três medidas formam um triângulo ', end='')
if l1 == l2 == l3:
print('EQUILÁTERO (todos os lados iguais).')
elif l1 == l2 != l3 or l2 == l3 != l1 or l1 ==l3 != l2:
print('ISÓSCELES (dois lados iguais e um diferente).')
else:
print('ESCALENO (três lados diferentes).')
else:
print('Estas três medidas NÃO podem formar um triângulo.')
|
66f5c870c701539f707199ae62e9174946ed66f7 | pratikbubne/Python | /logicalPython.py | 3,296 | 3.75 | 4 | # name = "A2D3"
# #AADDD
# newString = ""
# for item in name:
# if item.isalpha():
# x = item #x = D
# else:
# newString = newString + int(item) * x
# print(newString)
# name = "4D3C"
# #DDDDCCC
# blank = " "
# for char in name:
# if char.isnumeric():
# x = int(char)
# else:
# blank = blank + char * x
# print(blank)
# name ="A4D3C2"
# # AAAADDDCC
# blank = ""
# for char in name:
# if char.isalpha():
# x = char # A #D
# else:
# blank = blank + x * int(char) #AAAADDD
# print(blank)
#name ="4A3D2C"
# #AAAADDDCC
# blank = ""
# for char in name:
# if char.isnumeric():
# x = char # A #D
# else:
# blank = blank + int(x) * char #AAAADDD
# print(blank)
# name = "AAAAACCCCDDZ"
# seta = sorted(set(name))
# blank = ""
# for item in seta:
# a = item + str(name.count(item))
# blank = blank + a
# print(blank)
# name = "AAAZZZZZIIIIIMMMMMEEEEEUUUUUIIIIIOOOOOOOUUUUU"
# namey = sorted(set(name))
# namec = ["A","E","I","O","U"]
# print(namec)
# for item in namey:
# if item in namec:
# print(item,name.count(item))
#sum()
# LEVEL # PALINDROME
# name = "LEVEL"
# rev = name[::-1]
#
# if name == rev:
# print('print PALINDROME')
#LISTEN SILENT ANAGRAMS
name = "LISTEN"
name2 = "SILENT"
setA = set(name)
setB = set(name2)
if len(name) == len(name2):
if setA == setB:
print('ANAGRAMS')
# a2h2w3
#achjwz
# ASCII
# "BOOK"
# {B:1}
name = "AAAAACCCCDDZ"
dict = {}
for item in name:
dict[item] = dict.get(item,0) +1
print(dict)
blank = ""
for k,v in dict.items():
blank = blank + (k+str(v))
print(blank)
lista= [2001, 2002]
ageNew =[]
for i in lista:
age = 2021 - lista[i]
#******************************************************
#20/02/2021
# listA = [2002,2000,1998,1997,1996,2008]
# bill = [300,200,500,700,50,700]
# #discount = [30,]
# #[18,20,22,23,24,12]
# #[2012,2010,2008]
# #[354,....]
# def returnList(list,fn):
# listC = []
# for item in list:
# listC.append(fn(item))
# return listC
#
# def calDicount(el):
# return 0.10 * el
#
# def calGST(el):
# return 0.18 * el + el
#
# gstValue = returnList(bill,calGST)
# print(gstValue)
#
# sumDis = returnList(bill,calDicount)
# print(sumDis)
# print((sum(sumDis)/sum(bill)) * 100)
#
# def calculateAge(el):
# return 2021-el
#
# def addingTen(el):
# return el + 10
# sum()
# min()
# max()
# sorted()
# reversed()
# len()
# del
# b = returnList(listA,addingTen)
# print(b)
#
# v = returnList(listA,calculateAge)
# print(v)
#
# listB = []
# for item in listA:
# listB.append(2021-item)
# print(listB)
#
# listC = []
#
# for item in listA:
# listC.append(item+10)
# print(listC)
a = "AAAADDDCCBQ"
b = set(a) # b {'A','B','C','D'}
#A4D3C2B1Q1
nma= ""
nm = []
for item in sorted(b):
print(nm.append(item))
print(nm.append(str(a.count(item))))
print(nm)
v = "".join(nm)
print(v)
#
# w = "aeiouabc"
#
# # AEIOU
# count = 0
# for char in w:
# char = char.lower()
# if char == 'a' or char =='e' or char == 'i' or char == 'o' or char == 'u':
# count = count + 1
#
# print(count)
#
#
# b = 'aieouAEIOU'
# count = 0
# for char in w:
# if char in b:
# count = count +1
#
# print(count)
#
|
c15d3dfe2f878d9b8e4d7d738f469f529e71f761 | alirezamzh/number-game-app | /numberGameapp.py | 1,332 | 3.890625 | 4 | # limit the number of guesses
# catch when someone submit a non-integer value
# print "too high" or "too low" messages for bad guesses
# let peaple play again
# generate a random number between 1 to 10
import random
secret_number = random.randint(1, 10)
# get a number guess from the player
def run_gmae():
guesses = []
guess=0
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 to 10: "))
except ValueError :
print("{} isn't a number.".format(guess))
else:
# compare guess the secret number
# print hit/miss
if guess==secret_number:
print("you got it :D, my number was {}".format(secret_number))
break
elif guess < secret_number:
print("My number is higher than {}".format(guess))
elif guess > secret_number:
print("My number is lower than {}".format(guess))
else:
print("that's not it :(")
guesses.append(guess)
else:
print("you didn't win! my number was {}".format(secret_number))
play_again = input("do you want to play again? [y/n]")
if play_again.lower()=='y':
run_gmae()
else:
print("Bye!")
run_gmae()
# print('Hi, I am Alireza :D.')
|
f1c54f234b47b962339c32273c451e44445008aa | ANKITPODDER2000/LinkedList | /21_merge_list.py | 736 | 4.25 | 4 | from LinkedList import LinkedList
from LinkedListHelper import CreateLinkedList
def merge(head1 , head2):
l1 = LinkedList()
while head1 or head2:
if not head1:
l1.insert_end(head2.val)
head2 = head2.next
elif not head2:
l1.insert_end(head1.val)
head1 = head1.next
elif head1.val > head2.val:
l1.insert_end(head2.val)
head2 = head2.next
else:
l1.insert_end(head1.val)
head1 = head1.next
return l1
def main():
l1 = LinkedList()
CreateLinkedList(l1)
l2 = LinkedList()
CreateLinkedList(l2)
l3 = merge(l1.head , l2.head)
l3.display()
if __name__ == "__main__":
main()
|
44d7bfe2918ba5cbd2657b9ef00812c7c098baa2 | confi-surya/pythonicPracto | /GeeksforGeeks/divideAndConquor/calculatePower.py | 388 | 3.65625 | 4 | def powern_in_orderof_n(x,y):
if y==0:
return 1
elif (y%2==0):
return powern_in_orderof_n(x,y/2)*powern_in_orderof_n(x,y/2)
else:
return x*powern_in_orderof_n(x,y/2)*powern_in_orderof_n(x,y/2)
def power_in_orderof_logn(x,y):
if y==0:
return 1
temp=power_in_orderof_logn(x,y/2)
if (y%2==0):
return temp*temp
else:
return x*temp*temp
print power_in_orderof_logn(2,200)
|
29aee72d39417900fbaf697f5cba134673027e01 | afsanehshu/tamrin | /practice 5/key/1.py | 122 | 3.65625 | 4 | import datetime
time = datetime.datetime.today().minute
if (time%7)%2 == 0:
print("Even")
else:
print("odd")
|
76f128a9aeb0da9a2889e732dbdf34881fc50581 | xiaosean/leetcode_python | /Q88_Merge-Sorted-Array.py | 634 | 3.75 | 4 | class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
if n == 0:
return
offset1, offset2 = m-1, n-1
while offset1 >= 0 and offset2 >= 0:
num1, num2 = nums1[offset1], nums2[offset2]
if num1 > num2:
nums1[offset1+offset2+1] = num1
offset1 -= 1
else:
nums1[offset1+offset2+1] = num2
offset2 -= 1
for i in range(offset2+1):
nums1[i] = nums2[i]
|
3902fb27bba0c2270a9cfc51e53a670254109057 | TanyaKHughes/BasicPythonPractice | /exception.py | 323 | 4.03125 | 4 | # exception.py - just some basic exception practice
n = int(input("Enter a number and I'll divide 100 by your number: "))
try:
dividend = 100/n
except ZeroDivisionError:
print("I can't divide by zero!")
else:
print(f"I did it! The answer is {dividend:.2f}, or {dividend:.1%}")
print(f"Your number was: {n}")
|
74b11461ee87d679bf5abc41d2577473132a1e6e | yiyueya/random-time | /My_random.py | 1,258 | 3.796875 | 4 | import time
import matplotlib.pyplot as plt
import random as R
# ---------------------------------------------------------------------
# 获取当前时间(秒)小数点后第n个数字作为随机数,默认范围为0~9,可通过w改变
def get_random_time(n = 3):
while True:
now = time.time() * (10**(n-1))
diff = int((now - int(now)) * 10)
return diff
# 获取当前时间(秒)小数点后第n个数字作为随机数,随机生成0和1
def random_one(n = 3):
now = time.time() * (10**(n-1))
diff = int((now - int(now)) * 10)
if diff < 5:
return 0
else:
return 1
# ---------------------------------------------------------------------
# 使用random 生成0~9的整数
for i in iter(range(10)):
plt.subplot(2, 1, 1)
plt.scatter(i, R.randint(0,9))
plt.subplot(2, 1, 2)
plt.scatter(i, get_random_time())
plt.subplot(2, 1, 1)
plt.title('random')
plt.subplot(2, 1, 2)
plt.title('time')
plt.show()
# ---------------------------------------------------------------------
# now = time.time()
# print('当前时间:',time.time())
# for i in range(10):
# print('当前时间以秒为单位的小数部分:',time.time()-int(time.time()))
|
1fe9a1a32bde8d5baf249c6a949eecda0422841b | Sigrud/lesson1 | /vat.py | 589 | 3.859375 | 4 | price=100
vat_rate=18
vat=price/100*vat_rate
print(vat)
price_not_vat=price-vat
print(price_not_vat)
def get_vat(price,vat_rate):
vat=price/100*vat_rate
price_not_vat=price-vat
print(price_not_vat)
price1=100
vat_rate1=18
get_vat(price1,vat_rate1)
price2=500
vat_rate2=10
get_vat(price2,vat_rate2)
get_vat(50,int('5'))
get_vat(-100,18)
def get_summ(one,two,delimeter=' '):
return (str(one)+ str(delimeter)+ str(two))
get_summ('hello','world',delimeter='&')
get_summ('hello','world','+')
get_summ('hello','world')
sum_string=get_summ('learn','python')
print(sum_string.upper())
|
4962112c971ca2037c131b26c37302edd5f2915a | matteocodogno/python_course | /tkinter/script1.py | 871 | 3.890625 | 4 | from tkinter import *
from tkinter.font import names
def convert():
kilos = float(kg_value.get())
grams = kilos * 1000
pounds = kilos * 2.20462
ounces = kilos * 35.274
grams_txt.insert(END, grams)
pounds_txt.insert(END, pounds)
ounces_txt.insert(END, ounces)
window = Tk(baseName='Grams Pounds Ounces')
l1 = Label(window, text='Kg')
l1.grid(row=0, column=0)
kg_value = StringVar()
kg = Entry(window, textvariable=kg_value)
kg.grid(row=0, column=1)
convert_btn = Button(window, text='Execute', command=convert)
convert_btn.grid(row=0, column=2)
grams_txt = Text(window, height=1, width=20)
grams_txt.grid(row=1, column=0)
pounds_txt = Text(window, height=1, width=20)
pounds_txt.grid(row=1, column=1)
ounces_txt = Text(window, height=1, width=20)
ounces_txt.grid(row=1, column=2)
# needed to maintain program open
window.mainloop()
|
bc88183d5632e1e6260e4246490272e2b63cdbff | chris6037/guvitask | /looptillQ.PY | 150 | 3.96875 | 4 | a=str(input("enter the file:"))
while (1):
if(a!="q"):
print("invalid file")
else:
print("valid file")
|
16437c1956d2527406bd376ba53e59dedf4a71df | samuelrothen/advent_of_code_2020 | /src/aoc_day06.py | 833 | 3.578125 | 4 | # Advent of Code Day 6
def count_anyones_yes(answers_all):
n_yes = 0
for answers_group in answers_all:
answers_group = answers_group.replace('\n', '')
n_yes += len(set(answers_group))
return n_yes
def count_everyones_yes(answers_all):
n_yes = 0
for answers_group in answers_all:
answ_sets = [set(answ_person) for answ_person in answers_group.split('\n')]
answ_unique = None
for answ in answ_sets:
if answ_unique == None:
answ_unique = answ
answ_unique = answ_unique.intersection(answ)
n_yes += len(answ_unique)
return n_yes
with open ('../input/day06.txt', 'r') as f:
answers_all = f.read().split('\n\n')
print(f'Part 1: {count_anyones_yes(answers_all)}')
print(f'Part 2: {count_everyones_yes(answers_all)}') |
ff13c555276bfd2b04ea0f31e3fe026ea051c6a8 | PlabonKumarsaha/Python_Open_CV_Practice | /RGB2GraySCALE.py | 382 | 3.546875 | 4 | # package for opencv
import cv2
# read image from path
# stored the image in 'img'
img = cv2.imread("Resrouces/ironman.jpg")
# Convert to grayScale image
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# first parameter is window name..second is the image name
cv2.imshow("Gray Image", imgGray)
# must adda delay , otherwise the image gets popped down
cv2.waitKey(0)
|
789643484a71602d2389e8f557bbbc54e704de34 | antomin/GB_Algorithms | /lesson_1/task_1_5.py | 794 | 4.375 | 4 | """
Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв.
"""
x, y = input('Введите две буквы.\nОт: '), input('До: ')
if 65 <= ord(x.upper()) <= 90 and 65 <= ord(y.upper()) <= 90:
print(f'{x.upper()} - {ord(x.upper()) - 64}-я буква алфавита.')
print(f'{y.upper()} - {ord(y.upper()) - 64}-я буква алфавита.')
if ord(x.upper()) < ord(y.upper()):
print(f'Между ними {ord(y.upper()) - ord(x.upper()) - 1} букв.')
else:
print(f'Между ними {ord(x.upper()) - ord(y.upper()) - 1} букв.')
else:
print('Неверные данные!')
|
97cfc2468e699bf8bf9e5358fd652912601cc80e | jbial/daily-coding | /dailycoding038.py | 1,727 | 3.875 | 4 | """
This problem was asked by Microsoft.
You have an N by N board. Write a function that, given N,
returns the number of possible arrangements of the board
where N queens can be placed on the board without threatening each
other, i.e. no two queens share the same row, column, or diagonal.
solution: https://dailycodingproblem.com/blog/an-introduction-to-backtracking/
Use backtracking by attempting to place a queen in one position in one row
and brute forcing all other possible valid positions in the remaining rows,
but backtracking and returning 0 when there is no possible configuration
given the intial placement in the first row.
Run in O(N^2) time since we try N spots for N rows, and O(N) space since
the board is NxN so we only have to store an array with N elements each
representing the column index
"""
def is_valid(board):
"""Checks if the current board has no threathening queens
"""
curr_row, curr_col = len(board) - 1, board[-1]
for row, col in enumerate(board[:-1]):
diff = abs(curr_col - col)
if diff == 0 or diff == abs(curr_row - row):
return False
return True
def n_queens(n, board=[]):
"""Use backtracking to try every N^2 positions on the board
"""
if len(board) == n:
return 1
count = 0
for col in range(n):
board.append(col)
if is_valid(board):
count += n_queens(n, board)
board.pop()
return count
def main():
tests = {
1: 1,
2: 0,
3: 0,
4: 2,
5: 10,
6: 4,
7: 40,
8: 92,
9: 352,
10: 724
}
if all(tests[k] == n_queens(k) for k in tests):
print("Passed")
else:
print("Failed")
if __name__ == '__main__':
main()
|
f9f1c89271c969c9f1be83d7712a79eadb7aad9d | HumgTop/DataStructure-Algorithm | /LeetcodeForPython/leetcode/editor/cn/[剑指 Offer 59 - I]滑动窗口的最大值.py | 2,467 | 3.6875 | 4 | from typing import *
from queue import Queue
import collections
import itertools
# 给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
#
# 示例:
#
# 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
# 输出: [3,3,5,5,6,7]
# 解释:
#
# 滑动窗口的位置 最大值
# --------------- -----
# [1 3 -1] -3 5 3 6 7 3
# 1 [3 -1 -3] 5 3 6 7 3
# 1 3 [-1 -3 5] 3 6 7 5
# 1 3 -1 [-3 5 3] 6 7 5
# 1 3 -1 -3 [5 3 6] 7 6
# 1 3 -1 -3 5 [3 6 7] 7
#
#
#
# 提示:
#
# 你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。
#
# 注意:本题与主站 239 题相同:https://leetcode-cn.com/problems/sliding-window-maximum/
# Related Topics 队列 Sliding Window
# 👍 115 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
deque = collections.deque()
res = []
n = len(nums)
# 滑动窗口的移动和队列的操作同时进行,滑动窗口操作n-k+1次,队列操作n次
for i, j in zip(range(1 - k, n - k + 1), range(n)):
# 如果左端出列元素刚好是当前窗口的最大值,则队首出列
if i > 0 and deque[0] == nums[i - 1]: deque.popleft()
# 添加当前j指针到队尾前,先将队列中小于j指针的元素移除
while deque and deque[-1] < nums[j]:
# 当前j指针入列前,从队尾移除队列中所有比它小的元素(保持队列单调非递减)
deque.pop()
deque.append(nums[j])
# 当i==0时,第一个滑动窗口最大值已经在deque队首,将其添加到res中
if i >= 0: res.append(deque[0])
return res
# class Solution:
# def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
# n = len(nums)
# if n == 0: return []
#
# res = []
# # 共有n-k个滑动窗口
# for i in range(0, n - k + 1):
# res.append(max(nums[i:i + k]))
# return res
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
nums = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(Solution().maxSlidingWindow(nums, k))
pass
|
2f050dc9beece895a63a8baa6199f6901cd24b70 | bernease/A2DD13-hrwc | /hrws_survey.py | 3,515 | 3.625 | 4 | #! /usr/bin/env python
# Import python modules that will do useful stuff for us
import collections, csv
# code written for use by/for the Huron Valley Watershed Council (A2 DataDive 2013)
# Looks at the species table in the database, and outputs a file describing whether or not a given species is at a given site
# (value 0 = no, 1 = yes)
# Also prints out a list of the 10 surveys that showed the most species
# TODOS:
# - Adapt GIS software to show these results on a map [GIS, d3]
#
# Code written and discussed by Nick Krabbenhoeft, @bernease/Bernease Herman; refactoring by Andy Boughton
# To use: output the database table for site surveys to comma-separated values (CSV) format; we based this analysis
# on the provided excel file "6- species list.csv"
## NOTES:
# final map likely ought to be spot-checked by ecologists/other workers or volunteers familiar with the data
#################
all_species = set()
all_surveys = {}
# First pass through the file: create a list of all known species in the database
with open('species.csv', 'rU') as f:
reader = csv.reader(f)
# skip header row
reader.next()
for row in reader:
# Store species information in a dictionary whose key is the ID field in the database
# (this may not be the same as the UniqueID field; as I understand it, this reports the most species-rich surveys, rather than
# the most species-rich bioreserves. --abought
# Convert species names to lowercase
names_lowercase = [ item.lower() for item in row[5:] ]
for item in names_lowercase:
# Globally keep track of every unique species name listed. This list only combines obvious similarities (ELM and elm).
# To detect more subtle similarities (Am. Elm vs American elm), the final output will need to be spot-checked by HRWC
all_species.add( item )
# Store species information in a dictionary based on the ID field (column 0) in the database
# (this may not be the same as the UniqueID field, which we think is the name of the BioReserve).
# So the output of this file reports the most species-rich surveys, rather than
# the most species-rich bioreserves. --abought
all_surveys[ row[0] ] = collections.Counter( names_lowercase )
#####
# This next line is what connects a survey with an ID; change to row[1] to use the BioReserve ID instead of site ID
all_surveys[ row[0] ]['survey_id'] = row[0]
# We're not interested in blank columns, so get rid of those
if '' in all_surveys[ row[0] ] : del all_surveys[ row[0] ]['']
all_species = sorted( all_species )
if '' in all_species: all_species.remove( '' )
# Wrte data to output file; first column should be the survey_id ("ID" = column 0 in database)
with open('survey_species2.tsv','w') as f:
writer = csv.DictWriter( f, delimiter='\t', fieldnames=['survey_id'] + all_species , restval = 0 )
writer.writeheader()
for s in all_surveys:
writer.writerow( all_surveys[s] )
# Lastly: can we find the 10 surveys/bioreserve sites that seem to have the most unique species?
rank_by_most_species = sorted( all_surveys , reverse = True,
key = lambda x: len( all_surveys[x].values() ) -1 )
print "Most species-rich surveys:"
print "Survey_id", "#species"
for i in range(10):
survey_id = rank_by_most_species[i]
print survey_id , len( all_surveys[ survey_id ].values() ) - 1
# Don't close the output window until the user is done looking at it
raw_input( "Analysis done! Press the return key to exit." )
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.