blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5fcb38a7564095a79911de248d482e5ba28f6b8a | pybule/pythonProject | /面试题/32、生成数值和索引都是偶数的列表.py | 206 | 3.828125 | 4 | # _*_ encoding=utf-8 _*_
# author zdh
# date 2021/4/21--22:46
def num_list(num):
return [i for i in num if i%2==0 and num.index(i)%2==0]
num = [0,1,2,3,4,5,6,7,8,9,10]
list = num_list(num)
print(list)
|
e053834384e7634ab1c137c9c18f369bd13cdb58 | Catarina607/Python-Lessons | /6_27.py | 285 | 4 | 4 | num = int(input('Number: '))
c = 0
s = 0
cont = 0
if num <=0:
print('O numero tem que ser maior que zero')
for c in range(1, num+1):
if c==1:
cont = 1
elif c > 1:
cont = cont + 1
s = cont/cont/cont/(s + 1/c)
print('O resultado é ',s) |
063d37b05cabe2485abfcb27f13302f21a6833ea | edursantos/pythontest | /ex006.py | 197 | 3.796875 | 4 | print('===Quantos dólares você pode comprar?===')
n1=float(input('Quanto você tem na carteira?'))
n2 = n1/5.70
print('Você tem R$ {:.2f} e pode comprar U${:.2f}'.format(n1,n2))
print('Teste')
|
951f6d4a1d26cf9bfa91211fa02fa86d83e26ec2 | VaibhaviMandavia/pythoncodes | /missingnum.py | 416 | 3.734375 | 4 | #find the missing number from an array of first n numbers
x = int(input("enter number of elements : "))
print("enter "+str(x)+" elements : ")
lst = []
ans = 0
n = x + 1
for i in range(0,x):
y = int(input())
lst.append(y)
if all(item >= 0 for item in lst) == True:
res = n*(n+1)/2
else :
res = -(n*(n+1)/2)
ans = sum(lst)
misnum = res - ans
print("missing number is : ",int(misnum))
|
0d6c8fc72af375556a7c2a9febde294edbae03e6 | unexpectedCoder/GunProject | /my_parser.py | 3,153 | 4.0625 | 4 | from xml.etree import ElementTree
import csv
def read_txt_with_fieldnames(file, delim):
"""
This function reads data from TXT file with forming field of names
for further converting to CSV file.
:param path: TXT file path
:param delim: delimiter between data elements
:return: data and field of names
"""
data = []
fieldnames = file.readline().split(delim)
fieldnames[-1] = fieldnames[-1][:-1]
for line in file:
new_line = line.split(delim)
new_line[-1] = new_line[-1][:-1]
buf = []
for x in new_line:
buf.append(float(x))
data.append(dict(zip(fieldnames, buf)))
return data, fieldnames
def read_csv_dict(path, delim):
"""
This function reads data from CSV file to RAM in dictionary view.
:param path: CSV file path
:param delim: delimiter between data elements in CSV file
:return: list of dictionaries
"""
dicts_list = []
with open(path, 'r') as file:
reader = csv.DictReader(file, delimiter=delim)
for dict in reader:
dicts_list.append(dict)
return dicts_list
def read_csv_light(path, delim):
"""
This function is the light version of read_csv_dict() function.
It reads CSV data to RAM in dictionary view
and uses update() function to combine dictionaries
from this function and from CSV DictReader.
:param path: CSV file path
:param delim: delimiter between data elements in CSV file
:return: dictionary
"""
dic = {}
with open(path, 'r') as file:
reader = csv.DictReader(file, delimiter=delim)
for d in reader:
dic.update(d)
return dic
def write_csv(path, data, delim='\t'):
with open(path, 'w') as file:
writer = csv.writer(file, delimiter=delim)
for row in data:
writer.writerow(row)
def write_csv_dict(path, fieldnames, data, delim='\t'):
with open(path, 'w') as file:
writer = csv.DictWriter(file, delimiter=delim, fieldnames=fieldnames)
writer.writeheader()
for row in data:
writer.writerow(row)
def read_xml_tree(path):
"""
This function reads XML file to RAM in ElementTree view.
:param path: XML file path
:return: list of dictionaries of XML node objects (attributes)
"""
tree = ElementTree.parse(path)
root = tree.getroot()
return traverse_nodes(root)
def traverse_nodes(node, i=0, dicts=[], **kwargs):
"""
Recursive function to read all XML nodes to RAM.
:param node: current node
:param i: starting multiplier of tabulation
:param dicts: current list of dictionaries
:return: list of dictionaries of XML node objects (attributes)
"""
space = 4 * ' '
if 'space' in kwargs:
space = kwargs['space'] * ' '
if 'print' in kwargs:
for child in node:
print(i*space, child.tag, child.attrib)
dicts.append(child.attrib)
traverse_nodes(child, i + 1, dicts)
else:
for child in node:
dicts.append(child.attrib)
traverse_nodes(child, i + 1, dicts)
return dicts
|
56905404056ac7a20240ee58e4c27a2d86616c2b | Tom520class/AnacondaProject | /pandas/4-6 Preprocess the data using apply.py | 1,202 | 3.515625 | 4 | __author__ = 'zhongyue'
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
# 通过apply进行数据预处理
df = pd.read_csv('../data/apply_demo.csv')
print(df.head())
print(df.size)
# 使用apply进行预处理
# apply可以批量的改变dataframe中的数据。
s1 = Series(['a']*5)
df['A'] = s1
print(df)
print(df.size)
# 将A列改的值为大写
df['A'] = df['A'].apply(str.upper)
print(df)
# data列拆分
# data列的值其实是三个部分组成:
# Symbol、Seqno、Price
# .strip()是去除空格,split(" ")是以空格为分隔符进行分割
print(df['data'][0].strip().split(' '))
def foo(line):
item = line.strip().split(' ')
return Series([item[1],item[3],item[5]])
# 然后对原dataframe的data列数据进行apply处理:
# df = pd.read_csv('../data/apply_demo.csv')
print(df)
df_tmp = df['data'].apply(foo)
df_tmp = df_tmp.rename(columns={0:'Symbol',1:'Seqno',2:'Price'})
print(df_tmp.head())
# 将新的dataframe连接到原来的dataframe中并删除data列数据,得到最终的结果:
df_new = df.combine_first(df_tmp)
print(df_new.head())
del df_new['data']
print(df_new.head())
df_new.to_csv('../data/demo_duplicate.csv') |
e00505011a01ab08cb7aaf2a30ebcee9106f1452 | Eeun-ju/Algorithm-Study | /GOORM/약수개수세기.py | 237 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
n = int(input())
count = 0
for i in range(1,n+1):
if n%i == 0:
count +=1
if count%2 == 0:
print('no')
else:
print('yes')
#print ("Hello Goorm! Your input is " + user_input) |
0555c577a8fb746cf2debb929d02b46cd3be4d7b | timliakhor/geekbrains_python | /lesson3/6.py | 352 | 3.9375 | 4 | from typing import List
def uppercase_first_letter(string: str) -> str:
return string[0:1].upper() + string[1:]
string_list: List[str] = input('Please, input string: ').split(' ')
result: str = ''
for i, value in enumerate(string_list):
result += (lambda index: '' if index == 0 else ' ')(i) + uppercase_first_letter(value)
print(result)
|
c56b9646629e15dfa9d4eec8927f0fae3ca5364f | clint-ton/astar | /astar.py | 4,960 | 3.90625 | 4 | """Module to implement the A* algorithm using the abstract classes and generic graph search of search.py
Author: Clinton Walker"""
from search import *
import math
import heapq
class RoutingGraph(Graph):
def __init__(self, map_str):
# convert a map string to a 2d matrix of symbols
self.map = [list(line) for line in map_str.strip().splitlines()]
# initializes and populates lists for starting nodes and goal nodes
self.start = []
self.goal = []
self.read_map()
def read_map(self):
"""iterates over a map adding start, goal and fuel nodes"""
for row in range(len(self.map)):
for column in range(len(self.map[row])):
position = self.map[row][column]
if position == 'S':
self.start.append((row, column, math.inf))
elif position.isdigit():
self.start.append((row, column, int(position)))
elif position == 'G':
self.goal.append((row, column))
def is_goal(self, node):
"""returns true if the given node is a goal node"""
return any([goal == node[:2] for goal in self.goal])
def starting_nodes(self):
"""Returns the starting node"""
return self.start
def outgoing_arcs(self, tail_node):
"""returns avalible actions for the given state (node)"""
directions = [('N' , -1, 0),
('E' , 0, 1),
('S' , 1, 0),
('W' , 0, -1),]
arcs = []
row, column, fuel = tail_node
# if out of fuel, either fuel up or halt.
if fuel == 0:
if self.map[row][column] != 'F':
return arcs
else:
return [Arc(tail_node, (row, column, 9), "Fuel up", 15)]
# Calculate row/coulumn/fuel for each direction and add it as an arc.
for direction in directions:
new_row, new_column, new_fuel = tail_node
new_row += direction[1]
new_column += direction[2]
new_fuel -= 1
if self.map[new_row][new_column] not in ['X', '|', '-']:
arcs.append(Arc(tail_node, (new_row, new_column, new_fuel), direction[0], 5))
# Add a fuel up arc if current node is a fuel up node.
if self.map[row][column] == 'F' and fuel < 9:
arcs.append(Arc(tail_node, (row, column, 9), "Fuel up", 15))
return arcs
def estimated_cost_to_goal(self, node):
"""Heuristic used for algorithm, uses manhattan distance * cost"""
return 5 * min([manhattan_d(node, goal) for goal in self.goal])
class AStarFrontier(Frontier):
def __init__ (self, graph):
self.graph = graph
self.container = []
self.expanded = set()
self.entry_count = 0
def add(self, path):
# Pruning (dont expand paths that have been expanded)
if path[-1] in self.expanded:
return
cost = 0
for arc in path:
cost += arc.cost
cost += self.graph.estimated_cost_to_goal(path[-1][1])
# entry_count keeps the heap stable. Since it can only increment, paths with the same cost will work in a LIFO fashion.
heapq.heappush(self.container, (cost, self.entry_count, path))
self.entry_count += 1
def __next__(self):
if len(self.container) > 0:
# Select a path that has not had its tail node expanded
path = heapq.heappop(self.container)[2]
while path[-1] in self.expanded:
if len(self.container) > 0:
path = heapq.heappop(self.container)[2]
else:
raise StopIteration
# Mark the node about to be processed as expanded
self.expanded.add(path[-1])
return path
else:
raise StopIteration
def print_map(graph, frontier, solution):
printed_map =graph.map
# Mark solution on map
if solution is not None:
for arc in solution:
row, column = arc.head[0], arc.head[1]
if printed_map[row][column] == ' ':
printed_map[row][column] = '*'
# Mark expanded nodes on map
for arc in frontier.expanded:
row, column = arc.head[0], arc.head[1]
if printed_map[row][column] == ' ':
printed_map[row][column] = '.'
# print each row of the map array as a string
for row in printed_map:
print("".join(row))
def manhattan_d(node1, node2):
"""calculates the manhattan disctance between two nodes"""
return abs(node1[0] - node2[0]) + abs(node1[1] - node2[1])
|
037a107116515cf14e84f54378a26c719528a1dd | sjlee900211/algorithm | /Code10-06.py | 180 | 3.53125 | 4 | ## 별모양 출력하기 -> 입력한 숫자만큼 차례대로 별모양을 출력
def printStar(n):
if n > 0 :
printStar(n-1)
print('★ ' * n)
printStar(5) |
bda931731047e5d5a598a7a88bcd1d16ddef3ee4 | lehuyl/PythonDataAnalysis | /e1/pd_summary.py | 779 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 16:08:28 2019
@author: Steven
"""
import pandas as pd
totals = pd.read_csv('./e1/totals.csv').set_index(keys=['name'])
counts = pd.read_csv('./e1/counts.csv').set_index(keys=['name'])
cityPrecipitation = pd.Index(totals.sum(axis=1))
print('Row with lowest total precipitation:')
print(cityPrecipitation.argmin())
monthlyPrecipitation = pd.Index(totals.sum(axis=0))
monthlyCount = pd.Index(counts.sum(axis=0))
averagePerMonth = monthlyPrecipitation/monthlyCount
print('Average precipitation in each month')
print(averagePerMonth.values)
totalCount = pd.Index(counts.sum(axis=1))
averagePerCity = cityPrecipitation/totalCount
print('Average precipitation in each city')
print(averagePerCity.values)
print(cityPrecipitation) |
d155e34d3bcb2b6d54064c6699fd5311b872adbf | zfq308/py | /tree.py | 639 | 3.640625 | 4 | import sys
import os
def printsubfolder(path, name, level):
o = ''
if(os.path.isfile(path + name)):
for index in range(level - 1):
o = o + ' '
o = o + '|---'
print(o + name + '\n')
else:
for index in range(level - 1):
o = o + ' '
o = o + '|---'
if(level == 0):
print(path + '\n')
else:
print(o + name + '\n')
for file in os.listdir(path + name):
printsubfolder(path + name + '\\', file, level + 1)
def tree(path):
printsubfolder(path, '', 0)
tree('E:/release_new') |
11014d7e99b9a1ee5d9b2f292db272827f32e601 | Shubham-Coader/python | /beginner_python/02-strings.py | 5,533 | 4.59375 | 5 | me = "Caleb"
#escape character example
print("\n")
me = "C\ta\tl\te\tb\n"
print(me)
#can also use single quotes
you = 'Subscriber'
me = "Caleb" #reset to normal
#passing multiple arguments to print
print(me, you)
#double quotes and single quotes work the same way with the exception of working with quotes inside.
#here are some examples:
single_quotes = 'She said "Hi"'
print(single_quotes)
double_quotes = "She said \"Hi\""
print(double_quotes)
single_quotes = 'I\'m learning!'
print(single_quotes)
double_quotes = "I'm learning!"
print(double_quotes)
#notice we have to escape the same quote as the surrounding quote
#Here are the other escape sequences:
#https://docs.python.org/2.0/ref/strings.html
#Notice that if you want to print \ you must put two
print("\\")
#you can also prefix with r which will make a raw string (ignoring escapes except same quote)
print(r'as raw as I\'ve ever seen. \/\/ () \/\/. \t' ) #only \' is escaped
########## CONCATENTATION ##########
#Use a + to concatenate
msg = me + " + " + you
print(msg)
#Can use comma separated values in print. Automatically uses spaces between
print(me, "+", you)
#You can automatically concatenate literals (actual values with quotes as opposed to variables)
#by putting them one after the other. This is ideal if you need to split a large string up
#onto multiple lines.
print("my " "name "
"is " "Caleb")
#You can also use multiline string
print("""Name: Caleb
Age: 58""")
#skip newline using \ (without it, it would go down a line each line)
print("""\
Name: Caleb. \
Age: 58""")
"""You may see
them as multi-
line comments even
if they technically
are not.
https://stackoverflow.com/questions/7696924/is-there-a-way-to-create-multiline-comments-in-python
"""
########## INDEXES ##########
#It's very common to grab particular characters within a string
#this is also common for collections when we get to em.
msg = "This is a very important message."
print(msg[5])
#indexing is zero based. This means 0 will get the very first character:
print(msg[0])
#This value is returned and can be assigned to a variable or used in an expression
first_letter = msg[0]
print(first_letter + "acos")
#You can also index from the right.
period = msg[32] #from left
print(period)
period = msg[-1] #from right
print(period)
#This may be obvious, but we do not use -0 to get the first element from the right as we would
#use 0 to get the first element from the left. (Side note) -0 actually is 0:
print(-0) #(side note)
print(0 == -0) #0 == 0 (side note)
########## SLICING #########
#repeating this for ease of reading:
msg = "This is a very important message."
#We can pass two numbers in for the index to get a series of characters.
#left is included. Right is excluded.
#this will get 2 characters (from index 1 - 3 with 3 not included...we are left with index 1 and 2.
print(msg[1:3]) #hi
#You can also leave off first to start at beginning
#or leave off second to go to end
print(msg[:5]) #print index 0-4 (because 5 is excluded, remember)
print (msg[1:]) #from index 1 to end
#We can also use negatives. Here is how you get the last 8 characters:
print(msg[-8:]) #start 8 from right and go to end
#out of range index
#Grabbing an out of range index directly will cause an error.
#But incorrect ranges fail gracefully.
#print(msg[42]) #doesn't work
print(msg[42:43]) #works
########## IMMUTABILITY ##########
#Strings are immutable, meaning they can't change.
cant_change = "Java is my favorite!"
#cant_change[0] = K .....nope. Sorry Kava (my dog)
#generate new string from old:
#Kava is my favorite!
new = 'K' + cant_change[1:]
print(new)
#Python is my favorite!
fav_language = "Python " + cant_change[5:]
print(fav_language)
#Java is actually coffee
coffee = cant_change[:8] + "actually coffee" #grab first 7 characters (index 8 not included)
print(coffee)
#operations that appear to change string actually replace:
#Java is actually coffee (contrary to popular belief).
coffee += " (contrary to popular belief)."
print(coffee)
########## GETTING STRING LENGTH ##########
#There is a function we can use....
#similar to how we invoke print to do something for us (output to console)
#we can invoke len to count for us:
print(len(coffee))
#for those from other languages...
#notice we do not say coffee.len()
#coffee.len() XXXXXX
#nope.
#last index is always len() - 1.
name = "Caleb"
print("index 4:", name[4]) #b
print("len(name)", len(name)) #length is 5
########## MORE STRING WORK ##########
#How to convert a number to a string
length = len(name)
print("Length is " + str(length))
#this works however sometimes you just need one combined string instead of components.
#when we use a comma, we are passing in data as separate arguments.
#fortunately, print knows how to handle it. Other times, we must pass in one string.
#WARNING --> Commas automatically print a space.
print("length is ", length)
#an example of this is if we need a variable. We cannot use a comma:
#BAD
msg = "length is", len(name)
print(msg) #NOT WHAT WE WANTED!
#GOOD
length = len(name)
msg = "length is " + str(length)
print(msg)
#EVEN BETTER
#We can also nest function calls:
print("length is " + str(len(name)))
#The order in which these are invoked are in to out...
#len(name) is first which returns a number.
#this number is passed to str which converts it to a string
#this string is then concatenated with the string on the left
#this final string is then passed to print
#That's the end of your introduction to strings! |
5485bfe3d04b95096a68e3a297289d5ae4bd23dd | vieiraguivieira/PhytonStart | /strings.py | 654 | 3.75 | 4 | print("Today is a good day to learn Pyhton")
print('Phyton is fun')
print("Phyton's string are easy to use")
print('We can even include "quotes" in strings')
print("hello" + " world")
greeting = "Hello"
name = "Guilherme"
print(greeting + name)
# if we want a space, we can add that too
print(greeting + ' ' + name)
age = 30
print(age)
print(type(greeting))
print(type(age))
age_in_words = "2 years"
print(name, " is ", age, " years old")
print(type(age_in_words))
age_in_words = "2 years"
print(name + f" is {age} years old")
print(type(age_in_words))
print(f"Pi is approximately {22/7:5.3f}")
pi = 22/7
print(f"Pi is approximately {pi:<12.3f}")
|
2630106d3269f8d72a50eeb97f6303e174cb99df | rafaelperazzo/programacao-web | /moodledata/vpl_data/39/usersdata/115/15211/submittedfiles/dec2bin.py | 163 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
n=int(input('digite um número:'))
b=n
c=0
while b>0:
b=b//2
c=c+1
s=0
for i in range(0,c,1):
|
2aff2c0b9f1548bbb4176a6bcecdefbd0bdebe82 | shekharkrishna/ds-algo-udi-20 | /Data Structures/Trees/2. DFS/1traverse_tree.py | 1,744 | 4.25 | 4 | class Node(object):
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
def get_value(self):
return self.value
def set_value(self, value):
self.value = value
def get_left_child(self):
return self.left # PJ: We are calling this method as Node object in the Tree class object and the pointer thing is abstracted and
#playing with value directly so we remove value and dont need to conver pointer location to value (Dont have to DO: return self.left.value)
def set_left_child(self, node):
self.left = node
def get_right_child(self):
return self.right
def set_right_child(self, node):
self.right = node
def has_left_child(self):
return self.left != None
def has_right_child(self):
return self.right != None
def __repr__(self):
return f"Node({self.get_value()})"
def __str__(self):
return f"Node({self.get_value()})"
class Tree(object): # class inherits from object
def __init__(self, value=None): # constructor
self.root = Node(value)
def get_root(self):
return self.root
# Driver
# Tree with nodes'
tree = Tree("Google")
print(' ',tree.get_root())
tree.get_root().set_left_child(Node("Amazon"))
print(' Left Child: ', tree.get_root().get_left_child())
tree.get_root().set_right_child(Node("Microsoft"))
print(' Right Child: ',tree.get_root().get_right_child())
tree.get_root().get_left_child().set_left_child(Node("SpaceX"))
print('Left Left Child: ', tree.get_root().get_left_child().get_left_child()) |
bc061b44f7aec125a26e816bbde444107cf9aa34 | zhucebuliaolongchuan/my-leetcode | /DFS/LC310_MinimumHeightTrees.py | 1,801 | 4.28125 | 4 | """
310. Minimum Height Trees
For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.
Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
Example 1:
Given n = 4, edges = [[1, 0], [1, 2], [1, 3]]
0
|
1
/ \
2 3
return [1]
"""
class Solution(object):
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
res = {}
graph = collections.defaultdict(list)
for v1, v2 in edges:
graph[v1] += [v2]
graph[v2] += [v1]
visited = [False for i in range(n)]
for i in range(n):
res[i] = self.findDepth(i, graph, visited)
min_height = min(res.values())
nodes = []
for node in res.keys():
if res[node] == min_height:
nodes.append(node)
return nodes
def findDepth(self, node, graph, visited):
if visited[node] == True:
return -1
else:
res = 0
visited[node] = True
for neigh in graph[node]:
res = max(res, self.findDepth(neigh, graph, visited) + 1)
visited[node] = False
return res
|
3148cde7c931a22d9ef1ae5f69f8eda8dde30385 | joelranjithjebanesan7/Python-Programs | /sessionTwo/lab8.py | 504 | 3.78125 | 4 | def selling_price(list_price,binding_type,discount=0.1):
if(binding_type == "HB"):
return list_price
else:
DiscountPercent= float(list_price) * float(discount)
DiscountPrice=float(list_price) - float(DiscountPercent)
return DiscountPrice
list_price = input("Enter the list price:")
binding_type = input("Enter binding type:")
discount = input("Enter the discount:")
price = selling_price(list_price, binding_type,discount)
print("Price is:"+ str(price)) |
e7c19f6a6c0c693b51cacdf920dd98b47a85b6e9 | LucasJezap/GeometricAlgorithms | /5. Voronoi/test.py | 623 | 3.75 | 4 | from random import random,seed
from voronoi import Voronoi
def randomFirst(n, left, right):
pts = []
seed(1)
for i in range(0,n):
pts.append((round(left+random()*(right-left),8),round(left+random()*(right-left),8)))
return pts
left=int(input("Welcome to time complexity tester for generating Voronoi diagrams. "
"Enter left border of number of points: "))
right=int(input("Now enter right border: "))
times=[]
for i in range(left,right):
points=randomFirst(i,0,100)
v=Voronoi()
times.append((i,v.create_diagram(points)))
for t in times:
print(t)
|
adacfa66037f814c56253bc5e9db92b86bba093f | lauqerm/AlgoExam100 | /501 - Find Mode in Binary Search Tree.py | 1,017 | 3.5625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
a = {}
def travel(self, node):
if node == None:
return
if not node.val in self.a:
self.a[node.val] = 1
else:
self.a[node.val] += 1
if not node.left == None:
self.travel(node.left)
if not node.right == None:
self.travel(node.right)
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.a.clear()
d = []
self.travel(root)
mx = 0
for i in self.a:
if self.a[i] > mx:
mx = self.a[i]
print(mx)
for i in self.a:
print(i, self.a[i])
if mx == self.a[i]:
d.append(i)
print(d)
return d |
33e3f3db57749f123df73e565146da5e56f55c8c | alexanderluong/toUppercase | /toUppercase.py | 770 | 4.625 | 5 | #! /usr/bin/env python3
# toUppercase.py - converts clipboard text or argument to uppercase
import sys, pyperclip
if len(sys.argv) > 2:
print('''Usage: python toUppercase.py - converts clipboard text to uppercase OR
python toUppercase.py [string] - converts string to uppercase and prints to console''')
sys.exit()
if len(sys.argv) == 2:
inputString = sys.argv[1]
print(inputString.upper())
print('Would you like to copy this to the clipboard? (Type \'yes\' to copy)')
if input().lower() == 'yes':
pyperclip.copy(inputString.upper())
print('Copied to clipboard succesfully.')
else:
print('Converting string from clipboard to uppercase.')
clipboardString = pyperclip.paste()
pyperclip.copy(clipboardString.upper())
print('Conversion successful.')
|
c814e49a7c36cbb3a68c210f32d35aea61df1b08 | dldamian/ProgramasPython | /11-BinarioHexadecimal.py | 2,060 | 3.953125 | 4 | import time
print('Bienvenido al convertidor de Decimales a Binarios y Hexadecimales\n')
while True:
decimal = input('Generaremos una lista de decimales, binarios y hexadecimaneles.\n ¿Hasta que número quieres generar la lista?: ')
try:
decimal = int(decimal)
if decimal <= 0 or decimal == 1:
print('Error. Escribe al menos 2 o más')
else:
break
except:
print('Solo números enteros')
print('\nGenerando listas...')
lista_decimales = list(range(1,decimal+1))
binarios = [bin(binario) for binario in range(1,decimal+1)]
hexadecimales = [hex(hexa) for hexa in range(1,decimal+1)]
time.sleep(1)
print('Listo\n')
print('Usando "slices", vamos a mostrar solo una porción de la lista.')
while True:
empieza = input('¿Con qué decimal te gustaría empezar?: ')
try:
empieza = int(empieza)
if empieza <= 0 or empieza >= decimal:
print('Error. No podríamos mostrar datos a partir del valor que elegiste')
else:
break
except:
print('Solo números enteros')
while True:
termina = input('¿Con qué decimal te gustaría terminar?: ')
try:
termina = int(termina)
if termina <= empieza or termina > decimal:
print('Error. No podríamos mostrar datos a partir del valor que elegiste')
else:
break
except:
print('Solo números enteros')
print('\nValores decimales del ' + str(empieza) + ' al ' + str(termina))
for i in lista_decimales[empieza-1:termina]:
print(i)
print('\nValores binarios del ' + str(empieza) + ' al ' + str(termina))
for i in binarios[empieza-1:termina]:
print(i)
print('\nValores hexadecimales del ' + str(empieza) + ' al ' + str(termina))
for i in hexadecimales[empieza-1:termina]:
print(i)
input('\nPresiona ENTER para ver toda la tabla: ')
print('Decimal ----- Binario ----- Hexadecimal')
print('-'*50)
for d,b,h in zip(lista_decimales,binarios,hexadecimales):
print(str(d) + ' ----- ' + str(b) + ' ----- ' + str(h)) |
154b79a2cbdf52b3965098a45a4dbd1a3a0e9049 | TomRobo237/python_practice | /automate_the_boring_stuff/part_3/random_number.py | 794 | 3.84375 | 4 | import random, sys, os, math
amount = ''
rand_top = ''
while not amount:
print('How many random values would you like?')
amount = input()
if amount == 'exit':
sys.exit()
try:
amount = int(amount)
continue
except ValueError:
print('Please enter a whole number!\nIf you would like to quit, type exit.')
amount = ''
while not rand_top:
print('Maximum number?')
rand_top = input()
if rand_top == 'exit':
sys.exit()
try:
rand_top = int(rand_top)
continue
except ValueError:
print('Please enter a whole number!\nIf you would like to quit, type exit.')
rand_top = ''
for i in range( 0, amount ):
print('Number ' + str(i + 1) + ':\t' + str(random.randint(1, rand_top)))
|
cd3d9bd3cfc00c6cfdfe5143662ec823a57e7270 | priyaparshu/Python | /test.py | 912 | 3.671875 | 4 | class StackOverflowUser:
def __init__(self, name="", userid=0, rep=0):
self.name = name
self.userid = userid
self.rep = rep
def __str__(self):
s="Employee:"
s += ('(' + self.name + ',' + str(self.userid) + ',' + str(self.rep )+ ')')
return s
def dataentry(self):
daven = []
while True:
name = input("Enter name: ")
if not name:
return daven
userid = int(input("Enter user id: "))
rep = int(input("Enter rep: "))
dave = StackOverflowUser(name, userid, rep)
daven.append(dave)
return daven
d = StackOverflowUser()
data=d.dataentry()
for i in data:
print(i)
|
dede8db5e5853b241ba2b5b4abbb294b4eb847c5 | fkadeal/alx-higher_level_programming | /0x0B-python-input_output/11-student.py | 471 | 3.84375 | 4 | #!/usr/bin/python3
"""Module implementing class with method to serialize itself"""
class Student:
"""Class to represent student"""
def __init__(self, first_name, last_name, age):
"""Initialize new student instance with name and age"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self):
"""Create copy of attributes for use in json string"""
return self.__dict__.copy()
|
695bfded3d5f22544c02a9abb997d28a174a24bb | sophiadavis/nqueens | /nqueens.py | 3,283 | 3.90625 | 4 | # Written by Sophia Davis and Anna Quinlan, 4/27/14
import random
import sets
# Returns solution to for n by n board.
def nqueens(n):
if n <= 3:
return false
# make the board
board = []
j = 0
for i in range(0, n):
board.append(range(j, j + n))
j += n
printboard(board, n)
print
assignment = []
possible = [range(0, n*n)]
print "placing queens"
print backtrack(assignment, possible, n, board)
# with '0' as [0,0]
def getindex(i, n):
return (i%n, i/n)
def getrow(board, i, n):
return board[i / n]
def getcol(board, i, n):
col = []
for j in range(0, n):
col.append(board[j][i % n])
return col
def getdiagsleft(board, i, n):
index = getindex(i, n)
x = index[0]
y = index[1]
diags = [i]
while (x > 0 and y > 0):
new = board[y - 1][x - 1]
diags.append(new)
x -= 1
y -= 1
x = index[0]
y = index[1]
while (x < (n - 1) and y < (n - 1)):
new = board[y + 1][x + 1]
diags.append(new)
x += 1
y += 1
return diags
def getdiagsright(board, i, n):
index = getindex(i, n)
x = index[0]
y = index[1]
diags = [i]
while (x < (n - 1) and y > 0):
new = board[y - 1][x + 1]
diags.append(new)
x += 1
y -= 1
x = index[0]
y = index[1]
while (x > 0 and y < (n - 1)):
new = board[y + 1][x - 1]
diags.append(new)
x -= 1
y += 1
return diags
def printboard(board, n):
for i in range(0, n):
print board[i]
def backtrack(assignment, possible, n, board):
print "---Starting iteration of backtrack"
print assignment
if len(assignment) == n:
return assignment
# print "Options are"
currentoptions = possible[-1]
# print possible
# print currentoptions
print "---"
# get variable to assign
for loc in currentoptions:
print "considering location " + str(loc)
# if value is consistent with assignment
# add {var = value} to assignment
assignment.append(loc)
# perform inference
restricted = inference(board, loc, n, currentoptions)
# if inference not a failure
if len(restricted) >= (n - len(assignment)):
print "inference not a failure"
possible.append(restricted)
result = backtrack(assignment, possible, n, board)
print "this is result"
print result
if result:
print "in if"
return assignment
# remove {var = value} and inferences from assignment
print "BACKTRACK!!"
assignment.pop()
# possible.pop()
return False
## problem = it's not "popping" up far enough
# return all locations that can still have a queen
def inference(board, i, n, possible):
print "starting inference"
possibleset = sets.Set(possible)
rows = sets.Set(getrow(board, i, n))
cols = sets.Set(getcol(board, i, n))
ldiags = sets.Set(getdiagsleft(board, i, n))
rdiags = sets.Set(getdiagsright(board, i, n))
updated = possibleset.difference(rows).difference(cols).difference(ldiags).difference(rdiags)
return list(updated)
nqueens(8)
|
48c5c3c58c9236ceb57266a85c6311fb513fbf6f | LyaisanN/Homework_Figure | /src/Square.py | 1,094 | 3.84375 | 4 | from src.Figure import Figure
from src.Rectangle import Rectangle
from src.Circle import Circle
from src.Triangle import Triangle
class Square(Figure):
name = 'Square'
def __init__(self, height):
self.height = height
# self.width = width
super().__init__(name='Square', area=None, perimeter=None)
@property
def calculate_perimeter(self):
self.perimeter = 4 * self.height
return self.perimeter
@property
def calculate_area(self):
self.area = self.height ** 2
return self.area
# *** Вычисление площади и периметра квадрата ***
square = Square(20)
square_area = square.calculate_area
square_perimeter = square.calculate_perimeter
# *** Метод add_area(rectangle) ***
rectangle = Rectangle(15, 5)
square_add_rectangle = square.add_area(rectangle)
# *** Метод add_area(circle) ***
circle = Circle(10)
square_add_circle = square.add_area(circle)
# *** Метод add_area(triangle) ***
triangle = Triangle(13, 14, 15)
square_add_triangle = square.add_area(triangle)
|
4f6fa34946e31ece1ac1565a2436ffe696cddb96 | seanisoverhere/cs50 | /pset6/sentimentals/cash.py | 657 | 3.84375 | 4 | from cs50 import get_float
def main():
# Prompt user for change owed
while True:
change = get_float("Change owed: ")
# Ensure change is >= 0
if change >= 0:
break
# Rounding off change to cents
cents = round(change * 100)
# Initiailize coins
coins = 0
# Quarter (0.25$)
coins += cents // 25
cents %= 25
# Dimes (0.10$)
coins += cents // 10
cents %= 10
# Nickels (0.05$)
coins += cents // 5
cents %= 5
# Pennies (0.01$)
coins += cents // 1
cents %= 1
# Print no. of coins used
print(coins)
if __name__ == "__main__":
main()
|
48cbaff314209e6ba9512e2cb5b905b755abcf18 | shubham-aicoder/100DaysOfCode | /100DoC_D25.py | 624 | 3.890625 | 4 | def check_anagram(sentence_1,sentence_2):
#write your code here
sentence_1=sentence_1.lower().replace(" ","")
sentence_2=sentence_2.lower().replace(" ","")
if len(sentence_1)==0 and len(sentence_2)==0:
return True
for i in sentence_2:
if sentence_1.find(i)==-1:
return False
else:
sentence_1=sentence_1.replace(i,'',1)
if len(sentence_1)==0:
return True
if __name__ == "__main__":
sentence_1 = ""
sentence_2 = ""
print(check_anagram(sentence_1,sentence_2))
|
055768b604caec4b5bfd2e611cfc88285493a256 | BorthakurAyon/Algorithms | /puzzles/DiceTrial.py | 536 | 3.625 | 4 | import random
class Dicetrial(object):
def simulation(self, n):
self.count = 0
for _ in range(n):
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
score = dice1 + dice2
if score % 2 == 0 or score > 7:
self.count += 1
print(self.count/n)
if __name__ == '__main__':
ins = Dicetrial()
ins.simulation(10000)
|
98bde0321ebece804a934f960351659d2d458130 | AllenWang314/mpc-attendance | /script.py | 794 | 3.515625 | 4 | import pandas as pd
static_path = "static/"
csv_name = "poker_club_users.csv"
email_file_name = "emails.txt"
missing_accounts_file = "missing.txt"
# get only the columns you want from the csv file
df = pd.read_csv(static_path + csv_name)
result = df.to_dict()
emails_registered = result["Email"].values()
emails_registered_processed = [e.lower() for e in emails_registered if type(e) == str]
inFile = open(static_path + email_file_name, "r")
emails = inFile.readlines()
outFile = open(static_path + missing_accounts_file, "w")
emails_unregistered = []
for email in emails:
if email[:-1].lower() not in emails_registered_processed:
emails_unregistered.append(email[:-1].lower())
for email in emails_unregistered:
outFile.write(email + "\n")
inFile.close()
outFile.close()
|
373214f74b7f92cff6f8dc8f244df5f5ec02f797 | Khrystynka/LeetCodeProblems | /7_reverse-integer.py | 471 | 3.609375 | 4 | # Problem Title: Reverse Integer
import sys
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
res = ''
neg = False
if x < 0:
neg = True
x = x*(-1)
s = str(x)
res = s[::-1]
res = int(res)
if (not neg and res > 2**31) or (neg and -res < (-2**31-1)):
return 0
else:
return -res if neg else res
|
280f1927e345e2f1d071526df75d38f2f276aee4 | shiny132/pystudy | /source/quiz01_1.py | 343 | 3.6875 | 4 | str = "Life is too short, You need Python"
str = str.lower()
str = str.replace(" ","").replace(",","")
lst = list(str)
print("lst: ", lst)
# str = str.lower().replace(" ","").replace(",","")
chars = set(lst)
print("chars:", chars)
lst = list(chars)
print("lst: ", lst)
list.sort(lst)
print("lst: ", lst)
print("length of lis: ", len(lst)) |
08939f7fcb2c11f1d294eae8fb4b3eee90bc5191 | AzamatGainullin/education_2021_ | /obuchenie_bs4.py | 4,711 | 3.671875 | 4 | from bs4 import BeautifulSoup
import requests
import re
### ПОЛУЧЕНИЕ ИЗ ФАЙЛА ###
html_doc = """<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
### ПОЛУЧЕНИЕ ИЗ ИНТЕРНЕТА ###
def get_html(url):
r = requests.get(url)
return r.text
html_doc = get_html('https://wordpress.org/')
soup = BeautifulSoup (html_doc, 'html.parser')
print(soup.prettify())
soup.title.text
soup.find_all('a')
for link in soup.find_all('a'):
print(link.get('href'))
soup.get_text()
soup.section #извлекается первое вхождение тега
soup.section['class']
soup.find_all('section')[2]['class']
soup.find_all('section')[2].find('h2').text
Универсальный способ поиска по тегам любой вложенности,
любого повторяющегося числа тегов:
Ищем внутри любых тегов н-р <section>, если известно отличительное class == 'features':
for i in soup.find_all('section'):
if i['class']==['features']:
print(i.find('h2').text)
soup.find_all('section')[2].p.string
soup.section
stripped_strings достает любые тексты внути объекта супа, удаляя пробелы:
for string in soup.stripped_strings:
print(repr(string))
метод next_siblings, применяемый к первому элементу уровня section,
позволяет перебрать все элементы данного уровня:
for sibling in soup.section.next_siblings:
print(repr(sibling))
.find_all - работает только с тегами. Следующий код находит все теги в документе
(то есть исключает текст и т.п.):
for tag in soup.find_all(True):
print(tag.name)
Использование своих функций для отбора тегов:
def has_href_and_data_title(tag):
return tag.has_attr('href') and tag.has_attr('data-title')
soup.find_all(has_href_and_data_title)
Обновление универсального способа поиска по тегам любой вложенности,
любого повторяющегося числа тегов:
Ищем внутри любых тегов н-р <section>, если известно отличительное class == 'features':
))))). Но пока что находим только всю секцию:
soup.find_all("section", "features")
Любой нераспознанный аргумент будет превращен в фильтр по атрибуту тега.
Если вы передаете значение для аргумента с именем id,
Beautiful Soup будет фильтровать по атрибуту «id» каждого тега:
(кстати круто. по любому атрибуту найдет все что угодно)
soup.find_all(id="download")
Находит все, где есть href:
soup.find_all(href=True)
Если вы передадите значение для href, Beautiful Soup отфильтрует по атрибуту «href»
каждого тега:
soup.find_all(href=re.compile("face"))
И третий способ - используем нижнее подчеркивание class_:
soup.find_all("section", class_="features")
Помните, что один тег может иметь несколько значений для атрибута «class».
С помощью string вы можете искать строки вместо тегов.
soup.find_all(string=re.compile("Beautiful"))
Если относиться к объекту BeautifulSoup или объекту Tag так, будто это функция,
то это похоже на вызов find_all() с этим объектом.
soup(string=re.compile("Beautiful"))
first_link.find_next_siblings("a") - список все одноуровневых эелементов для "а".
Поддержка селекторов CSS.
soup.select("title")
soup.select('a[href]') - поиск по селектору для href работает лучше чем
просто find_all.
|
6c2caf02084e1b0f4cc055cc416a345297b263d1 | woohyun212/Data_Science_and_AI_introductory_Coding_Solution | /chapter4/ex4_7.py | 232 | 3.515625 | 4 | import random
n1 = random.randint(1, 100)
n2 = random.randint(1, 100)
number = int(input(str(n1) + " + " + str(n2) + " = "))
if number == n1 + n2:
print('잘했어요!!!')
else:
print('정답은 %d 입니다' % (n1 + n2))
|
dc5e65e4f63fe32b7b5519fb1c38b2d0f92c66d0 | hashamtanveer/Crossword-Puzzle-Solver | /solver.py | 2,722 | 3.625 | 4 |
import numpy as np
def find(word):
if checkRows(word) or checkCols(word) or checkDiag(word) or checkDiagRev(word):
return True
else:
return False
def checkRows(word):
found = False
for row in range(board.shape[0]) :
row_array = board[row,:]
row_string = ''.join(row_array)
row_string_r = row_string[::-1]
if word in row_string or word in row_string_r:
found = True
return found
def checkCols(word):
found = False
for col in range(board.shape[1]) :
col_array = board[:,col]
col_string = ''.join(col_array)
col_string_r = col_string[::-1]
if word in col_string or word in col_string_r:
found = True
return found
def checkDiag(word):
found = False
for diag in range(np.negative(board.shape[0])+1, board.shape[1]) :
diag_array = board.diagonal(diag)
diag_string = ''.join(diag_array)
diag_string_r = diag_string[::-1]
if word in diag_string or word in diag_string_r:
found = True
return found
def checkDiagRev(word):
found = False
board_rev=np.fliplr(board)
for diagr in range(np.negative(board_rev.shape[0])+1, board_rev.shape[1]) :
diagr_array = board_rev.diagonal(diagr)
diagr_string = ''.join(diagr_array)
diagr_string_r = diagr_string[::-1]
if word in diagr_string or word in diagr_string_r:
found = True
return found
if __name__ == '__main__': # check if run this script as the main file
# If run this Python script file as the main file, then do following tests
# else (e.g. when import this script into another file), the following
# code will be skipped.
# --- Example test setup 1: for testing the whole function "find"
board = np.array([['A','A','A','T'],
['A','G','G','C'],
['A','T','G','C'],
['A','A','T','A'],
['A','T','A','A']])
word = 'ACCT' # Expect True, ACCT is at the last column, read upward
# word = 'CTT' # Expect True, CTT is at anti diag, SouthWest direction
# word = 'ATTA' # Expect True, ATTA is at diag, SouthEast direction
# word = 'AAA' # Expect True, found in many directions and locations
# word = 'TTTA' # Expect False, not anywhere
# word = 'TTTAGCTA' # Expect False, not anywhere, also too long
print('=== Test case starts ===========================================')
result = find(word)
print(board)
print('*** Target word:', word, '\tResult:', result)
print('=== Test case ends ===========================================')
|
d88462c3b055970b704cec2f769de2e03f544a89 | csl-ugent/semantic-renewability | /core/parser.py | 2,464 | 3.640625 | 4 | """
Module used for parser related functionality.
"""
import logging
import re
class Parser:
"""
Class used for parsing input files using a parse function
the output is returned and can be written away to an output file.
"""
@staticmethod
def parse_file(input_file, parse_function, output_file=None):
# Debug
logging.debug("Parsing file: " + input_file + "...")
# The result of the parser.
output_lines = []
# We open the file for reading.
with open(input_file, "r") as fp:
# We iterate over all lines within the input file
# and apply the parse function to each line to
# generate output.
for line in fp:
parsed_output = parse_function(line)
if parsed_output is not None:
output_lines.append(parsed_output)
# We also write the result to an output file (in case this is specified)
if output_file is not None:
# We open the output file for writing.
with open(output_file, "w") as fp:
# We write away each of the lines.
for line in output_lines:
fp.write(line + "\n")
# We return the output.
return output_lines
@staticmethod
def parse_files(input_files, parse_function, output_files=None):
# The results of parsing the file individually.
results = []
# We parse each file using the parse function and corresponding output file.
for idx, input_file in enumerate(input_files):
results.append(Parser.parse_file(input_file, parse_function,
output_files[idx] if output_files is not None else None))
# We return the results.
return results
def data_section_extracter(line):
"""
Method used to extract the relevant function sections.
:param line: the current line in the file.
:return: a list of relevant function sections.
"""
result = re.search('([^ ]*\.data\.[^ \n]*)', line)
if result is not None:
return result.group(0)
def text_section_extracter(line):
"""
Method used to extract the relevant function sections.
:param line: the current line in the file.
:return: a list of relevant function sections.
"""
result = re.search('([^ ]*\.text\.[^ \n]*)', line)
if result is not None:
return result.group(0)
|
c8002cc6c31f04c52215cba52948dbd113bbfc1e | kjin97/thvln | /THavalonQuest.py | 14,437 | 3.90625 | 4 | #!/usr/bin/env python3
import os
import random
import shutil
def main():
# get the number of players
num_players = int(input("How many people are playing?\n"))
if num_players < 5 or num_players > 10:
print("Invalid number of players")
exit(1)
# get the names of players
players = set() # use as set to avoid duplicate players
for player_num in range(1, num_players+1):
players.add(input("Who is player " + str(player_num) + "?\n"))
players = list(players) # convert to list
random.shuffle(players) # ensure random order, though set should already do that
if len(players) != num_players:
print("No duplicate player names")
exit(1)
# choose 3 players
three_players = random.sample(players, 3)
# first two propose for the first mission, last is starting player of second round
first_mission_proposers = three_players[:2]
second_mission_starter = three_players[2]
# assign the roles in the game
good_roles = ["Merlin", "Percival", "Tristan", "Iseult", "Lancelot"]
evil_roles = ["Mordred", "Morgana", "Maelegant"]
if num_players >= 7:
good_roles.append("Guinevere")
good_roles.append("Arthur")
evil_roles.append("Agravaine")
evil_roles.append("Colgrevance")
if num_players != 9:
evil_roles.append("Oberon")
if num_players == 10:
good_roles.append("Gawain")
# shuffle the roles
random.shuffle(good_roles)
random.shuffle(evil_roles)
# determine the number of roles in the game
if num_players == 10:
num_evil = 4
num_good = 6
elif num_players == 9:
num_evil = 3
num_good = 4
elif num_players == 7 or num_players == 8:
num_evil = 3
num_good = num_players - num_evil
else: # 5 or 6
num_evil = 2
num_good = num_players - num_evil
# assign players to teams
assignments = {}
reverse_assignments = {}
good_roles_in_game = set()
evil_roles_in_game = set()
if num_players == 9:
pelinor = players[8]
assignments[pelinor] = "Pelinor"
reverse_assignments["Pelinor"] = pelinor
questing_beast = players[7]
assignments[questing_beast] = "Questing Beast"
reverse_assignments["Questing Beast"] = questing_beast
good_players = players[:num_good]
evil_players = players[num_good:num_good + num_evil]
# assign good roles
for good_player in good_players:
player_role = good_roles.pop()
assignments[good_player] = player_role
reverse_assignments[player_role] = good_player
good_roles_in_game.add(player_role)
# assign evil roles
for evil_player in evil_players:
player_role = evil_roles.pop()
assignments[evil_player] = player_role
reverse_assignments[player_role] = evil_player
evil_roles_in_game.add(player_role)
# delete and recreate game directory
if os.path.isdir("game"):
shutil.rmtree("game")
os.mkdir("game")
# make every role's file
# Merlin sees: Morgana, Maelegant, Oberon, Agravaine, Colgrevance, Lancelot* as evil
if "Merlin" in good_roles_in_game:
# determine who Merlin sees
seen = []
for evil_player in evil_players:
if assignments[evil_player] != "Mordred":
seen.append(evil_player)
if "Lancelot" in good_roles_in_game:
seen.append(reverse_assignments["Lancelot"])
random.shuffle(seen)
# and write this info to Merlin's file
player_name = reverse_assignments["Merlin"]
filename = "game/" + player_name + ".txt"
with open(filename, "w") as file:
file.write("You are Merlin.\n")
for seen_player in seen:
file.write("You see " + seen_player + " as evil.\n")
# Percil sees Merlin, Morgana* as Merlin
if "Percival" in good_roles_in_game:
# determine who Percival sees
seen = []
if "Merlin" in good_roles_in_game:
seen.append(reverse_assignments["Merlin"])
if "Morgana" in evil_roles_in_game:
seen.append(reverse_assignments["Morgana"])
random.shuffle(seen)
# and write this info to Percival's file
player_name = reverse_assignments["Percival"]
filename = "game/" + player_name + ".txt"
with open(filename, "w") as file:
file.write("You are Percival.\n")
for seen_player in seen:
file.write("You see " + seen_player + " as Merlin (or is it...?).\n")
if "Tristan" in good_roles_in_game:
# write the info to Tristan's file
player_name = reverse_assignments["Tristan"]
filename = "game/" + player_name + ".txt"
with open(filename, "w") as file:
file.write("You are Tristan.\n")
# write Iseult's info to file
if "Iseult" in good_roles_in_game:
iseult_player = reverse_assignments["Iseult"]
file.write(iseult_player + " is your lover.\n")
else:
file.write("Nobody loves you. Not even your cat.\n")
if "Iseult" in good_roles_in_game:
# write this info to Iseult's file
player_name = reverse_assignments["Iseult"]
filename = "game/" + player_name + ".txt"
with open(filename, "w") as file:
file.write("You are Iseult.\n")
# write Tristan's info to file
if "Tristan" in good_roles_in_game:
tristan_player = reverse_assignments["Tristan"]
file.write(tristan_player + " is your lover.\n")
else:
file.write("Nobody loves you.\n")
if "Lancelot" in good_roles_in_game:
# write ability to Lancelot's file
player_name = reverse_assignments["Lancelot"]
filename = "game/" + player_name + ".txt"
with open(filename, "w") as file:
file.write("You are Lancelot. You are on the Good team. \n\n")
file.write("Ability: Reversal \n")
file.write("You are able to play Reversal cards while on missions. A Reversal card inverts the result of a mission; a mission that would have succeeded now fails and vice versa. \n \n")
file.write("Note: In games with at least 7 players, a Reversal played on the 4th mission results in a failed mission if there is only one Fail card, and otherwise succeeds. Reversal does not interfere with Agravaine's ability to cause the mission to fail.")
if "Guinevere" in good_roles_in_game:
# determine who Guinevere sees
seen = []
if "Arthur" in good_roles_in_game:
seen.append(reverse_assignments["Arthur"])
if "Lancelot" in good_roles_in_game:
seen.append(reverse_assignments["Lancelot"])
if "Maelegant" in evil_roles_in_game:
seen.append(reverse_assignments["Maelegant"])
random.shuffle(seen)
# and write this info to Guinevere's file
player_name = reverse_assignments["Guinevere"]
filename = "game/" + player_name
with open(filename, "w") as file:
file.write("You are Guinevere.\n")
for seen_player in seen:
file.write("You see " + seen_player + " as either Lancelot, Maelegant, or Arthur.\n")
if "Arthur" in good_roles_in_game:
# determine which roles Arthur sees
seen = []
for good_role in good_roles_in_game:
seen.append(good_role)
random.shuffle(seen)
# and write this info to Arthur's file
player_name = reverse_assignments["Arthur"]
filename = "game/" + player_name
with open(filename, "w") as file:
file.write("You are Arthur.\n\n")
file.write("The following good roles are in the game:\n")
for seen_role in seen:
if seen_role != "Arthur":
file.write(seen_role + "\n")
file.write("\n")
file.write("Ability: Redemption\n")
file.write("If three of the first four missions fail, you may reveal that you are Arthur. You may, after consulting the other players, attempt to identify all evil players in the game. If you are correct, then the assassination round occurs as if three missions had succeeded; should the evil team fail to assassinate a viable target, the good team wins.\n")
if "Gawain" in good_roles_in_game:
# determine what Gawain sees
seen = []
player_name = reverse_assignments["Gawain"]
good_players_no_gawain = set(good_players) - set([player_name])
# guaranteed see a good player
seen_good = random.sample(good_players_no_gawain, 1)
seen.append(seen_good[0])
# choose two other players randomly
remaining_players = set(players) - set([player_name]) - set(seen_good)
seen += random.sample(remaining_players, 2)
random.shuffle(seen)
# write info to Gawain's file
filename = "game/" + player_name
with open(filename, "w") as file:
file.write("You are Gawain.\n\n")
file.write("The following players are not all evil:\n")
for seen_player in seen:
file.write(seen_player + "\n")
file.write("\nAbility: Whenever a mission (other than the 1st) is sent, you may declare as Gawain to reveal a single person's played mission card. The mission card still affects the mission. (This ability functions identically to weak Inquisition and occurs after regular Inquisitions.) If the card you reveal is a Success, you are immediately 'Exiled' and may not go on missions for the remainder of the game, although you may still vote and propose missions.\n\n")
file.write("You may use this ability once per mission as long as you are neither on the mission team nor 'Exiled'. You may choose to not use your ability on any round, even if you would be able to use it.\n");
# make list of evil players seen to other evil
if "Oberon" in evil_roles_in_game:
evil_players = list(set(evil_players) - set([reverse_assignments["Oberon"]]))
random.shuffle(evil_players)
if "Mordred" in evil_roles_in_game:
player_name = reverse_assignments["Mordred"]
filename = "game/" + player_name + ".txt"
with open(filename, "w") as file:
file.write("You are Mordred. (Join us, we have jackets and meet on Thursdays. ~ Andrew and Kath)\n")
for evil_player in evil_players:
if evil_player != player_name:
file.write(evil_player + " is a fellow member of the evil council.\n")
if "Morgana" in evil_roles_in_game:
player_name = reverse_assignments["Morgana"]
filename = "game/" + player_name + ".txt"
with open(filename, "w") as file:
file.write("You are Morgana.\n")
for evil_player in evil_players:
if evil_player != player_name:
file.write(evil_player + " is a fellow member of the evil council.\n")
if "Oberon" in evil_roles_in_game:
player_name = reverse_assignments["Oberon"]
filename = "game/" + player_name
with open(filename, "w") as file:
file.write("You are Oberon.\n")
for evil_player in evil_players:
file.write(evil_player + " is a fellow member of the evil council.\n")
file.write("\nAbility: Should any mission get to the last proposal of the round, after the people on the mission have been named, you may declare as Oberon to replace one person on that mission with yourself.\n\n")
file.write("Note: You may not use this ability after two missions have already failed. Furthermore, you may only use this ability once per game.\n")
if "Agravaine" in evil_roles_in_game:
player_name = reverse_assignments["Agravaine"]
filename = "game/" + player_name
with open(filename, "w") as file:
file.write("You are Agravaine.\n")
for evil_player in evil_players:
if evil_player != player_name:
file.write(evil_player + " is a fellow member of the evil council.\n")
file.write("\nAbility: On any mission you are on, after the mission cards have been revealed, should the mission not result in a Fail (such as via a Reversal, requiring 2 fails, or other mechanics), you may formally declare as Agravaine to force the mission to Fail anyway.\n\n");
file.write("Drawback: You may only play Fail cards while on missions.\n");
if "Maelegant" in evil_roles_in_game:
# write ability to Lancelot's file
player_name = reverse_assignments["Maelegant"]
filename = "game/" + player_name + ".txt"
with open(filename, "w") as file:
file.write("You are Maelegant. You are on the Evil team. \n\n")
for evil_player in evil_players:
if evil_player != player_name:
file.write(evil_player + " is a fellow member of the evil council.\n")
file.write("\nAbility: Reversal \n")
file.write("You are able to play Reversal cards while on missions. A Reversal card inverts the result of a mission; a mission that would have succeeded now fails and vice versa. \n \n")
file.write("Note: In games with at least 7 players, a Reversal played on the 4th mission results in a failed mission if there is only one Fail card, and otherwise succeeds. Reversal does not interfere with Agravaine's ability to cause the mission to fail.")
if "Colgrevance" in evil_roles_in_game:
player_name = reverse_assignments["Colgrevance"]
filename = "game/" + player_name
with open(filename, "w") as file:
file.write("You are Colgrevance.\n")
for evil_player in evil_players:
if evil_player != player_name:
file.write(evil_player + " is " + assignments[evil_player] + ".\n")
if "Oberon" in evil_roles_in_game:
file.write(reverse_assignments["Oberon"] + " is Oberon.\n")
# TODO: pelinor + questing beast
if num_players == 9:
# write pelinor's information
pelinor_filename = "game/" + pelinor
with open(pelinor_filename, "w") as file:
file.write("You are Pelinor.\n\n")
file.write("You must fulfill two of the following conditions to win:\n")
file.write("[1]: If Good wins via three mission success.\n")
file.write("[2]: If you go on the last mission with the Questing Beast.\n")
file.write("[3]: If, after the Assassination Round, you can guess the Questing Beast.\n")
questing_beast_filename = "game/" + questing_beast
with open(questing_beast_filename, "w") as file:
file.write("You are the Questing Beast.\n")
file.write("You must play the 'Questing Beast was here' card on missions.\n\n")
file.write("You must fulfill exactly one (not both) of the following conditions to win:\n")
file.write("[1]: If Evil wins via three missions failing.\n")
file.write("[2]: You never go on a mission with Pelinor.\n\n")
file.write(pelinor + " is Pelinor.\n")
# write start file
with open("game/start", "w") as file:
file.write("The players proposing teams for the first mission are:\n")
for first_mission_proposer in first_mission_proposers:
file.write(first_mission_proposer + "\n")
file.write("\n" + second_mission_starter + " is the starting player of the 2nd round.\n")
# write do not open
with open("game/DoNotOpen", "w") as file:
file.write("Player -> Role\n")
for player in players:
file.write(player + " -> " + assignments[player] + "\n")
if __name__ == "__main__":
main() |
f6506d8340ddf40153d5083be07ffd08b13b7a2d | Vshltayade/Q3_VishalTayade | /Q3.py | 388 | 3.703125 | 4 | inp = list(input().split())
def countingValleys(inp):
level = 0
valleys = 0
for direction in inp:
if direction == "U":
level += 1
if level == 0:
valleys += 1
else:
level -= 1
return valleys
if __name__ == "__main__":
print(countingValleys(inp))
|
391a33930df1454d5c225b1be3b19949b7996255 | JDer-liuodngkai/LeetCode | /torch/loss_vis.py | 543 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def focal_loss():
"""
段长相同情况下,vis 不同 n 取极大值的位置
乘积: x ** (n / x)
"""
xs = np.arange(1, 100) / 100
# 可见 当 p -> 1 时,loss 趋近 0,确信的样本 更少的 loss
for r in [0, 0.5, 1, 2, 5]: # r=0 就是 CE LOSS
ys = [-(1 - x) ** r * np.log(x) for x in xs]
plt.plot(xs, ys, label=f'r={r}')
plt.legend()
plt.title(r'focal loss')
plt.show()
if __name__ == '__main__':
focal_loss()
|
758df61ffa6ef0e7af009900cbf490e0b120c657 | ankursharma7/100-Days-Of-Code | /Day 8/06_pr_01.py | 304 | 4.09375 | 4 | def maximum(num1,num2,num3):
if (num1>num2):
if(num1>num2):
return num1
else:
return num2
else:
if (num2>num3):
return num2
else:
return num3
m = maximum(3,67,899)
print("The value of the maximum is", m) |
6db8850a9a9fbc271b1ec4a621795ab2bc7af9d0 | AbdelrahmanRadwan/Natural-Language-Processing-Package | /Minimum_Edit_Distance/minimum_edit_distance.py | 13,435 | 3.703125 | 4 | import operator
import math
def suggestions1(lines, search):
clubs = {}
search_club_name= search.split()[0]
for club in lines:
distance = calculate_minimum_edit_distance(club, search)
for club_token in club.split():
distance = min(distance, calculate_minimum_edit_distance(club_token, search_club_name))
clubs[club] = distance
clubs = sorted(clubs.items(), key=operator.itemgetter(1))
for i in range(5):
for j in range(i+1,5):
if clubs[i][1] == clubs[j][1] and \
len(clubs[i][0]) >= len(clubs[j][0]):
clubs[i], clubs[j] = clubs[j], clubs[i]
for i in range(5):
if clubs[i][1] == 0 and search == clubs[i][0]:
print ("Perfect match! - %s" % (clubs[i][0]))
return
print('Suggestions1 >>', end='')
for i in range(5):
if clubs[i][1] < 3:
print (clubs[i][0] + " (%s) - " %(clubs[i][1]), end= '' )
elif i == 0 and clubs[i][1] <=5:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
break
elif i==0:
print ("No such team!", end='')
else:
break
print("")
def suggestions2(lines, search):
clubs = {}
search_tokens = search.split()
for club_name in lines:
club_name_tokens= club_name.split()
distance = 0
for i in range(0, min(len(search_tokens), len(club_name_tokens))):
distance+=calculate_minimum_edit_distance(search_tokens[i], club_name_tokens[i])
clubs[club_name] = distance
clubs = sorted(clubs.items(), key=operator.itemgetter(1))
for i in range(5):
for j in range(i+1,5):
if clubs[i][1] == clubs[j][1] and \
len(clubs[i][0]) >= len(clubs[j][0]):
clubs[i], clubs[j] = clubs[j], clubs[i]
for i in range(5):
if clubs[i][1] == 0 and search == clubs[i][0]:
print ("Perfect match! - %s" % (clubs[i][0]))
return
print('Suggestions2 >>', end='')
for i in range(5):
if clubs[i][1] < 3:
print (clubs[i][0] + " (%s) - " %(clubs[i][1]), end= '' )
elif i == 0 and clubs[i][1] <=5:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
break
elif i==0:
print ("No such team!", end='')
else:
break
print("")
def suggestions3(lines, search):
clubs = {}
search_tokens = search.split()
for club in lines:
distances = []
club_tokens= club.split()
for token1 in search_tokens:
distance=10000
for token2 in club_tokens:
distance=min(distance, calculate_minimum_edit_distance(token1, token2))
distances.append(distance)
n = min(len(search_tokens), len(club_tokens))
distances.sort()
avg=abs(len(search_tokens) - len(club_tokens))
for i in range(n):
avg+=distances[i]
avg/=n
clubs[club]=avg
clubs = sorted(clubs.items(), key=operator.itemgetter(1))
for i in range(5):
for j in range(i + 1, 5):
if clubs[i][1] == clubs[j][1] and \
len(clubs[i][0]) >= len(clubs[j][0]):
clubs[i], clubs[j] = clubs[j], clubs[i]
for i in range(5):
if clubs[i][1] == 0 and search == clubs[i][0]:
print("Perfect match! - %s" % (clubs[i][0]))
return
print('Suggestions3 >>', end='')
for i in range(5):
if clubs[i][1] < 3:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
elif i == 0 and clubs[i][1] <=5:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
break
elif i == 0:
print("No such team!", end='')
else:
break
print("")
def suggestions4(lines, search):
clubs = {}
search_tokens = search.split()
for club in lines:
distances = []
club_tokens= club.split()
for token1 in search_tokens:
distance=10000
for token2 in club_tokens:
distance=min(distance, calculate_minimum_edit_distance(token1, token2))
distances.append(distance)
n = min(len(search_tokens), len(club_tokens))
distances.sort()
avg=0
for i in range(n):
avg+=distances[i]
avg/=n
clubs[club]=avg
clubs = sorted(clubs.items(), key=operator.itemgetter(1))
for i in range(5):
for j in range(i + 1, 5):
if clubs[i][1] == clubs[j][1] and \
len(clubs[i][0]) >= len(clubs[j][0]):
clubs[i], clubs[j] = clubs[j], clubs[i]
for i in range(5):
if clubs[i][1] == 0 and search == clubs[i][0]:
print("Perfect match! - %s" % (clubs[i][0]))
return
print('Suggestions4 >>', end='')
for i in range(5):
if clubs[i][1] < 3:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
elif i == 0 and clubs[i][1] <=5:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
break
elif i == 0:
print("No such team!", end='')
break
else:
break
print("")
def suggestions5(lines_synonyms, search):
clubs = {}
search_tokens = search.split()
for line in lines_synonyms:
club_synonyms = line.split(',')
for club in club_synonyms:
distances = []
club_tokens = club.split()
if not club_tokens:
continue
for token1 in search_tokens:
distance = 10000
for token2 in club_tokens:
distance = min(distance, calculate_minimum_edit_distance(token1, token2))
distances.append(distance)
n = min(len(search_tokens), len(club_tokens))
distances.sort()
avg=0
for i in range(n):
avg+=distances[i]
avg/=n
if club_synonyms[0] in clubs:
clubs[club_synonyms[0]]=min(avg, clubs[club_synonyms[0]])
else:
clubs[club_synonyms[0]] = avg
clubs = sorted(clubs.items(), key=operator.itemgetter(1))
for i in range(5):
for j in range(i + 1, 5):
if clubs[i][1] == clubs[j][1] and \
len(clubs[i][0]) >= len(clubs[j][0]):
clubs[i], clubs[j] = clubs[j], clubs[i]
for i in range(5):
if clubs[i][1] == 0 and search == clubs[i][0]:
print("Perfect match! - %s" % (clubs[i][0]))
return
print('Suggestions5 >>', end='')
for i in range(5):
if clubs[i][1] < 3:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
elif i == 0 and clubs[i][1] <=5:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
break
elif i == 0:
print("No such team!", end='')
break
else:
break
print("")
def suggestions6(lines_synonyms, search):
clubs = {}
search_tokens = search.split()
for line in lines_synonyms:
club_synonyms = line.split(',')
for club in club_synonyms:
distances = []
club_tokens = club.split()
if not club_tokens:
continue
for token1 in search_tokens:
distance = 10000
for token2 in club_tokens:
distance = min(distance, calculate_minimum_edit_distance(token1, token2))
distances.append(distance)
n = min(len(search_tokens), len(club_tokens))
distances.sort()
avg=0
for i in range(n):
avg+=distances[i]
avg/=n
if club_synonyms[0] in clubs:
clubs[club_synonyms[0]]=min(avg, clubs[club_synonyms[0]])
else:
clubs[club_synonyms[0]] = avg
clubs = sorted(clubs.items(), key=operator.itemgetter(1))
for i in range(5):
for j in range(i + 1, 5):
if clubs[i][1] == clubs[j][1] and \
len(clubs[i][0]) >= len(clubs[j][0]):
clubs[i], clubs[j] = clubs[j], clubs[i]
for i in range(5):
if clubs[i][1] == 0 and search == clubs[i][0]:
print("Perfect match! - %s" % (clubs[i][0]))
return
print('Suggestions6 >>', end='')
for i in range(5):
if clubs[i][1] < 3:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
elif i == 0 and clubs[i][1] <=5:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
break
elif i == 0:
print("No such team!", end='')
break
else:
break
print("")
def suggestions7(lines_synonyms, search):
clubs = {}
search_tokens = search.split()
for line in lines_synonyms:
club_synonyms = line.split(',')
for club in club_synonyms:
distances = []
club_tokens = club.split()
if not club_tokens:
continue
for token1 in search_tokens:
distance = 10000
for token2 in club_tokens:
distance = min(distance, calculate_minimum_edit_distance(token1, token2))
distances.append(distance)
n = min(len(search_tokens), len(club_tokens))
distances.sort()
avg = abs(len(search_tokens) - len(club_tokens))
for i in range(n):
avg+=distances[i]
avg/=n
if club_synonyms[0] in clubs:
clubs[club_synonyms[0]]=min(avg, clubs[club_synonyms[0]])
else:
clubs[club_synonyms[0]] = avg
clubs = sorted(clubs.items(), key=operator.itemgetter(1))
for i in range(5):
for j in range(i + 1, 5):
if clubs[i][1] == clubs[j][1] and \
len(clubs[i][0]) >= len(clubs[j][0]):
clubs[i], clubs[j] = clubs[j], clubs[i]
for i in range(5):
if clubs[i][1] == 0 and search == clubs[i][0]:
print("Perfect match! - %s" % (clubs[i][0]))
return
print('Suggestions7 >>', end='')
for i in range(5):
if clubs[i][1] < 3:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
elif i == 0 and clubs[i][1] <=5:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
break
elif i == 0:
print("No such team!", end='')
break
else:
break
print("")
def suggestions8(lines_synonyms, search):
clubs = {}
search_tokens = search.split()
for line in lines_synonyms:
club_synonyms = line.split(',')
for club in club_synonyms:
distances = []
club_tokens = club.split()
if not club_tokens:
continue
for token1 in search_tokens:
distance = 10000
for token2 in club_tokens:
distance = min(distance, calculate_minimum_edit_distance(token1, token2))
distances.append(distance)
n = min(len(search_tokens), len(club_tokens))
distances.sort()
avg = abs(len(search_tokens) - len(club_tokens))
for i in range(n):
avg+=distances[i]
avg/=n
if club_synonyms[0] in clubs:
clubs[club_synonyms[0]]=min(avg, clubs[club_synonyms[0]])
else:
clubs[club_synonyms[0]] = avg
clubs = sorted(clubs.items(), key=operator.itemgetter(1))
for i in range(5):
for j in range(i + 1, 5):
if clubs[i][1] == clubs[j][1] and \
len(clubs[i][0]) >= len(clubs[j][0]):
clubs[i], clubs[j] = clubs[j], clubs[i]
for i in range(5):
if clubs[i][1] == 0 and search == clubs[i][0]:
print("Perfect match! - %s" % (clubs[i][0]))
return
print('Suggestions8 >>', end='')
for i in range(5):
if clubs[i][1] < 3:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
elif i == 0 and clubs[i][1] <=5:
print(clubs[i][0] + " (%s) - " % (clubs[i][1]), end='')
break
elif i == 0:
print("No such team!", end='')
break
else:
break
print("")
def calculate_minimum_edit_distance (s1,s2):
"Calculate Levenstein edit distance for strings s1 and s2."
len1 = len (s1) # vertically
len2 = len (s2) # horizontally
# Allocate the table
table = [None]*(len2+1)
for i in range(len2+1):
table[i] = [0]*(len1+1)
# Initialize the table
for i in range(1, len2+1):
table[i][0] = i
for i in range(1, len1+1):
table[0][i] = i
# Do dynamic programming
for i in range(1,len2+1):
for j in range(1,len1+1):
if s1[j-1] == s2[i-1]:
d = 0
else:
d = 1
table[i][j] = min(table[i-1][j-1] + d,
table[i-1][j]+1,
table[i][j-1]+1)
return table[len2][len1]
|
a4d5abead572ab81ec886fb1853977d505def2cf | lowones/tic-tac-toe | /ttt.py | 2,526 | 3.71875 | 4 | #!/usr/bin/python
from itertools import cycle
from time import sleep
from os import system
import os
win_lines = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'],
['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9'],
['1', '5', '9'], ['3', '5', '7']]
def main():
print "main"
lst = ["X", "O"]
players = cycle(lst)
board = create_board()
winner = False
while not winner:
player = next(players)
announce = "say player, " + player
system(announce)
get_move(player, board)
winner = check_win(board)
print(player)
system(announce)
print
quit()
def check_win(board):
for win in win_lines:
if check_board_win(win, board):
return True
def check_board_win(win, board):
if board[win[0]] == board[win[1]] == board[win[2]]:
os.system('clear')
print_board(board)
print("WINNER!!!")
system('say we have a winner winner winner')
return True
else:
return False
def print_board(board):
print
print(" %s | %s | %s" % (board['1'], board['2'], board['3']))
print("-------------")
print(" %s | %s | %s" % (board['4'], board['5'], board['6']))
print("-------------")
print(" %s | %s | %s" % (board['7'], board['8'], board['9']))
print
'''
1234567890123
1 | 2 | 3
-------------
4 | 5 | 6
-------------
7 | 8 | 9
'''
def get_move(player, board):
available_spaces = get_empty_spaces(board)
if len(available_spaces) == 0:
os.system('clear')
print_board(board)
print("WINNER CAT!!!\n\nLet's Try Again...\n")
sleep(5)
main()
move = get_selection(player, available_spaces, board)
board[move] = player
def get_selection(player, choices, board):
print("get selection")
choices.sort()
valid_selection = None
warning=''
while valid_selection is None:
os.system('clear')
print_board(board)
print(warning)
selection = raw_input("Player %s choose an available space:\n %s : " % (player, choices))
if selection in choices:
return selection
else:
warning = 'TRY AGAIN!!!'
def get_empty_spaces(board):
empty_spaces = []
for key, value in board.iteritems():
if int(key) == value:
empty_spaces.append(key)
return empty_spaces
def create_board():
# create dict board
board = { '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9}
# board = { '1' : 'X', '2' : 'X', '3' : 'X', '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9}
return board
if __name__ == "__main__":
main()
|
5092b990cd26299f3b4b0512286ee47c935de43c | JeroenVerstraelen/GegevensAbstractie | /Main (python code)/redblack_tree.py | 13,191 | 3.734375 | 4 | class Redblacktree:
'''
class for the red-black tree
'''
class redblacknode:
'''
class for the node of a red-black tree
'''
def __init__(self,key):
self.key = key
self.red = False #self.red holds the color of the connectino between the node and it's parent, and is initialized as black
self.leftchild = None
self.rightchild = None
self.parent = None
def __str__(self): #returns a string representation for a node
return str(self.key)
def __repr__(self):
return str(self.key)
def create(self, key): #initializes a node
self.__init__(key)
def destroy(self): #destroys the node
del(self)
def isLeaf(self): #returns True if the node is a leaf, otherwise returns False
if self.rightchild == None and self.leftchild == None:
return True
else:
return False
def getParent(self): #returns the parent of the node
return self.parent
def getRightChild(self): #returns the right child of the node
return self.rightchild
def getLeftChild(self): #returns the left child of the node
return self.leftchild
def preOrderTraversal(self, node=None): #traverses and prints the tree in preorder
ret_list = []
if None != node.key and node != None:
ret_list.append(node.key)
if node.leftchild != None:
ret_list.extend(node.leftchild.postOrderTraversal(node.leftchild))
if node.rightchild != None:
ret_list.extend(node.rightchild.postOrderTraversal(node.rightchild))
return ret_list
def postOrderTraversal(self, node=None): #traverses and prints the tree in postorder
ret_list = []
if node.leftchild != None:
ret_list.extend(node.leftchild.postOrderTraversal(node.leftchild))
if node.rightchild != None:
ret_list.extend(node.rightchild.postOrderTraversal(node.rightchild))
if None != node.key and node != None:
ret_list.append(node.key)
return ret_list
def inOrderTraversal(self, node=None): #traverses and prints the tree in inorder
ret_list = []
if node.leftchild != None:
ret_list.extend(node.leftchild.inOrderTraversal(node.leftchild))
if None != node.key and node != None:
ret_list.append(node.key)
if node.rightchild != None:
ret_list.extend(node.rightchild.inOrderTraversal(node.rightchild))
return ret_list
def __init__(self):
self.dummy = Redblacktree.redblacknode(None)#dummy node
self.root = self.dummy #upon initialisation of a tree, the dummy serves as the root
def search(self,key,node=None):
'''
searches for a searchkey in the tree and returns the item if it's included in the tree, otherwise returns None
can be called with a node to search only the subtrees of that node
if no node is entered the default node is the root of the tree
'''
if None == node:
node = self.root
while node != self.dummy and key != node.key: #search until the end of the tree or until the key is found
if key < node.key:
node = node.leftchild
else:
node = node.rightchild
if node.key == key: return node.key #only return the item if the keys match
else: return None
def searchInternal(self,key,node=None):
''' Slightly modified search function for internal use. returns
node instead of key '''
if None == node:
node = self.root
while node != self.dummy and key != node.key: #search until the end of the tree or until the key is found
if key < node.key:
node = node.leftchild
else:
node = node.rightchild
if node.key == key: return node #only return the item if the keys match
else: return None
def insert(self,key,item):
'''
inserts an item in the tree and restores the properties of a red-black tree after
'''
the_node = Redblacktree.redblacknode(key) #initialize a node with the entered key
helpingnode = self.dummy
node = self.root
while node != self.dummy: #search for the node's place in the tree
helpingnode = node #helpingnode tracks the last visited node
if the_node.key < node.key:
node = node.leftchild
else:
node = node.rightchild
the_node.parent = helpingnode #the last visited node becomes the new node's parent
if helpingnode == self.dummy: #if the tree holds no nodes, the new node becomes the root
self.root = the_node
elif the_node.key < helpingnode.key: #otherwise, find out if the new node is the parents' left or right child
helpingnode.leftchild = the_node
elif the_node.key > helpingnode.key:
helpingnode.rightchild = the_node
elif the_node.key == helpingnode.key: # If a node with the same searchkey exists.
return False
the_node.leftchild = self.dummy #the new node becomes a leaf
the_node.rightchild = self.dummy
the_node.red = True #the new connection is initialized as red for convenience in the restoreproperties procedure
self.restoreproperties(the_node)
return True
def delete(self,key):
'''
deletes a node from the tree
if the entered key doesn't exist in the red-black tree, returns an error
'''
the_node = self.searchInternal(key) #search for the node that matches the key
if the_node == None: #error if the node doesn't exist
print("error: the node to delete doesn't exist")
return
helpingnode = self.dummy
node = the_node
if node.rightchild == self.dummy:#if the node does not have an inOrder succesor it can easily be deleted by connecting the left child to the parent, if the node doesn't have a left child self.dummy will be linked, so there are no special cases for this
if node == node.parent.rightchild: #find out if the node is its' parent's left or right child, link the left child, and delete the node
node.parent.rightchild = node.leftchild
del(the_node)
elif node == node.parent.leftchild:
node.parent.leftchild = node.leftchild
del(the_node)
else:
while node.rightchild != self.dummy: #if the node has an inOrder succesor, find it
node = node.rightchild
if node == node.parent.rightchild: #find out if the succesor is its' parent's left or right child and link the left child
node.parent.rightchild = node.leftchild
elif node == node.parent.leftchild:
node.parent.leftchild = node.leftchild
if the_node == the_node.parent.rightchild:#replace the_node with it's successor in the parent
the_node.parent.rightchild = node
elif the_node == the_node.parent.leftchild:
the_node.parent.leftchild = node
node.leftchild = the_node.leftchild #replace the_node with it's successor
node.rightchild = the_node.rightchild
node.parent = the_node.parent
self.restoreproperties(the_node)
del(the_node) #destroy the_node
def restoreproperties(self,the_node):
'''
restores the properties of a red-black tree through rotations
'''
while the_node.parent.red: #if the parent's connection is red, changes should be made.
if the_node.parent == the_node.parent.parent.leftchild: #find out what side of the parent's parent the parent is linked to.*
helpingnode = the_node.parent.parent.rightchild
if helpingnode.red: #if this connection is also red, execute the appropriate changes in the connections**
the_node.parent.red = False
helpingnode.red = False
the_node.parent.parent.red = True
the_node = the_node.parent.parent
else: #if this connection is not red, a rotation should be executed***
if the_node == the_node.parent.rightchild:
the_node = the_node.parent
self.left_rotate(the_node.parent.parent)
the_node.parent.red = False
the_node.parent.parent.red = True
self.right_rotate(the_node.parent.parent)
else: #*
helpingnode = the_node.parent.parent.leftchild
if helpingnode.red: #**
the_node.parent.red = False
helpingnode.red = False
the_node.parent.parent.red = True
the_node = the_node.parent.parent
else: #***
if the_node == the_node.parent.leftchild:
the_node = the_node.parent
self.right_rotate(the_node)
the_node.parent.red = False
the_node.parent.parent.red = True
self.left_rotate(the_node.parent.parent)
self.root.red = False
def left_rotate(self, the_node):
'''
subprocedure for restoreproperties
'''
helpingnode = the_node.rightchild
the_node.rightchild = helpingnode.leftchild
if helpingnode.leftchild != self.dummy and helpingnode.leftchild != None:
helpingnode.leftchild.parent = the_node
helpingnode.parent = the_node.parent
if the_node.parent == self.dummy:
self.root = helpingnode
elif the_node == the_node.parent.leftchild:
the_node.parent.leftchild = helpingnode
else:
the_node.parent.rightchild = helpingnode
helpingnode.leftchild = the_node
the_node.parent = helpingnode
def right_rotate(self, the_node):
'''
subprocedure for restoreproperties
'''
helpingnode = the_node.leftchild
the_node.leftchild = helpingnode.rightchild
if helpingnode.rightchild != self.dummy:
helpingnode.rightchild.parent = the_node
helpingnode.parent = the_node.parent
if the_node.parent == self.dummy:
self.root = helpingnode
elif the_node == the_node.parent.rightchild:
the_node.parent.rightchild = helpingnode
else:
the_node.parent.leftchild = helpingnode
helpingnode.rightchild = the_node
the_node.parent = helpingnode
def createTree(self): #creates a red-black tree
pass
def destroyTree(self): #destroys the tree
del(self)
def getLength(self):
list = self.inOrderTraversal()
length = len(list)
if length == 1:
if list[0] == None:
return 0
return length
def isEmpty(self):
if self.getLength() == 0:
return True
return False
def preOrderTraversal(self, node=None): #traverses and prints the tree in preorder
ret_list = []
if None == node:
node = self.root
ret_list.append(node.key)
if node.leftchild != None:
ret_list.extend(node.leftchild.preOrderTraversal(node.leftchild))
if node.rightchild != None:
ret_list.extend(node.rightchild.preOrderTraversal(node.rightchild))
return ret_list
def postOrderTraversal(self, node=None): #traverses and prints the tree in postorder
ret_list = []
if None == node:
node = self.root
if node.leftchild != None:
ret_list.extend(node.leftchild.postOrderTraversal(node.leftchild))
if node.rightchild != None:
ret_list.extend(node.rightchild.postOrderTraversal(node.rightchild))
ret_list.append(node.key)
return ret_list
def inOrderTraversal(self, node=None): #traverses and prints the tree in inorder
ret_list = []
if None == node:
node = self.root
if node.leftchild != None:
ret_list.extend(node.leftchild.inOrderTraversal(node.leftchild))
ret_list.append(node.key)
if node.rightchild != None:
ret_list.extend(node.rightchild.inOrderTraversal(node.rightchild))
return ret_list
|
7a35a92ef2887f22f265c0821c03c426c38c70eb | goalong/lc | /v2/140.py | 1,075 | 3.578125 | 4 | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
# 7 star, 比较难,这道题立即想到用dfs,结果超时了,而且用dfs还有两处细节需要注意,一个是dfs中for循环的范围,一个是递归调用时path的赋值应该直接在调用中进行,如果单独写一行path.append(s[:i]),就是错误,因为list的可变性
# result = []
# path = []
# memo = {}
# self.dfs(s, set(wordDict), path, result, memo)
# return result
# def dfs(self, s, word_set, path, result, memo):
# if s in memo:
# return memo[s]
# if s == "":
# sentence = " ".join(path)
# result.append(sentence)
# return
# for i in range(1, len(s)+1):
# if s[:i] in word_set:
# self.dfs(s[i:], word_set, path + [s[:i]], result, memo)
print(Solution().wordBreak("catsanddog",
["cat","cats","and","sand","dog"])) |
3ba9d804227913904d5515d7b7f91fb904357fe2 | LArchCS/Data-Science-and-Computational-Thinking-Using-Python | /Chapter1/fibo.py | 504 | 3.84375 | 4 | def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
def fib3(n):
a=0
b=1
while n>0:
a,b=b,a+b
n-=1
return b
def fib4(n):
if n == 0 or n ==1:
return 1
else:
return fib4(n-2) + fib4(n-1) |
a5f9e2aab9def077b22d233bbd19bb716fdc2fdc | cheeseaddict/think-python | /chapter-6/exercise-6.8.py | 196 | 3.703125 | 4 | def gcd(a, b):
if a == b:
return a
elif a > b:
return gcd(a-b, b)
elif b > a:
return gcd(a, b-a)
print(gcd(84, 132))
print(gcd(246, 642))
print(gcd(41, 107))
|
fc9cd04d4f696eefadd5a468f15c3ee4f02cfbaa | KarlJJonsson/NumberGuesser | /GuessTheNumber/GuessingGame.py | 1,636 | 4.0625 | 4 | from GameLogic import GameLogic
"""Simple game where the user has to guess a generated number, while getting clues in form of equations for given number.
Takes max_tries (integer) as an argument. No argument when instantiating the object sets a default max_tries = 5.
After instantiation, use the start method to start the game.
input other than an integer will crash the game.
"""
class GuessingGame:
def __init__(self, max_tries=5):
self.logic = GameLogic(max_tries)
def start(self):
print(f"Welcome to NumGuesser!\n You have {self.logic.max_tries} tries to guess the right number between 1-1000.\n Do you want a starting clue?\nYes(Y), No(N)> ")
choice = input()
if(choice.lower() == "y"):
print(self.logic.clue())
elif(choice.lower() == "n"):
print("No clue it is. Lets roll!")
else:
print("That's not a command, no clue for you. Lets roll!")
running = True
while running:
print("Make your guess> ")
guess = input()
if(self.logic.make_guess(guess)):
running = False
print("Correct answer!")
else:
tries_left = self.logic.tries_left()
if(tries_left == 0):
print(f"You're out of tries, game over! Correct Answer was {self.logic.answer}")
running = False
else:
print(f"That's not quite it, You have {tries_left} tries left. here's a new clue!")
print(self.logic.clue()) |
5ceed54e8368ea285bbcf0edb09d864abee2567d | SimeonTsekov/TP | /Files/Python_codes/lesson4-OOP1/class4.py | 604 | 3.65625 | 4 | class BookStore:
def __init__(self, title, author):
self.title = title
self.author = author
self.__privateMember = "private";
def bookInfo(self):
print("Book title:", self.title)
print("Book author:", self.author,"\n")
print("Private Member inside:", self.__privateMember,"\n")
# Create a virtual book store
b1 = BookStore("Great Expectations", "Charles Dickens")
# call member functions for each object
b1.bookInfo()
print("public member outside:", b1.author,"\n")
print("private member outside:", b1.__privateMember,"\n") |
e1a12174204cbcb6946d030a2daf5e45237f13d1 | AlanCFleming/SimulationProject3 | /scripts/pendulum.py | 2,607 | 3.734375 | 4 | import math
import matplotlib.pyplot as plt
import dynamics
class Pendulum(dynamics.Dynamics):
def __init__(self, pendulum_length, time_step):
numEquations = 2 # set the number of state equations
# set constants, if any
self.gOverL = 9.802 / pendulum_length
super().__init__(numEquations, time_step) # initialize super class dynamics (Euler Method)
# create variables to hold the state history for plotting
self.Q = [[] for i in range(numEquations)]
self.T = []
def initialize(self, angle, speed):
# set state variable initial values
self.q[0] = angle
self.q[1] = speed
# initialize state history used for plotting
self.Q = [[self.q[i]] for i in range(len(self.q))]
self.T = [0.0]
def advance(self, count):
# compute "count" updates of the state equations
for i in range(count):
self.dq[0] = self.q[1]
self.dq[1] = -self.gOverL * math.sin(self.q[0])
self.step()
# save the updated state variables after the "count" updates for plotting
[self.Q[i].append(self.q[i]) for i in range(len(self.q))]
self.T.append(self.now())
def print(self):
# custom print for current simulation
print('time={0:10f} speed={1:10f} angle={2:10f}'.format(self.time, self.q[1], self.q[0]))
def plot(self):
# custom plot for current simulation
plt.figure()
plt.subplot(211)
plt.plot(self.T, self.Q[0], 'k')
plt.ylabel('angle')
plt.subplot(212)
plt.plot(self.T, self.Q[1], 'r')
plt.ylabel('speed')
plt.xlabel('time')
plt.show()
# set parameters for pendulum simulation
# parameters describing the simulation time
endTime = 5.0 # length of simulation (i.e. end time)
dt = 0.0001 # time step size used to update state equations
# parameters describing the real system
length = 1.0 # pendulum length
initial_angle = 2.0 # initial pendulum angle
initial_speed = 0.0 # initial pendulum speed
# create the simulation and initialize state variables
P = Pendulum(length, dt)
P.initialize(initial_angle, initial_speed)
# run the simulation
displayInterval = 250 # number of state updates before saving state
while P.now() < endTime:
P.advance(displayInterval)
P.print() # call print to see numeric values
P.plot() # call custom plot
|
ec2327acb81e546fa1915bc075d8c417e0f79d64 | CyrilHub/GA---GIT | /Class-Notes/L6 - Class/Class Notes 010919.py | 284 | 3.96875 | 4 | class Car:
def __init __(self, size, color):
self.size = size
self.color = color
def print_size(self):
print ("The size is:")
print (self.size)
print ("the color is:")
print (self.color)
ford = Car(1):
ford.print_color_size
|
e19b09829ad8f77b478ff00eafd158cbd2ae006b | Mianmian028/python-study | /python/0307message_233.py | 223 | 3.546875 | 4 | #coding:utf-8
message ='you are ugly.'
message1 ="it is true."
print(message.title())
print(message.upper())
full_message =message +""+message1
print(full_message)
full_message1='hello!'+""+full_message
print(full_message1) |
c65bd44300e2016132e433dc7d5045819c594382 | JMaling/Final_Project | /input_functions.py | 1,257 | 3.5625 | 4 |
def get_good_list(positive_word_list, twitter_list):
'''
:param positive_word_list: uci list of good words or bad words
:param word_list6: twitter feed list of words
:return: list of good or bad words found in twitter words
'''
total = 0
words = []
for word in twitter_list:
if word in positive_word_list:
total += 1
words.append(word)
return words
def percentages(good_words, bad_words):
good = len(good_words)
bad = len(bad_words)
positive_percentage = ((good)/(good + bad)) * 100
negative_percentage = 100 - positive_percentage
return negative_percentage, positive_percentage
def frequent_words(my_list):
repeats = [[word, my_list.count(word)] for word in my_list]
print(repeats)
repeats.sort(key=lambda x: x[1])
print(repeats)
repeats = dict(repeats)
print(repeats)
new_repeats = []
for key, value in repeats.items():
new_repeats.append([key, value])
new_repeats = [x[0] for x in new_repeats if len(x[0]) > 3]
new_repeats = new_repeats[-3:]
print(new_repeats)
return new_repeats, repeats
if __name__ == "__main__":
frequent_words(["j", "j", "j", "d", "d", "m", "m", "m", "z", "z", "z"])
|
80f6a51c5e033834c5afdabc4c1c8b7342399b21 | arihant-2310/Python-Programs | /sort without sort function.py | 292 | 3.59375 | 4 | n= input('enter how many numbers:-')
l= []
for i in range(n):
e= input('enter elements-')
l.append(e)
for i in range(n):
for j in range(n-1-i):
if l[j]>l[j+1]:
t= l[j]
l[j]= l[j+1]
l[j+1]= t
print'sorted list is:-'
print l
|
a5c27ef09b29297aff35191f06e91b211d6ae54e | thehawkgriffith/BlackJack-by-Shahbaz-Khan | /Blackjack.py | 6,449 | 3.875 | 4 | from random import shuffle
print("Welcome to the game of BlackJack by Shahbaz Khan!")
class Hand():
def __init__(self):
self.cards_in_hand = []
def addCard(self, card):
self.cards_in_hand.append(card)
class Deck():
def __init__(self):
self.cards = ['A', 'J', 'K', 'Q', 10, 9, 8, 7, 6, 5, 4, 3, 2, 'A', 'J', 'K', 'Q', 10, 9, 8, 7, 6, 5, 4, 3, 2, 'A', 'J', 'K', 'Q', 10, 9, 8, 7, 6, 5, 4, 3, 2, 'A', 'J', 'K', 'Q', 10, 9, 8, 7, 6, 5, 4, 3, 2]
def shuffle(self):
shuffle(self.cards)
class Account():
def __init__(self, name):
self.balance = 30000
self.name = name
self.bet = 0
def displayBalance(self):
print(f'Hey {self.name}, your remaining balance is $' + self.balance)
def betAmount(self, bet):
self.bet = int(bet) + self.bet
if (self.bet > self.balance):
for check in range(15):
print(f'Sorry, that bet exceeds your current balance which is ${self.balance}, try again.')
print('Enter an acceptable bet amount: ')
self.bet = int(input())
if (self.bet > self.balance):
break
else:
print('Sorry, try again.')
continue
class Players(Hand, Account):
def __init__(self, name):
self.name = name
Hand.__init__(self)
Account.__init__(self,self.name)
self.score = 0
def scoreCheck(self):
self.score = 0
for i in range(0, len(self.cards_in_hand)):
if self.cards_in_hand[i] == 10:
self.score = self.score + 10
elif self.cards_in_hand[i] == 9:
self.score = self.score + 9
elif self.cards_in_hand[i] == 8:
self.score = self.score + 8
elif self.cards_in_hand[i] == 7:
self.score = self.score + 7
elif self.cards_in_hand[i] == 6:
self.score = self.score + 6
elif self.cards_in_hand[i] == 5:
self.score = self.score + 5
elif self.cards_in_hand[i] == 4:
self.score = self.score + 4
elif self.cards_in_hand[i] == 3:
self.score = self.score + 3
elif self.cards_in_hand[i] == 2:
self.score = self.score + 2
elif self.cards_in_hand[i] == 'K':
self.score = self.score + 10
elif self.cards_in_hand[i] == 'Q':
self.score = self.score + 10
elif self.cards_in_hand[i] == 'J':
self.score = self.score + 10
elif self.cards_in_hand[i] == 'A':
if self.score + 11 <= 21:
self.score = self.score + 11
else:
self.score = self.score + 1
return self.score
def victory(self):
self.balance = self.balance + self.bet
print(f'Congratulations {self.name}! You have won ${self.bet}, your new balance is ${self.balance}.')
def loss(self):
self.balance = self.balance - self.bet
print(f'Uh-oh! {self.name}, you have lost ${self.bet}, your new balance is ${self.balance}.')
def showHand(self):
print(f'Current cards with {self.name} are: \n\n')
for card in self.cards_in_hand:
print('\n' + str(card) + '\t')
def showHandComputer(self):
print('Current cards with Computer are: \n\n')
print(str(self.cards_in_hand[0]) + '\t' + '[]')
def checkEligibilityPlayer(self):
self.scoreCheck()
if self.score > 21:
computer.showHand()
contestant.showHand()
print('YOU BUST!')
contestant.loss()
print('Want to play another hand? Y/N')
choice = input()
if choice == 'Y':
reset()
main()
else:
exit()
def checkEligibilityComputer(self):
self.scoreCheck()
if self.score > 21:
computer.showHand()
contestant.showHand()
print('YOU WIN!')
contestant.victory()
print('Want to play another hand? Y/N')
choice = input()
if choice == 'Y':
reset()
main()
else:
exit()
def victoryCheck():
if ((21 - computer.scoreCheck()) < (21- contestant.scoreCheck())):
computer.showHand()
contestant.showHand()
print("Computer won this round!")
contestant.loss()
elif ((21 - computer.scoreCheck()) == (21 - contestant.scoreCheck())):
print("No one won this round!")
computer.showHand()
contestant.showHand()
else:
print('Congratulations on winning this round.')
computer.showHand()
contestant.showHand()
contestant.victory()
def reset():
computer.score = 0
contestant.score = 0
computer.cards_in_hand = []
contestant.cards_in_hand = []
playdeck.cards = ['A', 'J', 'K', 'Q', 10, 9, 8, 7, 6, 5, 4, 3, 2, 'A', 'J', 'K', 'Q', 10, 9, 8, 7, 6, 5, 4, 3, 2, 'A', 'J', 'K', 'Q', 10, 9, 8, 7, 6, 5, 4, 3, 2, 'A', 'J', 'K', 'Q', 10, 9, 8, 7, 6, 5, 4, 3, 2]
contestant.bet = 0
playdeck = Deck()
print("Please enter your name: ")
name = input()
contestant = Players(name)
computer = Players('Computer')
print("Let's Play!")
def main():
playdeck.shuffle()
card = playdeck.cards[0]
computer.addCard(card)
playdeck.cards.pop(0)
card = playdeck.cards[0]
computer.addCard(card)
playdeck.cards.pop(0)
computer.showHandComputer()
card = playdeck.cards[0]
contestant.addCard(card)
playdeck.cards.pop(0)
card = playdeck.cards[0]
contestant.addCard(card)
playdeck.cards.pop(0)
contestant.showHand()
print("Would you like to Hit or Stay? H/S")
choice = input()
while choice == 'H':
print('Please place your bet: ')
bet = input()
contestant.betAmount(bet)
card = playdeck.cards[0]
contestant.addCard(card)
playdeck.cards.pop(0)
contestant.showHand()
contestant.checkEligibilityPlayer()
print("Would you like to Hit or Stay? H/S")
choice = input()
for play2 in range(10):
computer.showHand()
computer.checkEligibilityComputer()
if computer.scoreCheck() >= 17:
break
else:
card = playdeck.cards[0]
computer.addCard(card)
playdeck.cards.pop(0)
computer.checkEligibilityComputer()
victoryCheck()
print('Would you like to play another hand? Y/N')
choice2 = input()
if choice2 == 'Y':
reset()
main()
else:
exit()
if __name__ == '__main__':
main()
|
3a450fa853b4c5801162d148a5cacfdba1805cfe | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 06 (stacks_queues_deques)/reverse_file_using_stack.py | 509 | 3.71875 | 4 | from stack_class import *
def reverse_file(path):
"""Overwrite given file using its context line-by-line reversed"""
s=ArrayStack()
with open(path,"r") as original:
for line in original:
s.push(line.rstrip("\n")) # removing newline characters
# overwrite the contents in LIFO order
with open(path,"w") as new:
while not s.is_empty():
new.write(s.pop()+"\n") # re-insert newline characters.
return "Reversed"
print(reverse_file("sample.txt"))
|
b9fd3f47fb6f8c78d7d6ffacf7657897ed140e4d | shahad02/final-project | /final edge project (reserving a table).py | 1,483 | 4.09375 | 4 | class restaurant:
setmenu=["Chines","American", "Italian" , "Indain", "Thai"]
def welcome():
print("WELCOME TO THE 5 STAR international RESTAURANT!!")
print("here you can reseve your table to have a wonderful meal")
welcome()
def __init__(self):
self.output=""
def place(where):
if where == "city" or "sea":
print("great choice")
else:
print("please try again")
where=input("please choose your table for tonight (city / sea) view")
place(where)
def time(when):
if 12>when>1:
print("good timming")
else:
print("Unforunately we are closed")
when= int(input("When you are planning to visit our restaurant?(1pm to 12am)"))
time(when)
def cuisine(fav):
if fav == "y":
type=input("choose your wishing for cuisine for tonight from the list")
print("Get ready to have an unforgettable meals")
else:
setmenu=["Chines","American", "Italian" , "Indain", "Thai"]
xxx=input("Please write your fav cuisine and we will do our best to prepare it for you if possible")
setmenu.append(xxx)
print(setmenu)
print("Get ready to have an unforgettable meals")
print("setmenu=[Chines,American, Italian , Indain, Thai]")
fav=input("Is your fav cuisine on the list? Yes= y No=n")
cuisine(fav)
def end():
print("This is the end of the reserving systme. I wish you a great experience")
end()
|
d3797f35e69009ca0237aafc2e024641acc741ca | KqSMea8/Learning_Workspace | /Learning_Opencv_python/day5_padding.py | 1,163 | 3.53125 | 4 | '''
cv2.copyMakeBorder()用来给图片添加边框,它有下面几个参数:
src:要处理的原图
top, bottom, left, right:上下左右要扩展的像素数
borderType:边框类型,这个就是需要关注的填充方式
其中填充方式有 默认方式和固定值方式最常用
'''
# 固定值填充
'''
cv2.BORDER_CONSTANT这种方式就是边框都填充成一个固定的值,比如下面的程序都填充0:
'''
import cv2
import numpy as np
img = cv2.imread("/home/sanjay/Workspace/learning/Learning_Opencv_python/lena.jpg")
# print(img)
# 固定值边框,统一都填充为0也成为zero padding
cons = cv2.copyMakeBorder(img, 1, 1,1,1, cv2.BORDER_CONSTANT, value=0)
# print(cons)
np_img = np.random.randn(3,3)
# print(np_img)
# 默认边框 cv2.BORDER_DEFAULT其实是取镜像堆成的像素填充
default = cv2.copyMakeBorder(np_img, 1,1,1,1, cv2.BORDER_DEFAULT)
# print(default)
# opencv进行卷积
# 用cv2.filter2D()实现卷积操作
#定义卷积核
kernel = np.ones((3,3), np.float32) / 10
# 卷积操作, -1表示通道数与原图相同
dst = cv2.filter2D(img, -1, kernel)
cv2.imshow('conv', dst)
cv2.waitKey(0) |
8f9cb889a07147e9bbbbffce7dc0e2b3ae2b3ab8 | layshidani/learning-python | /lista-de-exercicios/Curso_IntroCiênciadaCompPythonParte 1_Coursera/SEMANA_4/S4OP2-digito-repetido.py | 468 | 4 | 4 | print('-=-' * 15)
print('Digito adjacente igual'.center(15, '-'))
print('-=-' * 15)
n = int(input('Insira um número inteiro: '))
print('\nO número', n, 'possui dígitos adjacentes iguais?')
n_anterior = n % 10
n = n // 10
igual = False
i = 0
while n > 0 and not igual:
n_atual = n % 10
if n_atual == n_anterior:
igual = True
else:
i += 1
n_anterior = n_atual
n = n // 10
if igual:
print('sim')
else:
print('não')
|
7706eb0fbf5c2f19a9d5566641f8c660498ef5cf | lixiang2017/leetcode | /problems/0540.0_Single_Element_in_a_Sorted_Array.py | 4,475 | 3.765625 | 4 | '''
xor
Runtime: 64 ms, faster than 92.68% of Python3 online submissions for Single Element in a Sorted Array.
Memory Usage: 16.5 MB, less than 39.56% of Python3 online submissions for Single Element in a Sorted Array.
'''
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
return reduce(operator.xor, nums)
'''
xor
Runtime: 56 ms, faster than 99.48% of Python3 online submissions for Single Element in a Sorted Array.
Memory Usage: 16.4 MB, less than 39.56% of Python3 online submissions for Single Element in a Sorted Array.
'''
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
ans = 0
for x in nums:
ans ^= x
return ans
'''
Binary Search
Runtime: 122 ms, faster than 8.47% of Python3 online submissions for Single Element in a Sorted Array.
Memory Usage: 16.5 MB, less than 6.68% of Python3 online submissions for Single Element in a Sorted Array.
'''
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
l, r = 0, len(nums) - 1
N = len(nums)
while l < r:
mid = (l + r) // 2
# exactly mid
if (mid - 1 >= 0 and nums[mid] != nums[mid - 1]) and (mid + 1 < N and nums[mid] != nums[mid + 1]):
return nums[mid]
if (mid % 2 == 0 and mid + 1 < N and nums[mid] == nums[mid + 1]):
l = mid + 2
if (mid % 2 == 1 and mid - 1 >= 0 and nums[mid] == nums[mid - 1]):
l = mid + 1
if (mid % 2 == 1 and mid + 1 < N and nums[mid] == nums[mid + 1]):
r = mid - 1
if (mid % 2 == 0 and mid - 1 >= 0 and nums[mid] == nums[mid - 1]):
r = mid - 2
return nums[l]
'''
[1,1,2,3,3,4,4,8,8]
[3,3,7,7,10,11,11]
[1]
[1,1,2,3,3]
'''
'''
Binary Search
Runtime: 72 ms, faster than 56.14% of Python3 online submissions for Single Element in a Sorted Array.
Memory Usage: 16.5 MB, less than 39.56% of Python3 online submissions for Single Element in a Sorted Array.
'''
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) // 2
if (mid % 2 == 1 and nums[mid] == nums[mid - 1]) or (mid % 2 == 0 and nums[mid] == nums[mid + 1]):
l = mid + 1
else:
r = mid
return nums[l]
'''
Binary Search
Runtime: 79 ms, faster than 26.20% of Python3 online submissions for Single Element in a Sorted Array.
Memory Usage: 16.3 MB, less than 75.51% of Python3 online submissions for Single Element in a Sorted Array.
'''
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) // 2
if mid % 2:
mid -= 1
if nums[mid] == nums[mid + 1]:
l = mid + 2
else:
r = mid
return nums[l]
'''
binary search
Runtime: 182 ms, faster than 55.03% of Python3 online submissions for Single Element in a Sorted Array.
Memory Usage: 23.8 MB, less than 14.27% of Python3 online submissions for Single Element in a Sorted Array.
'''
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
n = len(nums)
l, r = 0, n - 1
while l <= r:
mid = (l + r) // 2
if mid & 1:
mid -= 1
if mid + 1 < n and nums[mid] == nums[mid + 1]:
l = mid + 2
elif mid - 1 >= 0 and nums[mid - 1] == nums[mid]:
r = mid - 2
else:
return nums[mid]
return nums[l]
'''
return nums[r]
Runtime: 179 ms, faster than 66.70% of Python3 online submissions for Single Element in a Sorted Array.
Memory Usage: 23.8 MB, less than 39.30% of Python3 online submissions for Single Element in a Sorted Array.
'''
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
n = len(nums)
l, r = 0, n - 1
while l <= r:
mid = (l + r) // 2
if mid & 1:
mid -= 1
if mid + 1 < n and nums[mid] == nums[mid + 1]:
l = mid + 2
elif mid - 1 >= 0 and nums[mid - 1] == nums[mid]:
r = mid - 2
else:
return nums[mid]
return nums[r]
|
91d548e43f21dcd5301be65e89d5a7cae41aa39f | lvsdian/python | /clazz/02-闭包.py | 363 | 3.71875 | 4 | def outer():
x = 10 # 在外部函数里定义了一个变量x,是一个局部变量
def inner():
# 在内部函数如何修改外部函数的局部变量
nonlocal x # 用nonlocal,此时,这里的x就是外部函数的局部变量x
y = x + 1
print("inner里的y = ", y)
return inner
# inner里的y = 11
outer()() |
b30036dd55cf3e208996b1892a2d72a9fcd03335 | ZackSungy/Python | /StupidToLearnPython(BookName)/ex6.py | 378 | 3.71875 | 4 | x="There are %d type of people."%10;
binary="binary";
do_not="dont't";
y="Those who know %s and those who %s."%(binary,do_not);
print x;
print y;
print "I said:%r."%x;
print "I also said:'%s'."%y;
hilarious=False;
joke_evaluation="Isn't that joke so funny?!%r";
print joke_evaluation%hilarious;
w="This is the left side of...";
e="a string with a right side.";
print w+e;
|
408a0e0f285a66da35c0125f054edb9b6e124351 | nikhiilll/Algorithms-using-Python | /Medium-AE/RemoveKthNodeFromEnd.py | 671 | 3.828125 | 4 | class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def removeKthNodeFromEnd(head, k):
noOfNodes = 0
node = head
while node is not None:
noOfNodes += 1
node = node.next
nodePosToRemove = noOfNodes - k
if nodePosToRemove == 0:
head.value = head.next.value
head.next = head.next.next
return
else:
previousNode = None
currentNode = head
while nodePosToRemove != 0:
previousNode = currentNode
currentNode = currentNode.next
nodePosToRemove -= 1
previousNode.next = currentNode.next
|
6535e97a83003cd8fab1814f99f6af2abc7fbeb2 | sakshisangwan/Python-101 | /Problem Set /Pattern2.py | 93 | 3.640625 | 4 | k = 1
for i in range (1, 6, +1):
for j in range( , i+1, +2):
print (k),
k+=1
print("") |
f076687e233c6d298e4b5df84b25d0ae337c2086 | JohnSchlerf/Sternberg | /sternberg.py | 8,465 | 3.53125 | 4 | #!/usr/bin/python
from helperfunctions import *
from random import shuffle, choice
from Tkinter import *
import copy
WIDTH = -1
HEIGHT = -1
FONTSIZE = 36
yesKey = 'f'
noKey = 'j'
encode_color = "green"
probe_color = "white"
encode_time = 2
probe_timeout = 2
set_size = [4,6]
number_of_sets = 20
probes_per_set = 6
min_delay = 0.6
max_delay = 1.4
set_items = ['B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Z']
# Having vowels makes this a bit easier, because you can make words:
#set_items = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
def chooseSet(size):
shuffle(set_items)
theSet = []
distractorSet = []
for item in range(size):
theSet.append(set_items[item])
distractorSet.append(set_items[item+size])
return theSet,distractorSet
def setString(set):
myString = " "
for item in set:
myString+=item
myString+=" "
return myString
def GridLabel(Parent,Text,Row,Column):
"""
This is a helper function which adds a label to a grid.
This is normally a couple of lines, so multiple labels
gets a little cumbersome...
"""
L = Label(Parent,text=Text)
L.grid(row=Row,column=Column)
return L
def GridEntry(Parent,DefaultText,Row,Column):
"""
This is a helper function which adds an Entry widget
to a grid. Also sets default text.
"""
E = Entry(Parent)
E.insert(0,DefaultText)
E.grid(row=Row,column=Column)
return E
class sternbergGUI():
def __init__(self):
self.AllData = DataDict()
self.win = Tk()
self.win.update()
nextRow = 0
self.BlockNumber = 1
GridLabel(self.win,"Current Block:",nextRow,0)
GridLabel(self.win,str(self.BlockNumber),0,1)
nextRow+=1
GridLabel(self.win,"Yes Key",nextRow,0)
self.__yesKeyEntry = GridEntry(self.win,yesKey,nextRow,1)
nextRow+=1
GridLabel(self.win,"No Key",nextRow,0)
self.__noKeyEntry = GridEntry(self.win,noKey,nextRow,1)
nextRow+=1
GridLabel(self.win,"",nextRow,0)
nextRow+=1
GridLabel(self.win,"Set Lengths",nextRow,0)
self.__setSizeEntry = GridEntry(self.win,str(set_size),nextRow,1)
nextRow+=1
GridLabel(self.win,"",nextRow,0)
nextRow+=1
GridLabel(self.win,"Number of Sets",nextRow,0)
self.__numSetsEntry = GridEntry(self.win,str(number_of_sets),nextRow,1)
nextRow+=1
GridLabel(self.win,"Probes per Set",nextRow,0)
self.__numProbesEntry = GridEntry(self.win,str(probes_per_set),nextRow,1)
nextRow+=1
GridLabel(self.win,"Encoding time (sec)",nextRow,0)
self.__encodeTimeEntry = GridEntry(self.win,str(encode_time),nextRow,1)
nextRow+=1
GridLabel(self.win,"",nextRow,0)
nextRow+=1
GridLabel(self.win,"Encoding Color",nextRow,0)
self.__encodeColorEntry = GridEntry(self.win,encode_color,nextRow,1)
nextRow+=1
GridLabel(self.win,"Probes Color",nextRow,0)
self.__probeColorEntry = GridEntry(self.win,probe_color,nextRow,1)
nextRow+=1
GridLabel(self.win,"",nextRow,0)
nextRow+=1
GridLabel(self.win,"Filename",nextRow,0)
self.__fileNameEntry = GridEntry(self.win,"Subject",nextRow,1)
nextRow+=1
self.__runButton = Button(self.win,text="Run Block",
command=self.runBlock)
self.__runButton.grid(row=nextRow,column=1,pady=5,sticky=E+W)
self.__quitButton = Button(self.win,text="Quit",command=self.CleanUp)
self.__quitButton.grid(row=nextRow,column=0,pady=5,sticky=E+W)
self.win.mainloop()
def CleanUp(self):
self.AllData.writeToFile(self.fileName)
self.win.quit()
def runBlock(self):
optDic = {}
optDic['number_of_sets'] = eval(self.__numSetsEntry.get())
optDic['probes_per_set'] = eval(self.__numProbesEntry.get())
optDic['set_size'] = eval(self.__setSizeEntry.get())
optDic['encode_color'] = self.__encodeColorEntry.get()
optDic['probe_color'] = self.__probeColorEntry.get()
optDic['yesKey'] = self.__yesKeyEntry.get()
optDic['noKey'] = self.__noKeyEntry.get()
optDic['encode_time'] = self.__encodeTimeEntry.get()
if self.BlockNumber == 1:
self.fileName = SafeFile(self.__fileNameEntry.get(),'.ana')
self.AllData = runSternbergBlock(self.BlockNumber,optDic,self.AllData)
self.__fileNameEntry.delete(0,END)
self.__fileNameEntry.insert(0,self.fileName)
self.BlockNumber+=1
GridLabel(self.win,str(self.BlockNumber),0,1)
def runSternbergBlock(BN,optionDict=None,TrialDict=None):
if optionDict:
for key in optionDict.keys():
exec(key + "=optionDict['" + key + "']")
myWindow = Display(width=WIDTH,height=HEIGHT)
myWindow.SetSize(FONTSIZE)
# Put up brief instructions?
myWindow.SetText("You will see a list of " + encode_color + " letters, which\n" + \
"you must remember. You will then be shown " + probe_color + \
"\nletters, which you must compare to the remembered list.\n" + \
"If the letter was in the list, press <" + yesKey + ">, otherwise\n" + \
"press <" + noKey + ">. Respond as quickly and accurately as\n" + \
"possible.\n\nPress any key to begin.")
myWindow.clearKey()
responseCollected = False
while not(responseCollected):
if myWindow[0]:
myWindow.update()
if myWindow.keyPress:
responseCollected = True
else:
responseCollected = True
myWindow.SetText("")
myWindow.update()
myClocks=Clock(5)
TN = 0
if not(TrialDict):
TrialDict = DataDict()
while myClocks[3] < 1:
myClocks.update()
myClocks.resetAll()
# Create my list of sets:
setList = []
while len(setList)<number_of_sets:
for size in set_size:
setList.append(size)
shuffle(setList)
emptyOrFullList = []
while len(emptyOrFullList)<(number_of_sets*probes_per_set):
emptyOrFullList += ['Empty','Full']
shuffle(emptyOrFullList)
for set in range(number_of_sets):
size = setList.pop()
Targets,Distractors = chooseSet(size)
myWindow.SetColor(encode_color)
myWindow.SetText(setString(Targets))
myWindow.update()
myClocks.reset(4)
if myWindow[0]:
while myClocks[4] < float(encode_time):
myClocks.update()
myWindow.SetText("")
myWindow.update()
myWindow.SetColor(probe_color)
# These help avoid repeats:
thisProbe,lastProbe = None,None
for probe in range(probes_per_set):
TN += 1
EorF = emptyOrFullList.pop()
pause = float(choice(range(int(min_delay*10),int(max_delay*10))))/10.0
myClocks.reset(4)
if myWindow[0]:
while myClocks[4] < pause:
myClocks.update()
while thisProbe == lastProbe:
if EorF=='Full':
thisProbe = choice(Targets)
else:
thisProbe = choice(Distractors)
if size==1: lastProbe = None # Avoids an infinite loop
lastProbe = thisProbe
myWindow.SetText(thisProbe)
myWindow.clearKey()
myWindow.update()
myClocks.reset(1)
myWindow.clearKey()
responseCollected = False
while not(responseCollected):
if myWindow[0]:
myClocks.update()
myWindow.update()
if myWindow.keyPress:
if myWindow.keyPress in [yesKey,noKey]:
responseCollected = True
response = myWindow.keyPress
RT = myClocks[1]
elif myClocks[1] > float(probe_timeout):
responseCollected = True
response = None
RT = -1
else:
responseCollected = True
response = None
RT = -1
TrialDict.update(BN,TN,set+1,response,RT,size,thisProbe,Targets,myClocks[0],yesKey,noKey)
myWindow.SetText("")
myWindow.clearKey()
myWindow.update()
myWindow.Close()
return TrialDict
if __name__ == '__main__':
sternbergGUI()
|
f473434e2066a83907bc39244011ccfb08a53b87 | jaggureddy/ZTM | /ZeroToMastery/Assignments/21_CalculateDistance.py | 1,377 | 4.5625 | 5 | """
A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer. Example: If the following tuples are given as input to the program:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:
2
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.Here distance indicates to euclidean distance.Import math module to use sqrt function.
"""
import math
c = []
while True:
line = input('')
if line:
c.append(line)
else:
break
x, y = 0, 0
prev = ''
for i in c:
stage = i.split(' ')[0]
dista = int(i.split(' ')[1])
if prev == '' and stage == 'UP':
x += dista
prev = 'UP'
if prev == 'UP' and stage == 'DOWN':
x -= dista
prev = 'DOWN'
if prev == 'DOWN' and stage == 'LEFT':
y -= dista
prev = 'LEFT'
if prev == 'LEFT' and stage == 'RIGHT':
y += dista
prev = 'RIGHT'
print(x, y)
print(round(math.sqrt(x**2 + y**2)))
|
cab6615cb0fdadb4b7f4f832407b6f7be4d447c3 | enterpreneur369/holbertonschool-higher_level_programming | /0x0A-python-inheritance/7-base_geometry.py | 860 | 3.59375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Module 7-base_geometry
This module contains the BaseGeometry class
"""
class BaseGeometry:
"""BaseGeometry class
A simple empty BaseGeometry class
"""
def area(self):
"""Returns an Exception"""
raise Exception("area() is not implemented")
def integer_validator(self, name, value):
"""Returns a TypeError or ValuError exception
Args:
name (str): The
"""
if not isinstance(name, str):
raise TypeError("The first parameter must \
be an string")
if not isinstance(value, int) or\
value.__class__ is bool:
raise TypeError("{:s} must be an integer"
.format(name))
if value <= 0:
raise ValueError("{:s} must be greater tha\
n 0".format(name))
|
c298b6f2cd9894f3f6b6fbbaca8b2e2b529f6e7f | saddam1999/code | /python/project/inline/INLineShell.py | 1,164 | 3.5 | 4 | First_FolderDIRECTORY = ["CODING"]
First_FolderFILE = ["Script.py","Text.txt"]
Second_FolderDIRECTORY = ["Python","Javascript","Php","Html","Css"]
Second_FolderFILE = [""]
class Folder:
def __init__(self,Name,Directory):
self.Name = Name
self.Directory = Directory
def Shell(self):
return f"{self.Name} \nDirectory:\n {self.Directory}\n"
class Riccardo(Folder):
def __init__(self,Name,Directory,File):
super().__init__(Name,Directory)
self.File = File
def Shell(self):
Shell = f"File:\n {self.File}"
return super().Shell() + Shell
class Coding(Folder):
def __init__(self,Name,Directory,File):
super().__init__(Name,Directory)
self.File = File
def Shell(self):
Shell = f"File \n {self.File}"
return super().Shell() + Shell
class Python(Folder):
def __init__(self,Name,Directory,File):
super().__init__(Name,Directory)
self.File = File
def Shell(self):
Shell = f"File:\n {self.File}"
return super().Shell() + Shell
First_Folder = Riccardo("Riccardo",First_FolderDIRECTORY,First_FolderFILE)
Second_Folder = Coding("Coding",Second_FolderDIRECTORY,Second_FolderFILE)
print(Riccardo.Shell(Second_Folder))
|
18b76ea8c82eb974bf4b353b3d1c7316bd767150 | quocanha/recurrence_solver | /recurrence_solver/solver/solver.py | 1,875 | 3.6875 | 4 | from sympy import *
from recurrence.recurrence import Recurrence
class Solver:
recurrence = None
def __init__(self, recurrence):
if type(recurrence) is not Recurrence:
raise TypeError("Solver requires a recurrence of type Recurrence")
self.recurrence = recurrence
def solve(self):
print("**** Recurrence ****")
print(self.recurrence)
terms = self.terms()
homo = []
non = []
for term in terms:
if self.is_homogeneous(term):
homo.append(term)
else:
non.append(term)
print("Homogeneous terms:")
for term in homo:
print("\t- " + str(term))
print("Nonhomogeneous terms:")
for term in non:
print("\t- " + str(term))
print()
def is_homogeneous(self, term):
"""
Traverses a term until it finds a function as argument.
:param term:
:return:
"""
if term.is_Function:
return true
else:
is_homo = false
for arg in term.args:
is_homo = self.is_homogeneous(arg)
return is_homo
def terms(self):
terms = []
expression = sympify(self.recurrence.recurrence)
var = expression[list(expression.keys())[0]]
equation = expression[list(expression.keys())[1]]
if type(var) is not Symbol or not var.is_Atom or not var.is_symbol:
raise TypeError(
"Expected the first element of the expression to be a variable."
)
if type(equation) is Add:
# We have multiple terms
terms = equation.args
else:
# We do not have multiple terms, so the whole expression is one term
terms.append(expression)
return terms
|
09cee9a9c8e880fb948b0eb5815ad0c592223b5a | eberlitz/data-analyst-nanodegree | /pj1/problem_sets/ps3/6 - Plotting Residuals.py | 1,402 | 3.578125 | 4 | import numpy as np
import scipy
from scipy import stats
import matplotlib.pyplot as plt
def plot_residuals(turnstile_weather, predictions):
'''
Using the same methods that we used to plot a histogram of entries
per hour for our data, why don't you make a histogram of the residuals
(that is, the difference between the original hourly entry data and the predicted values).
Try different binwidths for your histogram.
Based on this residual histogram, do you have any insight into how our model
performed? Reading a bit on this webpage might be useful:
http://www.itl.nist.gov/div898/handbook/pri/section2/pri24.htm
'''
plt.figure()
# plt.xlabel('Residuals')
# plt.ylabel('Frequency')
# plt.title('Histogram of the residuals')
# residual = turnstile_weather['ENTRIESn_hourly'] - predictions
# plt.xlabel('Fitted Value')
# plt.ylabel('Residual')
# plt.title('Residuals versus fits')
# plt.plot(predictions, residual, 'ro')
#plt.plot(turnstile_weather['ENTRIESn_hourly'],predictions, 'b')
#(turnstile_weather['ENTRIESn_hourly'] - predictions).hist(bins=100)
#plt.plot(turnstile_weather['ENTRIESn_hourly'] - predictions, 'b')
#plt.plot(predictions, 'b')
# Probability Plot
stats.probplot(turnstile_weather['ENTRIESn_hourly'] - predictions, plot=plt)
plt.show()
return plt |
70e42d6d6efbd0048b7c2850c8048c4b1fcc7340 | Harishkumar18/data_structures | /interviewbit_problems/trees/trie_pgm/shortest_unique_prefix.py | 1,172 | 3.84375 | 4 | """
Find shortest unique prefix to represent each word in the list.
Example:
Input: [zebra, dog, duck, dove]
Output: {z, dog, du, dov}
where we can see that
zebra = z
dog = dog
duck = du
dove = dov
"""
class Trie:
def __init__(self):
self.letters = {}
def addstring(self, s):
letters = self.letters
for ch in s:
if ch not in letters:
letters[ch] = {"freq": 1}
else:
letters[ch]["freq"] += 1
letters = letters[ch]
letters["*"] = True
def generateprefix(self, s):
prefix = []
letters = self.letters
for c in s:
prefix.append(c)
if letters[c]["freq"] == 1:
break
letters = letters[c]
return "".join(prefix)
class Solution:
def prefix(self, words):
trie_obj = Trie()
for word in words:
trie_obj.addstring(word)
ans = []
for each in words:
prefix = trie_obj.generateprefix(each)
ans.append(prefix)
return ans
inp_words = ["zebra", "dog", "duck", "dove"]
print(Solution().prefix(inp_words))
|
6c4ec3ddb3a760076af15332548512f1170fcf53 | artkpv/code-dojo | /hackerrank.com/contests/hourrank-24/strong-password/strong-password.py | 644 | 3.8125 | 4 | #!/bin/python3
"""
https://www.hackerrank.com/contests/hourrank-24/challenges/strong-password/problem
"""
import sys
def minimumNumber(n, password):
return max(6 - n,
(1 if not any(c in "abcdefghijklmnopqrstuvwxyz" for c in password) else 0) +
(1 if not any(c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for c in password) else 0) +
(1 if not any(c in "0123456789" for c in password) else 0) +
(1 if not any(c in "!@#$%^&*()-+" for c in password) else 0))
if __name__ == "__main__":
n = int(input().strip())
password = input().strip()
answer = minimumNumber(n, password)
print(answer)
|
05efbb842383e3a6f723a11eef297f2e1fab152d | yatengLG/leetcode-python | /question_bank/counting-bits/counting-bits.py | 717 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:88 ms, 在所有 Python3 提交中击败了92.93% 的用户
内存消耗:20.6 MB, 在所有 Python3 提交中击败了23.45% 的用户
解题思路:
某一数值num的比特位为1的计数,等于其 /2的余数为1 的数量
例:
13 余 6 余
/2 6 1 /2 3 0
/2 3 0 /2 1 1
/2 1 1 /2 0 1
/2 0 1
"""
class Solution:
def countBits(self, num: int) -> List[int]:
dp = [0 for _ in range(num+1)]
for i in range(1, num+1):
dp[i] = dp[i // 2] if i%2 == 0 else dp[i // 2]+1
return dp |
0205ffacd9f22b8e94f2eff85f6caee95aec8cd8 | Mygithub-projects/python_programs | /threads/three_thread.py | 608 | 3.640625 | 4 | import threading
def sum_of_even_series(n):
i=1
next = 2
sumeven=0
while( i <= n):
sumeven +=next
next+=2
i+=1
print("sum of even numbers = {} \n".format(sumeven))
def checknumber(n):
if (n%2==0):
print("{} is even number\n".format(n))
else:
print("{} is odd number\n".format(n))
def main():
t1 = threading.Thread(target=sum_of_even_series,args=(5,))
t2 = threading.Thread(target=checknumber,args=(7,))
t1.
t1.start()
t2.start()
if __name__=="__main__":
main()
|
a9c0ba8b4ed748ce19e31d413fe5437bf6d68b91 | diego-pacheco-PE/pythonCookbook_review | /ch01_PythonCookbook.py | 3,507 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 18 13:59:35 2021
@author: DIEGO PACHECO
"""
import numpy as np
# UNPACKING A SEQUENCE INTO SEPARATE VARIABLES
"""
You have an N-element tuple or sequence that you would like
to unpack into a collection of N variables.
"""
p = (4,5)
x, y = p
x
y
data = ['ACME', 50, 91.2, (2020,12,21)]
name, quantity, price, mydate = data
print(name)
name, quantity, price,(year, month, day) = data
year
_, var1, var2, _ = data
var1
# UNPACKING ELEMENTS FROM ITERABLES OF ARBITRARY
"""
You need to unpack N elements from an iterable, but the iterable
may be longer than N elements, causing a
“too many values to unpack” exception.
"""
# the use of star expressions
def drop_first_last(grades):
first, *middle, last = grades
return sum(middle)
print(drop_first_last([10, 8, 7, 1, 9, 5, 10]))
# KEEPING THE LAST N ITEMS
"""
You want to keep a limited history of the last few items seen during iteration
or during some other kind of processing
"""
import os
print(os.getcwd())
from collections import deque
print("ex3")
print('-'*20)
# generator function involving yield.
def search(lines, pattern, history=4):
previous_lines = deque(maxlen = history)
for line in lines:
if pattern in line:
yield line, previous_lines
previous_lines.append(line)
if __name__ == '__main__':
with open('somefile.txt') as f:
for line, prevlines in search(f, 'python', 4):
for pline in prevlines:
print(pline, end='')
print(line, end='')
print('-'*20)
q = deque()
q.append(1)
q.append(2)
q.append(3)
print(q)
q.appendleft(4)
print(q)
q.pop()
print(q)
q.popleft()
print(q)
# adding or popping items from either end of a queue has O(1) complexity.
# 1.4 FINDING THE LARGEST OR SMALLEST N ITEMS
"""
You want to make a list of the largest or smallest N items in a collection
"""
import heapq
nums = [1,8,2,2,3,6,-7,323,34,1211,3434,12,232,233]
print(heapq.nlargest(3,nums))
print(heapq.nsmallest(4,nums))
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(1, portfolio, key=lambda s: s['price'])
print(cheap)
print(expensive)
#order as a heap
nums = [-2,0,-123,23,2323,54,4,9,-334]
import heapq
heap = list(nums)
#order using heapify!
heapq.heapify(heap)
print(heap)
heapq.heappop(heap)
print(heap)
# 1.5 IMPLEMENTING A PRIORITY QUEUE
"""
You want to implement a queue that sorts items by a given priority and always returns
the item with the highest priority on each pop operation.
"""
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
class Item:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Item({!r})'.format(self.name)
q = PriorityQueue()
q.push(Item('foo'),1)
q.push(Item('bar'),332)
q.push(Item('spam'),120)
q.push(Item('grok'),5)
print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())
|
09655dd51519ee0139bca4ef1e342633bca5dbca | fwar34/Python | /test_yield7.py | 949 | 3.640625 | 4 | # async和await
# 弄清楚了asyncio.coroutine和yield from之后,在Python3.5中引入的async和await就不难理解了:可以将他们理解成
# asyncio.coroutine/yield from的完美替身。当然,从Python设计的角度来说,async/await让协程表面上独立于生成器而存在,
# 将细节都隐藏于asyncio模块之下,语法更清晰明了。
# 加入新的关键字 async ,可以将任何一个普通函数变成协程
import time
import asyncio
import random
async def mygen(alist):
while len(alist) > 0:
c = random.randint(0, len(alist) - 1)
print(alist.pop(c))
await asyncio.sleep(1)
str_list = ['aa', 'bb', 'cc']
int_list = [1, 3, 5, 6]
gen1 = mygen(str_list)
gen2 = mygen(int_list)
print(gen1)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
tasks = [gen1, gen2]
loop.run_until_complete(asyncio.wait(tasks))
print('All task finished.')
loop.close()
|
404bce339010302339fef981e1530c693ef11d6d | sakuya13/Study | /python/grok/grok_factorise.py | 325 | 3.984375 | 4 | def factorise(limit):
for i in range(1, limit + 1):
for j in range(1, limit + 1):
if i % j == 0:
print('* ', end='')
else:
print('- ', end='')
print()
def main():
limit = int(input('Maximum number to factorise: '))
factorise(limit)
main()
|
224a16dcd048dc9f524c35231bddaa2c8d831836 | ThomasZumsteg/project-euler | /problem_0050.py | 2,884 | 3.984375 | 4 | #!/usr/bin/env python3
"""
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?
"""
import logging
import sys
import time
logging.basicConfig(
level=logging.INFO,
stream=sys.stderr,
format='%(levelname)s:%(message)s')
def main():
block = 100000
primes = prime_sieve(block)
i = 0
max_i = 0
max_prime_set = 0
while True:
i += 1
if i >= len(primes):
primes = prime_sieve(block,primes)
if primes[i] > 1000000: break
logging.debug("Testing {}".format(primes[i]))
prime_set = is_prime_sum(primes[i],primes, max_prime_set)
if prime_set and max_prime_set < len(prime_set):
max_prime_set = len(prime_set)
max_i = i
logging.debug("{} is the sum of {} primes".format(
primes[i], max_prime_set))
print("{} is the sum of {} primes".format(primes[max_i], max_prime_set))
def is_prime_sum(num,primes,sum_min):
i = 0
while True:
prime_sum = primes[i:i+sum_min]
if sum(prime_sum) > num: return False
j = i + sum_min
while True:
prime_sum.append(primes[j])
if sum(prime_sum) > num: break
elif sum(prime_sum) == num: return prime_sum
j += 1
i += 1
def prime_sieve(extend,primes=[]):
logging.debug("Called prime_sieve")
nums = [ True ] * (extend)
if not primes: offset = 2
else:
offset = primes[-1]+1
for p in primes:
start = ( offset - 1 ) // p + 1
end = ( offset + extend - 1 ) // p + 1
for n in range(start, end):
logging.debug("{} is not prime ({} * {})".format(n*p, n,p))
nums[n*p-offset] = False
logging.debug("Marked {} False".format(n*p-offset))
for i in range(extend):
if nums[i]:
logging.debug("Found {}".format(i+offset))
primes.append(i+offset)
for n in range(2,1+extend//(i+offset)):
logging.debug("{} is not prime it {} * {}".format(
(i+offset)*n, n, i+offset))
nums[(i+offset)*n-offset] = False
logging.debug(nums)
return primes
def prime_generator(block=100000):
primes = []
i = 0
while True:
if len(primes) <= i:
primes = prime_sieve(block, primes)
yield primes[i]
i += 1
if __name__ == "__main__":
start = time.time()
main()
logging.info('That took {:4.2f} seconds'.format(time.time() - start))
|
ae232e69150bc4ba9fb6867d0b8d15521414dc1c | noahadelstein/mathemagic | /sample_python/automatedCensor (2013).py | 1,710 | 3.890625 | 4 | #-------------------------------------------------------------------------------
# Name: automatedCensor.py
# Purpose: prompts user for input/output file and wordlength,n; reads in text from a file
# and creates a new file where all n-length words are replaced by n *'s
#
# Assumptions: 1. ignores punctuation, 2. words printed on a single line
#
# Author: Adrienne Sands
#
# Created: 19/05/2013
# Copyright: (c) Adrienne Sands 2013
#-------------------------------------------------------------------------------
#to do: allow for punctuation
#D:\From Adrienne's Computer\Programming\Python\Chapter 11\sample data sets\censorTest.txt
def censor(stringList,censorNum):
censoredList = []
temp = ""
censorChar = "*"*censorNum
for i in stringList: #for each line in the file
temp=i.split() #split the line into words
for j in range(len(temp)): #for each word
if len(temp[j])==censorNum: #if the length of the word == censorNum
temp[j]=censorChar #replace it with the censor
censoredList.append(" ".join(temp)) #add the new line to censoredList
return censoredList
#prompts the user for an input/output file name and a word length to censor
def main():
filename = input("Enter an input filename: ")
infile = open(filename,'r')
stringList=infile.readlines()
infile.close()
censorNum = int(input("What size words do you want to censor? "))
output = censor(stringList,censorNum)
filename = input("Enter an output filename: ")
outfile = open(filename,'w')
for i in output:
print(i,file=outfile)
outfile.close()
print("File printed to",filename)
if __name__ == '__main__':
main()
|
95bee9ed7d0024dba765761dc9f801253d1822ee | HsiangHung/Code-Challenges | /Crackingcode_interview/3.stack_and_queues/Q3.5_mimicStack_by_twoStacks.py | 859 | 4.25 | 4 | ## Q3.5: use two stacks to implement a queue
#
# idea: using two stacks to pop can mimic a queue
#
class MyQueue():
def __init__(self):
self.items = []
def push(self,x):
self.items.append(x)
def pop(self):
C = stack()
for i in range(len(self.items)-1,0,-1):
C.push(self.items[i])
#print (C.get())
self.items = []
while C.get() != None:
#print (C.get(), type(C.get()))
self.items.append(C.get())
C.pop()
#print (C.get())
def get(self):
if self.items == []: return None
return self.items[0]
A = MyQueue()
A.push(5)
A.push(10)
A.push(1)
A.push(20)
print (A.get())
A.pop()
print (A.get())
A.pop()
print (A.get())
A.pop()
print (A.get())
A.pop()
print (A.get()) |
9eeb7eb2f8693c317416920e72ecee5794bca984 | AssiaHristova/SoftUni-Software-Engineering | /Python Advanced/first_exam_preparation/problem_2.py | 1,515 | 3.71875 | 4 | import math
def create_matrix(n):
matrix = []
for _ in range(n):
line = input().split()
matrix.append(line)
return matrix
def find_the_player(matrix):
for r in range(len(matrix)):
for c in range(len(matrix[r])):
if matrix[r][c] == 'P':
return r, c
def player_move(player_position, command):
r, c = player_position
if command == 'up':
r -= 1
elif command == 'down':
r += 1
elif command == 'left':
c -= 1
elif command == 'right':
c += 1
return r, c
def is_move_valid(player_move):
r, c = player_move
if r in range(len(matrix)) and c in range(len(matrix)):
if not matrix[r][c] == 'X':
return True
return False
n = int(input())
matrix = create_matrix(n)
player_position = find_the_player(matrix)
coins = 0
player_path = []
win = False
while True:
command = input()
if command == '':
break
move = player_move(player_position, command)
if not is_move_valid(move):
coins = math.floor(coins * 0.5)
break
else:
r, c = move
player_path.append([r, c])
player_field = matrix[r][c]
coins += int(player_field)
player_position = move
if coins >= 100:
win = True
break
if win:
print(f"You won! You've collected {coins} coins.")
else:
print(f"Game over! You've collected {coins} coins.")
print("Your path: ")
for el in player_path:
print(f"{el}")
|
eac76ba05b43e4e57097b0442855f73a8708212d | kwyate/py101 | /Juego_21/funciones.py | 3,153 | 3.71875 | 4 | import random
nombre = input("Por favor digita el nombre del jugador: ")
nombre = nombre.upper()
usuario = []
computador = []
def user(): # funcion retornar lista cartas usuario
return usuario
def pc(): #funcion retornar lista cartas maquina
return computador
def resUser(res):
res += res
return res
def list_cartas(): # lista de las cartas
valor = ["A", "2", "3", "4", "5", "6", "7", "8", "9" , "10", "J", "Q", "K"]
figura = ["c", "p", "d", "t"]
carta = random.choice(valor) + random.choice(figura)
return carta
def turno(t): # funcion ejecutar turno y el parametro se refiere al tipo de usuario
if t == "user":
if user() == []:
user().append(list_cartas ())
user().append(list_cartas ())
else:
user().append(list_cartas ())
return user()
else: # de no ser user sera turno de la maquina
if pc() == []:
pc().append(list_cartas ()) # agregar carta a la lista
pc().append(list_cartas ())
else:
pc().append(list_cartas ())
return pc()
def suma(res, inicio, t): # sumar el puntaje de las cartas res = puntaje cartas anteriores
if t == "user":
for i in range(inicio, len(user())): # este for busca recorrer la lista de cartas
if user()[i][0] in ["J", "Q", "K"]:
res += 10
elif user()[i][0] in ["A"]:
if res <= 10:
res += 11
elif res >= 11:
res +=1
elif user()[i][0] == "1" and user()[i][1] == "0":
res += 10
else:
res += int(user()[i][0])
#if user() in ["Ad", "Ap", "At", "Ac"] and res > 21:
# res -=10
return res
elif t == "maquina":
res
for i in range(inicio, len(pc())):
if pc()[i][0] in ["J", "Q", "K"]:
res += 10
elif pc()[i][0] in ["A"]:
if res >= 11:
res += 1
elif res <= 10:
res += 11
else:
res += random.choice([1, 11])
elif pc()[i][0] in ["1"] and pc()[i][1] in["0"]:
res += 10
else:
res += int(pc()[i][0])
return res
def validarGanador(numU, numC, userP, maqP):
if (numU > numC and numU <= 21) or (numU<= 21 and numC > 21) :
print("FELICIDADES GANASTE " + nombre)
print("El ganador es "+ nombre + " con : " + str(numU) + " contra : " + str(numC) + " de la MAQUINA")
userP += 1
elif (numC > numU and numC <= 21) or (numC<= 21 and numU > 21) :
print("QUE TRISTE PERDISTE" + nombre)
print("El ganador es la MAQUINA con : " + str(numC) + " contra : " + str(numU) + " de "+ nombre + " ")
maqP += 1
elif numU == numC:
print ("Empatados")
userP +=1
maqP +=1
del user()[:]
del pc()[:]
return userP, maqP
|
519591b63acf9735600117a530d47039e710f453 | arinj9508/algorithm | /알고리즘_이러닝/자릿수의 합.py | 309 | 3.609375 | 4 | # n의 각 자릿수의 합을 리턴
def sum_digits(n):
n = str(n)
if len(n) < 2:
return int(n)
return sum_digits(n[:len(n) - 1]) + int(n[len(n) - 1])
# 테스트
print(sum_digits(22541))
print(sum_digits(92130))
print(sum_digits(12634))
print(sum_digits(704))
print(sum_digits(3755)) |
5a9dde2044547c63061f203526db846738fef62e | musicicon/MIT-6.0001-solutions-to-projects | /Problem Set 2_Hangman Game.py | 12,819 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 16 12:11:21 2020
@author: Varun
"""
# Problem Set 2, hangman.py
# Name:
# Collaborators:
# Time spent:
# Hangman Game
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def choose_word(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = load_words()
def is_word_guessed(secret_word, letters_guessed):
'''
secret_word: string, the word the user is guessing; assumes all letters are
lowercase
letters_guessed: list (of letters), which letters have been guessed so far;
assumes that all letters are lowercase
returns: boolean, True if all the letters of secret_word are in letters_guessed;
False otherwise
'''
iswordguessed = True
for i in secret_word:
if i not in letters_guessed:
iswordguessed = False
break
return iswordguessed
def get_guessed_word(secret_word, letters_guessed):
'''
secret_word: string, the word the user is guessing
letters_guessed: list (of letters), which letters have been guessed so far
returns: string, comprised of letters, underscores (_), and spaces that represents
which letters in secret_word have been guessed so far.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
blanks = []
for i in range(len(secret_word)):
blanks.append('_ ')
j = 0
while j < len(secret_word):
if secret_word[j] in letters_guessed:
blanks[j] = secret_word[j]
j += 1
return ''.join(blanks)
def get_available_letters(letters_guessed):
'''
letters_guessed: list (of letters), which letters have been guessed so far
returns: string (of letters), comprised of letters that represents which letters have not
yet been guessed.
'''
allletters = list(string.ascii_lowercase)
for i in letters_guessed:
if i in allletters:
del(allletters[allletters.index(i)])
#we used this long format because python gets confused whether i belongs to
#letters_guessed or i belongs to allletters
return ''.join(allletters)
def islettercorrect(letter, numguess, strike, letters_guessed):
while True:
if letter.isalpha() and letter.lower() in get_available_letters(letters_guessed):
break
# elif letter == "*" :
# break
else:
if strike != 0:
print("Three Strikes and you loose a guess")
print("Strike ", strike)
if strike == 3:
numguess -= 1
strike = 0
print("Guesses Remaining: ", numguess)
if numguess == 0:
break
if not letter.isalpha():
letter = input("Please enter an aplhabet:")
if letter == "*":
strike -= 1
print(show_possible_matches(get_guessed_word(secret_word, letters_guessed), letters_guessed))
print("letters guessed", letters_guessed)
strike +=1
print("\n--------------------------")
return (letter, numguess, strike)
def getuniquewords(secret_word):
count = 0
listofletters = string.ascii_lowercase
for i in listofletters:
if i in secret_word:
count += 1
return count
def hangman(secret_word):
'''
secret_word: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secret_word contains and how many guesses s/he starts with.
* The user should start with 6 guesses
* Before each round, you should display to the user how many guesses
s/he has left and the letters that the user has not yet guessed.
* Ask the user to supply one guess per round. Remember to make
sure that the user puts in a letter!
* The user should receive feedback immediately after each guess
about whether their guess appears in the computer's word.
* After each guess, you should display to the user the
partially guessed word so far.
Follows the other limitations detailed in the problem write-up.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
uniquewords = getuniquewords(secret_word)
numguess = 6
letters_guessed = []
strike = 1
print("Welcome to the game Hangman")
print("I am thinking of a word that is", len(secret_word), "letters long")
print("----------------------------------")
print("Available guesses: ", numguess)
print("Available letters: ", get_available_letters(letters_guessed))
print("If you wrongly guess a consonant you get penalty of 1 guess")
print("If you wrongly guess a vowel you get a penalty of 2 guess")
while not(is_word_guessed(secret_word, letters_guessed)) and numguess > 0:
letter = input("Please input your guessed letter: ")
(letter, numguess, strike) = islettercorrect(letter, numguess, strike, letters_guessed)
if letter.lower() in secret_word:
numguess +=1
elif letter.lower() in 'aeiou' :
numguess -=1
letters_guessed.append(letter.lower())
print(get_guessed_word(secret_word, letters_guessed))
numguess -=1
if numguess == -1:
numguess = 0
print("\nGuesses Remaining: ", numguess)
print("Available Letters: ", get_available_letters(letters_guessed))
print("----------------------------------")
if is_word_guessed(secret_word, letters_guessed):
print("You won with a score of ",numguess*uniquewords)
else:
print("Game Over! you loose")
# When you've completed your hangman function, scroll down to the bottom
# of the file and uncomment the first two lines to test
#(hint: you might want to pick your own
# secret_word while you're doing your own testing)
# -----------------------------------
def match_with_gaps(my_word, other_word, letters_guessed):
'''
my_word: string with _ characters, current guess of secret word
other_word: string, regular English word
returns: boolean, True if all the actual letters of my_word match the
corresponding letters of other_word, or the letter is the special symbol
_ , and my_word and other_word are of the same length;
False otherwise:
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
iword = my_word.replace(" ", "")
what_to_return = True
for n in range(len(other_word)):
if iword[n] != "_" and iword[n] != other_word[n]:
what_to_return = False
break
for a in range(len(other_word)):
if other_word[a] in letters_guessed and other_word[a] != iword[a]:
what_to_return = False
return what_to_return
def show_possible_matches(my_word, letters_guessed):
'''
my_word: string with _ characters, current guess of secret word
returns: nothing, but should print out every word in wordlist that matches my_word
Keep in mind that in hangman when a letter is guessed, all the positions
at which that letter occurs in the secret word are revealed.
Therefore, the hidden letter(_ ) cannot be one of the letters in the word
that has already been revealed.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
possible = []
new_word = my_word.replace(" ","")
newlist = []
for i in wordlist:
if len(i) == len(new_word):
newlist.append(i)
for o in newlist:
if match_with_gaps(new_word, o, letters_guessed):
possible.append(o)
o = 0
return possible
def hangman_with_hints(secret_word):
'''
secret_word: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secret_word contains and how many guesses s/he starts with.
* The user should start with 6 guesses
* Before each round, you should display to the user how many guesses
s/he has left and the letters that the user has not yet guessed.
* Ask the user to supply one guess per round. Make sure to check that the user guesses a letter
* The user should receive feedback immediately after each guess
about whether their guess appears in the computer's word.
* After each guess, you should display to the user the
partially guessed word so far.
* If the guess is the symbol *, print out all words in wordlist that
matches the current guessed word.
Follows the other limitations detailed in the problem write-up.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
uniquewords = getuniquewords(secret_word)
numguess = 6
letters_guessed = []
strike = 1
print("Welcome to the game Hangman")
print("I am thinking of a word that is", len(secret_word), "letters long")
print("----------------------------------")
print("Available guesses: ", numguess)
print("Available letters: ", get_available_letters(letters_guessed))
print("If you wrongly guess a consonant you get penalty of 1 guess")
print("If you wrongly guess a vowel you get a penalty of 2 guess")
print("To get a hint at anytime in game enter an asterik * ")
while not(is_word_guessed(secret_word, letters_guessed)) and numguess > 0:
letter = input("Please input your guessed letter: ")
if letter == "*":
numguess +=1
print(show_possible_matches(get_guessed_word(secret_word, letters_guessed), letters_guessed))
(letter, numguess, strike) = islettercorrect(letter, numguess, strike, letters_guessed)
if letter.lower() in secret_word:
numguess +=1
elif letter.lower() in 'aeiou' :
numguess -=1
letters_guessed.append(letter.lower())
print(get_guessed_word(secret_word, letters_guessed))
numguess -=1
if numguess == -1:
numguess = 0
print("\nGuesses Remaining: ", numguess)
print("Available Letters: ", get_available_letters(letters_guessed))
print("----------------------------------")
if is_word_guessed(secret_word, letters_guessed):
print("You won with a score of ",numguess*uniquewords)
else:
print("Game Over! you loose")
print(secret_word)
# When you've completed your hangman_with_hint function, comment the two similar
# lines above that were used to run the hangman function, and then uncomment
# these two lines and run this file to test!
# Hint: You might want to pick your own secret_word while you're testing.
if __name__ == "__main__":
# # pass
# # To test part 2, comment out the pass line above and
# # uncomment the following two lines.
# secret_word = choose_word(wordlist)
# hangman(secret_word)
###############
# To test part 3 re-comment out the above lines and
# uncomment the following two lines.
secret_word = choose_word(wordlist)
hangman_with_hints(secret_word)
|
0668730f3d269c3116dc65b2f302e81df3c1d92c | PrimeMinisters/PrimeMinisters | /PrimeMinistersByPython/primeministers/reader.py | 919 | 3.578125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import io
import table
import tuple
class Reader(io.IO):
"""リーダ:総理大臣の情報を記したCSVファイルを読み込んでテーブルに仕立て上げる。"""
def __init__(self, csv_filename):
"""リーダのコンストラクタ。"""
self._csv_name = csv_filename
print "[Reader]ファイルネーム確認",self._csv_name
return
def table(self):
"""ダウンロードしたCSVファイルを読み込んでテーブルを応答する。"""
print "[Reader]tableの起動を確認"
csv_table = table.Table('input')
print "[Reader]ファイルネーム確認",self._csv_name
#継承の確認
#test = super(Reader,self).test()
#print test
reader = super(Reader,self).read_csv(self._csv_name)
#print reader
for row in reader:
csv_table.add(tuple.Tuple(csv_table.attributes(), row))
#print row
return csv_table
|
8687c99f0d4318142c6389c59d184029de809f83 | dkl2036/magic-8-ball-game | /magic8ball.py | 1,090 | 4 | 4 | import random
import time
print("Ask Python, the Magic 8 Ball a question!")
time.sleep(5) # waits 5 seconds
print("Searching for an answer . . . ")
time.sleep(2) # waits 2 seconds
print("Please be patient . . .")
time.sleep(1) # waits 1 seconds
for dot in range(10): # prints 10 dots seperated by 0.5 pause
print(".")
time.sleep(0.5) # waits 0.5 seconds
time.sleep(1) # waits 1 seconds
print("Python, the magic 8 ball says . . .")
time.sleep(3) # waits 3 seconds
answer = random.randint(1,9) # generates random number for answer in range
if answer == 1:
print("As I see it, yes.")
elif answer == 2:
print("Ask again later.")
elif answer == 3:
print("Better not tell you now.")
elif answer == 4:
print("Yes – definitely.")
elif answer == 5:
print("Without a doubt.")
elif answer == 6:
print("Outlook not so good.")
elif answer == 7:
print("Reply hazy, try again.")
elif answer == 8:
print("My sources say no.")
elif answer == 9:
print("Concentrate and ask again.")
|
eba2879bd01b0081978591f88cf293339a747fa6 | MaiziXiao/Algorithms | /Leetcode/数组字符串链表/7-easy-Reverse Integer.py | 610 | 3.9375 | 4 | class Solution:
"""
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
"""
def reverse(self, x: int) -> int:
res = 0
sign = -1 if x < 0 else 1
x = x*sign
# X 会变0
while x:
digit = x % 10
x = x // 10
res = res*10 + digit
# 溢出
if res > 2147483648 or res < -2147483648:
return 0
return sign*res
print(Solution().reverse(10)) |
a4d17516505b10e78c2107d64b9ea8dad42fe708 | ggardiakos/bradquant | /NYC时期/pcm_tools/toolbox.py | 12,868 | 3.5 | 4 | """
Contents:
1. Open CSV file
2. Count business days
3. Create multiple graphs
4. Import multi-tickers' close price
5. Stats Arb Pair's Z-score plotting
6. Any single time series's sharpe ratio
7. Fred's economic data import
"""
#------------------------------------------------------------------------------------------------------------------------------
# Open CSV file:
import csv
def open_with_csv(filename):
data = []
with open(filename, encoding = 'utf-8') as tsvin:
tie_reader = csv.reader(tsvin, delimiter = d) # just in case we have different types of delimiter
for line in tie_reader:
data.append(line)
# use UTF-8 encoding, just in case there are any special characters that may be an apostrophe or accent mark
return data
#------------------------------------------------------------------------------------------------------------------------------
# Counting business days:
import numpy as np
import datetime as dt
def counting_bdays(start, end):
days = np.busday_count(start, end)
return days
# counting_bdays(dt.date(2016, 1, 1), dt.date(2017,7,15))
#------------------------------------------------------------------------------------------------------------------------------
# Creating multiple graphs on one single chart:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
import pandas_datareader.data as wb
import seaborn as sns
def two_separate_graphs(series1, series2):
fig, (ax1, ax2) = plt.subplots(2,1, figsize=(25,20), sharex=True)
series1.plot(ax = ax1, color = 'blue', lw=1)
series2.plot(ax = ax2, color = 'red', lw=1)
def two_graphs_twinx(series1, series2):
fig = plt.figure(figsize = (30, 15))
ax1 = fig.add_subplot(1, 1, 1)
ax2 = ax1.twinx()
series1.plot(ax = ax1, color = 'blue', lw = 1)
series2.plot(ax = ax2, color = 'red', lw = 1)
ax1.axhline(0, color = 'blue', linestyle='--', lw=1)
ax2.axhline(0, color = 'red', linestyle='--', lw=1)
def three_graphs(series1, series2, series3):
fig, ax1 = plt.subplots(1,1, figsize=(25,10), sharex=True)
series1.plot(ax = ax1, color = 'blue', lw=1)
series2.plot(ax = ax1, color = 'red', lw=1)
series3.plot(ax = ax1, color = 'green', lw = 1)
def three_graphs_twinx(series1, series2, series3):
fig = plt.figure(figsize = (30, 15))
ax1 = fig.add_subplot(1, 1, 1)
ax2 = ax1.twinx()
ax3 = ax1.twinx()
series1.plot(ax = ax1, color = 'blue', lw = 1)
series2.plot(ax = ax2, color = 'red', lw =1)
series3.plot(ax = ax3, color = 'green', lw = 1)
# ax1.axhline(-1.0, color='g', linestyle='--', lw=1)
ax2.axhline(0, color = 'red', linestyle='--', lw=1)
ax3.axhline(0, color = 'green', linestyle='--', lw=1)
def five_graphs_twinx(series1, series2, series3, series4, series5):
fig = plt.figure(figsize = (30, 15))
ax1 = fig.add_subplot(1, 1, 1)
ax2 = ax1.twinx()
ax3 = ax1.twinx()
ax4 = ax1.twinx()
ax5 = ax1.twinx()
series1.plot(ax = ax1, color = 'blue', lw = 1)
series2.plot(ax = ax2, color = 'red', lw =1)
series3.plot(ax = ax3, color = 'green', lw = 1)
series4.plot(ax = ax4, color = 'black', lw = 1)
series5.plot(ax = ax5, color = 'purple', lw = 1)
def four_graphs(series1, series2, series3, series4):
fig, ax1 = plt.subplots(1,1, figsize=(25,10), sharex=True)
series1.plot(ax = ax1, color = 'blue', lw=1)
series2.plot(ax = ax1, color = 'red', lw=1)
series3.plot(ax = ax1, color = 'green', lw = 1)
series4.plot(ax = ax1, color = 'purple', lw = 1)
def five_graphs(series1, series2, series3, series4, series5):
fig, ax1 = plt.subplots(1,1, figsize=(25,10), sharex=True)
series1.plot(ax = ax1, color = 'blue', lw=1)
series2.plot(ax = ax1, color = 'red', lw=1)
series3.plot(ax = ax1, color = 'green', lw = 1)
series4.plot(ax = ax1, color = 'purple', lw = 1)
series5.plot(ax = ax1, color = 'black', lw = 1)
# ax3.axhline(-1.0, color='g', linestyle='--', lw=1)
# ax3.axhline(1.0, color='red', linestyle='--', lw=1)
# ax3.axhline(0, color = 'black', linestyle='--', lw=1)
#------------------------------------------------------------------------------------------------------------------------------
#def multiple_graphs2(series1, series2):
# fig, ax1 = plt.subplots(figsize = (30,15))
# series1.plot(ax = ax1, color = 'blue', lw=1)
# series2.plot(ax = ax1, color = 'red', lw=1)
#------------------------------------------------------------------------------------------------------------------------------
def google_data_close_price(symbol_list, start, end):
#decide which variables and how the function is gonna give you the result.
import_ = wb.DataReader(symbol_list, data_source='google', start=start, end=end)
close = import_['Close']
df = import_.to_frame().unstack()
# return df
return close
def google_data_oc_price(symbol_list, start, end):
import_ = wb.DataReader(symbol_list, data_source='google', start=start, end=end).drop(['Volume', 'High', 'Low'])
df_ = import_.to_frame().stack()
df = df_.unstack(level = 1)
idx = []
for ts, t in df.index:
if t == 'Open':
ts_ = ts.replace(hour=9, minute=30, second=0)
elif t == 'Close':
ts_ = ts.replace(hour=15, minute=59, second=59)
idx.append(ts_)
df.index = pd.DatetimeIndex(idx)
return df
# Update this fixed package on 9-18-2017:
import fix_yahoo_finance as yf
def get_yahoo_data(symbol_list, start_str, end_str):
"""
Documentation: start/end_str is of the format of, e.g. "2017-09-15"
"""
import_ = yf.download(symbol_list, start = start_str, end = end_str)
df = import_.to_frame().unstack()
return df
def get_yahoo_data_single(symbol, start_str, end_str):
"""
Documentation: start/end_str is of the format of, e.g. "2017-09-15"
"""
import_ = yf.download(symbol, start = start_str, end = end_str)
return import_
#------------------------------------------------------------------------------------------------------------------------------
# Create z-score
from collections import deque
def data_stream(symbol_list, start=datetime(2000,1,1), end=datetime(2015,12,31), source='google'):
if isinstance(symbol_list, str): symbol_list = [symbol_list]
data = wb.DataReader(symbol_list, data_source=source, start=start, end=end)
data = data.to_frame().unstack(level=1).dropna()
for dt, tickers in data.iterrows():
output = tickers.unstack().to_dict(orient='dict')
output['timestamp'] = dt
yield output
def cal_beta(X, y):
"""can be applied to cal beta betwene two securities
"""
X_ = np.asarray(X).reshape(-1,1)
y_ = np.asarray(y).reshape(-1,1)
X_ = np.concatenate([np.ones_like(X_), X_], axis=1)
return np.linalg.pinv(X_.T.dot(X_)).dot(X_.T).dot(y_)[1][0]
def cal_residual(x, y, beta):
return y - beta * x
def run_pairs(window, pair=['VXX', 'VXZ'], start=None, end=None, source='google', use_log=False):
s1, s2 = deque(maxlen=window), deque(maxlen=window) # data store
beta, signal, signal2 = [], [], [] # signal store
residual = deque(maxlen=window) # store the residual
ts = [] # time stamp
for tickers in data_stream(pair, start=start, end=end, source=source): # iter every market ticks
ts.append(tickers['timestamp']) # store this day's timestamp
s1.append(tickers[pair[0]]['Close']) # store VXX
s2.append(tickers[pair[1]]['Close']) # store VXZ
# now we have enough data to calculate signal
if len(s1)>=window and len(s2)>=window:
# getting the beta
if use_log:
X = np.log(s1)
y = np.log(s2)
else:
X, y = s1, s2
beta_ = cal_beta(X, y)
beta.append(beta_)
# calculate residual
res_ = cal_residual(x=X[-1], y=y[-1], beta=beta_)
residual.append(res_)
if len(residual)>=window:
mean = np.mean(residual)
std = np.std(residual)
signal_ = (res_ - mean) / std
signal2_ = res_
else:
signal_ = None
signal2_ = None
signal.append(signal_)
signal2.append(signal2_)
else:
beta.append(None)
signal.append(None)
signal2.append(None)
return pd.Series(beta, index=ts), pd.Series(signal, index=ts), pd.Series(signal2, index=ts)
# beta, signal, signal2 = run_pairs(10, ['QQQ','SPY'], start = datetime(2016,8,24))
def plot_zscore(signal, signal2):
fig, (ax1, ax2) = plt.subplots(2,1, figsize=(18,12))
signal2.plot(ax=ax1)
signal.plot(ax=ax2)
ax1.set_title('No Z-score Signal')
ax2.set_title('Z-score signal')
plt.axhline(signal.mean(), color='black')
plt.axhline(1.0, color='red', linestyle='--')
plt.axhline(-1.0, color='green', linestyle='--')
plt.legend(["Spread z-score - Ryan", 'Mean', '+1', '-1'], loc = 'best')
from fredapi import Fred
from datetime import datetime
USE_API = False
# generate a series of interest rate
def fred_3mon_ir(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('DTB3', observation_start=start, observation_end=end)
return s
# generate the most updated interest rate
def fred_3mon_ir_today(end = datetime.now()):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('DTB3', observation_end=end)
return s[-1]/100
def fred_1r_ir_today(end = datetime.now()):
if USE_API:
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('DGS1', observation_end=end)
return s[-1]/100
else:
return 1.2/100
# fred_data('DTB3', '2012-09-02', '2014-09-05')
def ten_yr_rate(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('DGS10', observation_start=start, observation_end=end)
return s
def three_fin_rate(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('DCPF3M', observation_start=start, observation_end=end)
return s
def three_nonfin_rate(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('CPN3M', observation_start=start, observation_end=end)
return s
def three_rate(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('TB3MS', observation_start=start, observation_end=end)
return s
def fed_total_asset(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('WALCL', observation_start=start, observation_end=end)
return s
def high_yield_rate(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('BAMLH0A0HYM2EY', observation_start=start, observation_end=end)
return s
def spx(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('SP500', observation_start=start, observation_end=end)
return s
def unemployment(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('UNRATE', observation_start=start, observation_end=end)
return s
def cpi(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('CPIAUCSL', observation_start=start, observation_end=end)
return s
def effective_fed_rate(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('FEDFUNDS', observation_start=start, observation_end=end)
return s
# industrial production index
def ipi(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('INDPRO', observation_start=start, observation_end=end)
return s
def m2(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('M2', observation_start=start, observation_end=end)
return s
def ppi(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('PCUOMFGOMFG', observation_start=start, observation_end=end)
return s
def gdp(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('A191RL1Q225SBEA', observation_start=start, observation_end=end)
return s
def debt_to_equity(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('TOTDTEUSQ163N', observation_start=start, observation_end=end)
return s
import urllib.request, urllib.error, urllib.parse
def put_call(start, end):
urlStr = 'http://www.cboe.com/publish/ScheduledTask/MktData/datahouse/totalpc.csv'
df_ = pd.read_csv(urllib.request.urlopen(urlStr), header = 2, index_col=0,parse_dates=True)
df = df_['P/C Ratio']
return df[start:end]
def ten_yr_3_month_rate_sprd(start, end):
fred = Fred(api_key='3de60b3b483033f57252b59f497000cf')
s = fred.get_series('T10Y3M', observation_start=start, observation_end=end)
return s
|
afb65d89a6a5a5baba23a8491562a192f4e3e7b9 | AstiV/Harvard-cs50 | /pset6/caesar/caesar.py | 2,469 | 4.4375 | 4 | from cs50 import get_string
import sys
def main():
# => argv = list of command-line arguments
# In C: argc = number of command line arguments
# A python list knows its length, so do len(sys.argv)
# to get the number of elements in argv.
# get the key from command line argument
# argc must be 2 (caesar.py and key)
if len(sys.argv) != 2:
print("Please include your desired key to the command line argument!\n")
elif len(sys.argv) == 2:
print(f"The key you chose is: {sys.argv[1]}")
# argv[1] = key is of datatype string
# convert key string to integer
# use atoi function
# check which value it will return if the string passed in doesn't contain all numbers
key = int(sys.argv[1])
# prompt for plaintext
# output "plaintext: " (without a newline) and then
# prompt the user for a string of plaintext (using get_string).
plaintext = get_string("plaintext: ")
# encipher
# for each character in the plaintext string
print("ciphertext: ", end="")
# n = length of user input string
n = len(plaintext)
for i in range(n):
# check if character is alphabetic (isalpha)
# in python isalpha does not take any parameters
# (in C isalpha(plaintext[i]))
if (plaintext[i]).isalpha():
# preserve case - lower case characters
if (plaintext[i]).islower():
# in python:
# function ord() gets the int value of the char
# to convert back afterwards, use function chr()
# -97, as difference of ASCII value and alphabetical index (for lower case characters)
# modulo 26 is used to wrap around the alphabet, e.g. x + 3 => a (26 = length of alphabet)
# add 97 back again to access right ASCII value letter
# store char value in variable as , end="" didn't work on calculation
lowercasechar = chr(((((ord(plaintext[i]) - 97) + key) % 26) + 97))
print(lowercasechar, end="")
# preserve case - upper case characters
else:
uppercasechar = chr(((((ord(plaintext[i]) - 65) + key) % 26) + 65))
print(uppercasechar, end="")
# preserve all other non-alphabetical characters
else:
print(plaintext[i], end="")
# print linebreak after string
print()
if __name__ == "__main__":
main() |
f9c532f999950b3dc727cc3f397db9414b03506b | zhangjingf/Python | /math.py | 376 | 3.671875 | 4 | import math
def power(x, n = 2):
s = 1
while n > 0:
n = n -1
s = s * x
return s
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
L = []
n = 1
while n <= 99:
L.append(n)
n = n + 2
L1 = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
L1[0:3] #['Michael', 'Sarah', 'Tracy'] L1[:3]
|
3747e2e64b4ebf567b39e4209e16911ba95a7c5f | buriihenry/python_basics | /functions.py | 1,516 | 4.03125 | 4 |
# Sum of two numbers
def add(a, b):
sum = a + b
return sum
res = add(10,5)
print(res)
print ('\n')
# Even or ODD Number
def even_number(n):
if n % 2 ==0:
print('Even Number')
else:
print('Odd Number')
even_number(19)
print ('\n')
# Version 2
def is_even(list1):
even_num=[]
for n in list1:
if n % 2==0:
even_num.append(n)
return even_num
even_num = is_even([2,3,10,15,20,24,9,62])
print(even_num)
print("\n")
# Version 3
def arithmetic(num1, num2):
add = num1 + num2
sub = num1 + num2
multiply = num1 * num2
division = num1 / num2
return add, sub, multiply, division
a, b, c, d = arithmetic(10,2)
print("Add:",a)
print("sub:",b)
print("multi:",c)
print("division:",d)
# Program to find the average marks
def find_average_marks(marks):
sum_of_marks =sum(marks)
total_subjects=len(marks)
average_marks=sum_of_marks/total_subjects
return average_marks
# Calculate grade and return it.
def compute_grade(average_marks):
if average_marks >= 80:
grade = 'A'
elif average_marks >= 60:
grade = 'B'
elif average_marks >= 50:
grade = 'C'
else:
grade = 'F'
return grade
marks = [80,75,90,64,55]
average_marks = find_average_marks(marks)
print("The Avreage Marks is:", average_marks)
grade = compute_grade(average_marks)
print("Your grade is:",grade)
# program to add and multiply two numbers
def add(x,y):
result = x + y
return result
sum = add( 2, 8)
print(sum)
def multiply(x,y):
result = x * y
return result
multi= multiply( 2, 8)
print(multi)
# End |
727e95470fa7f79947831e4b2f577365f81ba387 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/443a8b38e1c74b13b3a060c20bc57613.py | 395 | 3.828125 | 4 | def square_of_sum(number):
total_holder = 0
for x in range(1,number+1):
total_holder += x
total_holder = total_holder ** 2
return total_holder
def sum_of_squares(number):
total_holder = 0
for x in range(1,number+1):
total_holder += x**2
total_holder = total_holder
return total_holder
def difference(number):
return abs(sum_of_squares(number) - square_of_sum(number))
|
cbdde55117391d6e3ac3d8940f61188e66068ef8 | deplanty/mini-games | /Stars/src/objects/star.py | 563 | 3.8125 | 4 | import tkinter as tk
class Star:
def __init__(self, canvas:tk.Canvas, x:int, y:int, radius:int, mass:int):
self.r = radius
self.x = x
self.y = y
self.mass = mass
self.iid = None
self.canvas = canvas
def init(self):
"""
Initalizes the star and draw it
"""
self.iid = self.canvas.create_oval(
self.x - self.r,
self.y - self.r,
self.x + self.r,
self.y + self.r,
fill="yellow"
)
|
8e2b626b60fed9b67136ef6be7536f8967c57180 | abhinav33agrawal/Python_Projects | /Date_checker_from_two_differnt_string.py | 1,006 | 3.765625 | 4 | import re
def List_for_dates(all):
month_to_number = {
'January': 1,
'February': 2,
'March': 3,
'April': 4,
'May': 5,
'June': 6,
'July': 7,
'August': 8,
'September': 9,
'October': 10,
'November': 11,
'December': 12}
for i in range(len(all)):
all[i] = all[i].replace('-', ' ')
for i in range(len(all)):
p = all[i].split(' ')
month_name = p[0]
date = p[1]
year = p[2]
month_no = [v for k, v in month_to_number.items(
) if month_name.lower() in k.lower()][0]
final_date = "{}/{}/{}".format(month_no, date, year)
all[i] = final_date
return all
# TYPE TEXT 1 HERE
text_1 = """ """
# TYPE TEXT 2 HERE
text_2 = """ """
dates_list_1 = re.findall(r"[ADFJMNOS]\w*.[\d]{1,2}.[\d]{4}", text_2)
dates_list_2 = re.findall(r"\d{1,2}/\d{1,2}/\d{4}", text_1)
print(dates_list_2)
print(List_for_dates(dates_list_1) == dates_list_2)
|
96f7f4a761520477d45971bb984775f74b9db96a | GabrielTeodoroDomingues/calculadoraDePassagens | /Caluladora.py | 378 | 3.75 | 4 | #Variaveis.
vCartao = float(input('Quanto dinheiro há no seu cartão :'))
vPassagem = float(input('Quanto custa uma passagem :'))
dUso = float(input('Quantos vezes em um dia você utiliza este meio de transporte :'))
#Calculo de quantas passagens é possível utilizar.
print('O total de passagens que podem ser utilizadas é de {:.2f} .'.format(vCartao / (vPassagem * dUso)))
|
4d82f349a1ada5dfde06821f5782b7f2d38baadb | oh-data-sci/python_exercises | /exercises/09_brandwatch_sdk/sample_scripts/upload_queries.py | 1,641 | 3.515625 | 4 | """ Generates a uploads queries from a CSV file: name, includedTerms, language, samplePercent """
from bwresources import BWQueries
from ps_utils import ps_helper as ps
import csv
import re
#start script
project, username, projname = ps.create_proj_from_user()
queries = BWQueries(project)
#print a template for the csv file if requested
template = input("Would you like a template? [Y/N] ")
if template in ["y", "Y", "yes", "Yes", "YES"]:
filename = input('Enter name of CSV file for the template (e.g. template.csv): ')
with open(filename, 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"', escapechar = '"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(["name", "includedTerms", "language", "samplePercent"])
writer.writerow(["Sample Query", "(jibberish OR nonsense) AND nvajhfaehn", "en", "100"])
#get name of csv file and read it in
filename = input("When you're ready, enter the name of the CSV file that the queries are stored in: ")
query_list = []
with open(filename) as infile:
reader = csv.reader(infile)
for row in reader:
query_list.append(row)
#format data from csv file for bulk upload of queries
if query_list[0] == ['name', 'includedTerms', 'language', 'samplePercent']:
query_list.pop(0)
query_dicts = []
for row in query_list:
query_dicts.append({"name": row[0],
"includedTerms": row[1],
"language": row[2],
"samplePercent": row[3]})
#upload all queries
print("Uploading your queries now.")
queries.upload_all(query_dicts)
print("All done! Check in your account to see your new queries.")
|
ced82634722c4074b69e5f8fa84022a646eda16f | andyyang777/PY_LC | /383_另外一种解法.py | 1,049 | 3.6875 | 4 | # Given an arbitrary ransom note string and another string containing letters fr
# om all the magazines, write a function that will return true if the ransom note
# can be constructed from the magazines ; otherwise, it will return false.
#
# Each letter in the magazine string can only be used once in your ransom note.
#
#
#
# Example 1:
# Input: ransomNote = "a", magazine = "b"
# Output: false
# Example 2:
# Input: ransomNote = "aa", magazine = "ab"
# Output: false
# Example 3:
# Input: ransomNote = "aa", magazine = "aab"
# Output: true
#
#
# Constraints:
#
#
# You may assume that both strings contain only lowercase letters.
#
# Related Topics String
# 👍 694 👎 209
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
from collections import Counter
return Counter(magazine) & Counter(ransomNote) == Counter(ransomNote)
# leetcode submit region end(Prohibit modification and deletion)
|
dcc6534a97d9347cbc29a4332253a3b91dbe6fdb | Cremily/text-adventure | /Chooseyourownadventure.py | 11,167 | 3.5 | 4 | global PLAYER_INV
PLAYER_INV = {}
GAME_ON = True
from colorama import init
init()
from colorama import Fore,Back,Style
def read_inventory():
if len(PLAYER_INV) == 0:
print("You aren't carrying anything!")
return False
inv_string = "You have the "
for count,key in enumerate(PLAYER_INV):
if len(PLAYER_INV) == 1:
inv_string += key + "."
elif count <(len(PLAYER_INV)-1):
inv_string += key + ", "
else:
inv_string += "and the " + key + "."
print(inv_string)
return True
def remove_item(name):
if name in PLAYER_INV:
del PLAYER_INV[name]
class Room:
"""This is a room."""
def __init__(self,name):
self.name = name
def room_def(self,description,directions,items,interacts,look_desc):
self.desc = description
self.direc = directions
self.item = items
self.interact = interacts
self.look = look_desc
def add_item(self,item_pair):
self.item.append(item_pair)
def add_direc(self,direc_pair):
self.direc.update(direc_pair)
def add_interact(self,inter_pair):
self.interact.update(inter_pair)
def read_room(self):
direc_string = "You can go "
for count,key in enumerate(self.direc):
if len(self.direc) == 1:
direc_string += key + "."
elif count <(len(self.direc)-1):
direc_string += key + ", "
else:
direc_string += "and " + key + "."
item_string = "There is a "
for count,key in enumerate(self.item):
if len(self.item) == 1:
item_string += key.name + "."
elif count < (len(self.item) -2):
item_string += key.name + ", a "
elif count < (len(self.item)-1):
item_string += key.name + ", "
else:
item_string += "and an " + key.name + "."
inter_string = "You can see a "
for count,key in enumerate(self.interact):
if len(self.interact) == 1:
inter_string += key.name + "."
elif count <(len(self.interact)-2):
inter_string += key.name + ", a "
elif count < (len(self.interact)-1):
inter_string += key.name + ", "
else:
inter_string += "and an " + key.name + "."
print(Fore.RED + self.name + Style.RESET_ALL)
print(self.desc)
if direc_string != "You can go ":
print(direc_string)
if item_string != "There is a ":
print(item_string)
if inter_string != "You can see a ":
print(inter_string)
def read_obj(self,obj):
for item in self.item:
if obj == item.name.lower():
print(item.description)
return
for item in PLAYER_INV:
if obj == PLAYER_INV[item].name.lower():
print(item.description)
return
for inter in self.interact:
if obj == inter.name.lower():
print(inter.description)
return
for direc in self.direc:
print(direc.lower())
if obj == direc.lower():
print(self.direc[direc].look)
return
else:
print("What are you looking at? There's no %s!" % (obj))
return False
def take_item(self,item):
for obj in self.item:
if obj.name.lower() == item.lower():
PLAYER_INV.update({obj.name:obj})
print("You take the %s." % obj.name)
self.delete_item(obj)
return True
else:
print("There's no %s in this room!" % (item))
return False
def change_room(self,direction):
for room in self.direc:
if room.lower() == direction:
if isinstance(self.direc[room],EndRoom):
self.end_game()
return True
self.direc[room].read_room()
return self.direc[room]
else:
print("You can't go %s! Try a direction in this room!" % direction)
return self
def delete_item(self,del_item):
if del_item in self.item:
new_item_list = []
for item in self.item:
if item != del_item:
new_item_list.append(item)
self.item = new_item_list
return
try:
del(PLAYER_INV[del_item.name])
except Exception as e:
print(del_item.name,e)
def delete_interact(self,del_inter):
if del_inter.name in self.interact:
new_inter_list = []
for interact in self.interact:
if interact != del_inter.name:
new_inter_list.append(interact)
self.interact = new_inter_list
def use_item(self,first,second):
inter_obj = ""
item_obj = ""
for inter in self.interact:
if inter.name.lower() == second:
inter_obj = inter
if inter_obj == "":
print("I don't see a %s in this room!" % (second))
return
for item in PLAYER_INV:
if PLAYER_INV[item].name.lower() == first:
item_obj = PLAYER_INV[item]
for item in self.item:
if item.name.lower() == first:
item_obj = item
if item_obj == "":
print("I don't see a %s to use!" % (first))
return
print(inter_obj,item_obj)
if isinstance(inter_obj,Chest):
if isinstance(item_obj,Key):
inter_obj.unlock_chest(self,item_obj)
elif isinstance(inter_obj,Door):
if isinstance(item_obj,Key):
inter_obj.unlock_door(self,item_obj)
def take_words(self):
while GAME_ON == True:
player_in = input("What would you like to do? ")
verb = ""
phrase = ""
words = []
unclean_input = []
player_in = player_in.split(" ")
for x in player_in:
unclean_input.append(x.lower())
for word in unclean_input:
if word not in ["the","to","at","in"]:
words.append(word)
verb = words[0]
del(words[0])
for length,word in enumerate(words):
if length != len(words) - 1:
phrase += word + " "
else:
phrase += word
if verb == "exit" or verb == "quit":
print('Goodbye!')
break
if phrase == '':
if verb == "room" or (verb == "look"):
self.read_room()
continue
if verb == "go" or verb == "move":
print("Go where? Try again.")
continue
if verb == ("take" or "grab"):
print("What would you like to take? Try again.")
continue
if verb == "inventory" or verb == "inv":
read_inventory()
continue
if verb == "go" or verb == "move":
self = self.change_room(phrase)
if verb == "take" or verb == "grab":
self.take_item(phrase)
if verb == "look" and phrase == "room":
self.read_room()
continue
if verb == "look":
self.read_obj(phrase)
if verb == "use":
nphrase = phrase.split(" on ")
test_phrase = ""
for x in nphrase:
test_phrase += x
if test_phrase == phrase:
nphrase = phrase.split(" with ")
print(nphrase)
if len(nphrase) == 1:
self.use_inter(nphrase)
else:
self.use_item(nphrase[0],nphrase[1])
else:
print("You are amazing! Well Done!")
def end_game(self):
global GAME_ON
GAME_ON = False
return
class EndRoom(Room):
def __init__(self,name):
Room.__init__(self,name)
def room_def(self,look):
self.look = look
class Item:
def __init__(self,name,description):
self.name = name
self.description = description
class Key(Item):
def __init__(self,name,description):
Item.__init__(self,name,description)
class Chest(Item):
def __init__(self,name,description,keys,contents,unlock_str):
Item.__init__(self,name,description)
self.key = keys
self.content = contents
self.string = unlock_str
def unlock_chest(self,room,key):
for unlock_keys in self.key:
if key.name == unlock_keys.name:
for item in self.content:
room.add_item(item)
print(self.string)
room.delete_item(key)
remove_item(key)
room.delete_interact(self)
break
else:
print("That doesn't unlock %s!" % (self.name))
class Door(Item):
def __init__(self,name,description,keys,directions,unlock_str):
Item.__init__(self,name,description)
self.key = keys
self.direction = directions
self.string = unlock_str
def unlock_door(self,room,key):
for unlock_keys in self.key:
if key.name.lower() == unlock_keys.name.lower():
for direc in self.direction:
room.add_direc({direc:self.direction[direc]})
print(self.string)
room.delete_item(key)
remove_item(key)
room.delete_interact(self)
break
else:
print("That doesn't unlock the %s!" % (self.name))
SmallKey = Key("Useless key","Opens nothing.")
BigKey = Key("Stone Key","Opens the big chest.")
IronKey = Key("Iron Key","Comes from the test chest!")
TestChest = Chest("Chest","This is a test",[BigKey],[IronKey],"The chest bursts open, revealing a %s" % (IronKey.name))
TestRoom = Room("Testing Room")
NextRoom = Room("Testing Room 2")
Finish = EndRoom("Ending Room")
BigDoor = Door("Iron Door","Big and Iron.",[IronKey],{"East":Finish},"The door unlocks, letting you leave the cave!")
TestRoom.room_def("This is a room!",{'North':NextRoom},[BigKey],[TestChest,BigDoor],"Where you woke up.")
NextRoom.room_def("This is another room!",{'South':TestRoom},[BigKey],[],"Another cave.")
Finish.room_def("The outside!")
#TestRoom.read_room()
#TestRoom.take_words()
#this is another test |
f4fd7dd2b920178b27f21762af3cb1f4a1aff91b | iNateDawg/Craft | /normalize.py | 4,663 | 3.671875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import cv2
# Takes height and width as parameters
# sets and gets values in array
# returns and array
class NormArray:
def __init__(self, height, width):
self.height = height
self.width = width
self.array = np.arange(self.height * self.width).reshape(self.width, self.height)
self.minimum = [3]
self.maximum = [3]
def setval(self, x, y, val):
self.array[x][y] = val
def getval(self, x, y):
val = self.array[int(x)][int(y)]
return val
def getarray(self):
return self.array
def get_min(self, position=None):
return self.minimum[position]
def get_max(self, position=None):
return self.maximum[position]
def set_min(self, min, x, y):
self.minimum[1] = min
self.minimum[2] = x
self.minimum[3] = y
def set_max(self, max, x, y):
self.maximum[1] = max
self.maximum[2] = x
self.maximum[3] = y
# Takes image as parameter and normalizes it
# Normalize means taking an array of value and making min 0 and max 100 (or whatever value you want to the max)
# Returns normalized array#
#
## \package normalize
# \brief PURPOSE : Creates a file containing pixel values of topographic image
#
# \brief Ref : Req 1.0 Craft implementation shall create a terrain from a topographic image
# \brief Ref : Req 1.3 The realistic range of block heights shall be a minimum of 20 blocks and a maximum of 100 blocks
# \brief Ref : Req 3.0 One pixel in topographic image shall correspond to a 2x2 block area
# \brief Ref : Req 4.0 The minimum terrain generated block height shall be 20 blocks
# \brief Ref : Req 4.1 The maximum terrain generated block height shall be 100 blocks
#
# \param image : the topographic image to be processed
# \return norm_arr : file containing the data of pixel values for the topographic image
##
def normalize(image):
# scan image, resize to equal dimensions, convert to array of rgb values.
height = 1000
width = 1000
"""limit is 80 and not 100 b/c values will be normalized to range of 0 - 80
then 20 will be added on to make he range from 20 - 100, which is the
intented range """
limit = 80
img = plt.imread(image)
img = cv2.resize(img, (height, width))
# 1000 x 1000 array of pixel values
img_arr = np.asarray(img)
# 2000 x 2000 array of block height values
norm_arr = NormArray(height * 2, width * 2)
max_ = 50; min_ = 50
# get max and min values from img_arr
max = img_arr.max()
min = img_arr.min()
p = 0
q = 0
# Ref : Req 1.3 The realistic range of block heights shall be a minimum of 20 blocks and a maximum of 100 blocks
# Ref : Req 3.0 One pixel in topographic image shall correspond to a 2x2 block area
# copy img_arr to norm_arr
for x in range(norm_arr.height):
if (x % 2) == 0 and x != 0 and p < height:
p += 1
for y in range(norm_arr.width):
if (y % 2) == 0 and y != 0 and q < height:
q += 1
val = img_arr[p][q].min()
# depth of blocks is from 0 to 256 blocks, but max height will be 100 to give room to build higher
# and have a terrain that's easier to traverse
# Ref Req 4.0 The maximum terrain generated block height shall be 100
val = ((val - min) / (max - min)) * limit
# added 20 b/c the lowest point in the image should still be able to be mined past
#Ref : Req 4.0 The minimum terrain generated block height shall be 20 blocks
val = int(val + 20)
if val > max_:
max_ = val
norm_arr.set_max(val, p, q)
if val < min_:
min_ = val
norm_arr.set_max(val, p, q)
norm_arr.setval(x, y, val)
q = 0
return norm_arr
## \package normalize
# \brief PURPOSE : Creates a file containing pixel values of topographic image
# \brief Ref : Req 1.1 Topographic image shall be a .png image.
#
# \param image_name : the topographic image file to be processed
# \return file : file containing the data of pixel values for the topographic image
##
def process_image(image_name):
if not image_name.endswith(".png"):
return print("File must be a .png")
pixel_arr = normalize(image_name)
with open("data_file.txt", 'w') as file:
for x in range(pixel_arr.height):
for y in range(pixel_arr.width):
file.write(str(pixel_arr.getval(x, y)) + '\n')
file.close()
return file
process_image("heightdata.png") |
9171139f88726e7544264bad4d0a71c022bc51ea | riddhisharma2019/PYTHON-EXAMPLES | /fabonnici.py | 346 | 3.84375 | 4 | def fib(n):
a= 0
b= 1
print(a)
print(b)
for i in range(2,n): # range is from 2 bcz 0 and 1 is already print
c= a+b #this swapping is used for the forward nos
a=b
b=c
print(c)
fib(10) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.