blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
e36601367dfc98cf48ce14506a1df43646df0eb2 | vsisamp/aula | /é primo.py | 169 | 3.53125 | 4 | def primo(n):
for k in range(2, int(n/2)):
if n % k == 0:
return False
return True
n = primo(int(input('coloque o valor ')))
mudança @ TK |
47b445a9410aa417c021dac4fa8366a5063893df | EvanMeek/PythonBasics | /03_循环/hm_03_累加求和.py | 133 | 3.578125 | 4 | # 计算0~100之间的所有数字的累积和
i = 0
sum_number = 0
while i <= 100:
sum_number += i
i += 1
print(sum_number)
|
0345395299ba4ded394a1a0201eaf4108fd54424 | elizaluo/Word-Search-Solver | /word_finder.py | 866 | 3.71875 | 4 | #Eliza Luo, AthenaHacks
from funcs import *
def main():
puzzle = input('LETTERS IN WORD SEARCH (LEFT TO RIGHT, TOP TO BOTTOM):\n')
words = input('WORDS TO FIND:\n')
formatted_puzzle = format_puzzle(puzzle)
formatted_words = format_words(words)
print('Puzzle:\n')
for i in range(len(formatted_puzzle)):
print(formatted_puzzle[i])
print('')
locations = find_words(formatted_puzzle, formatted_words)
for i in range(len(formatted_words)):
if locations[i] == None:
print(formatted_words[i] + ': ' + 'word not found')
else:
word_c = formatted_words[i] + ':'
direction = locations[i][2]
row_num = locations[i][0]
col_num = locations[i][1]
print(word_c, direction, 'row:', row_num, 'column:', col_num)
if __name__ == '__main__':
main()
|
c3597881451d2771eff6c9f8fd55ef9becc230d4 | tegaryudistira/belajarpython | /percabangan logika/nilai.py | 305 | 3.859375 | 4 | #file grade_nilai.py
nilai = input("Inputkan nilaimu: ")
if nilai >= 90:
grade = "A"
elif nilai >= 80:
grade = "B+"
elif nilai >= 70:
grade = "B"
elif nilai >= 60:
grade = "C+"
elif nilai >= 50:
grade = "C"
elif nilai >= 40:
grade = "D"
else:
grade = "E"
print("Grade: %s" % grade)
|
09885bf3c6b93003b29a1b84e4869e1c33fbbc41 | Astr4l-project/Python | /Python/Variables.py | 2,215 | 3.921875 | 4 | aux_var = "Hola Mundo"
print(aux_var)
number_one = 10
number_two = 4
# La función print, se puede escribir de la forma ("Str", variable) o ("Str", concatenar(variable))
result = number_one + number_two
print ("Suma", result)
result = number_one - number_two
print ("Resta", result)
result = number_one * number_two
print("Multiplicación", result)
result = number_one / number_two
print("Division",result)
result = number_one // number_two
print("División Entera", result)
result = number_one ** number_two
print("Exponencial", result)
result = number_one % number_two
print("Modulo", result)
#################### Strings ###############################
my_string = "Hola Mundo!\nMe llamo Astr4l\nMi objetivo es Ayudar al Mundo"
print(my_string)
course ="Python 3"
name ="Kevin"
final_message = "Nuevo curso de "+ course + " por " + name #1
print(final_message)
final_message = "Nuevo curso %s por %s" %(course,name) #2
print(final_message)
final_message = "Nuevo curso de {} por {}".format(course, name) #3 ---> Es la forma más elegante de trabajar
print(final_message)
my_string = "Curso de Código Facilito!"
print(my_string)
print(my_string[0])
#El signo negativo invierte el sentido de lectura
print(my_string[-1])
#Extrae --> posinicial:posfinal+1
print(my_string[0:10])
#Extrae con saltos --> posinicial:posfinal+1:salto
print(my_string[0:10:2])
#Hacer un reverse a un String ::-1
print(my_string[::-1])
### Métodos String ####
#FORMATOS#
course = "Curso"
my_string = "Código Facilito"
result = "{} de {}".format(course,my_string)
print(result)
#Este formato parece útil
result = "{a} de {b}".format(b = course, a= my_string)
print(result)
#Minisculas
print(result.lower())
#Mayusculas
print(result.upper())
#Titulos
print(result.title())
#BUSQUEDA#
#El metodo find devuelve -1 cuando no encuentra el valor
pos = result.find("Curso")
print(pos)
#Cuenta los caracteres
count = result.count("o")
print(count)
#REEMPLAZO
#Donde esta "o" reemplaza con X
new_string = result.replace ("o","x")
print(new_string)
#SPLIT
new_string = result.split(" ")
print(new_string) |
3449dcaedae68ded96f3e769413da3227acf44f9 | qq76049352/python_workspace | /day13/字典推导式.py | 231 | 3.734375 | 4 | # dic = {"a":"b","c":"d"}
#
# new_dic = {dic[key]:key for key in dic }
# print(new_dic)
lst1 = ["alex","wusir","taibai","ritian"]
lst2 = ['sb',"很色","3","4"]
new_dic = {lst1[i]:lst2[i] for i in range(len(lst1))}
print(new_dic)
|
7a276e337f8928d3f8ae6a7dfc9d6bc971ea0205 | barua-anik/python_tutorials | /break.py | 275 | 4.1875 | 4 | #Example 1: Type exit to break
print("Example 1: ")
while True:
command = input("type 'exit' to exit \n")
if (command == "exit"):
break
#Example 2: exit from the program with a certain value
print("Example 2: ")
for x in range(1,101):
print(x)
if x==30:
break
|
d64417075ad511ce4783aeb1a3a341ddcd6db68a | saxenasamarth/BootCamp_PythonLearning | /week7/DS/Array/Missing_number.py | 238 | 4.125 | 4 | # Find missing number from group of n numbers
def missing_number(arr):
return (((len(arr)+2)*(len(arr)+1))/2)-sum(arr)
arr = [1, 2, 3, 5, 6, 7]
print(missing_number(arr))
arr = [1, 2, 3, 4, 5, 7, 8]
print(missing_number(arr)) |
a10e231591336158ce9546e6b629492495e0a5ed | aasimkhan30/203compiler | /python/pycc.py | 835 | 3.640625 | 4 | '''
This is the main file for the PyCC compiler.
There are 3 steps for the entire compilation process.
1. Lexer: Identifying token in the files.
2. Parser: Parsing those tokens.
3. Code Generation: Generate the actual assembly code for the compiler.
Given an input file, PYCC will generate an assemble code (3 address code)
which the gcc can assemble into an executable file.
Hopefully, This file should run on bash.
NO CODE OPTIMIZATIONS IS CONSIDERED AT THIS MOMENT.
'''
import os, sys
from parser import parser
with open(sys.argv[1], "r") as input_file:
print("Compiling " + sys.argv[1])
file_str = input_file.read()
# lex = lexer(file_str)
# cg = code_generator(sys.argv[1].split(".")[0] + '.s')
parser = parser(file_str, sys.argv[1].split(".")[0] + '.s')
parser.parse_source()
|
8e223758816ef401cab3ab44e6b3bebc5228dc59 | davidcinglis/relational-algebra | /plans/Parser.py | 17,219 | 3.96875 | 4 | import PlanNode as pn
import re
import sys
class Indices:
"""This object stores a set of indices.
Usually used for tracking the location of a substring within a larger string."""
def __init__(self, start_index, end_index):
"""
Class constructor.
:param start_index: the starting index
:param end_index: the ending index
"""
self.start_index = start_index
self.end_index = end_index
class Parser:
"""This object is used for parsing relational algebra input strings.
It stores a dictionary of relations and uses these relations to parse an input into an execution plan."""
def __init__(self, relations):
"""
Class constructor.
:param relations: A dictionary of relation names to relation objects (defined in PlanNode.py)
"""
self.relations = relations
@staticmethod
def tokenize_string(input_string):
"""
This method takes an input string and generates an array of all the variable names in the array.
A variable name must start with a letter and can contain only letters, numbers, periods, and underscores.
The keywords 'and' and 'or' are filtered from the results as these are reserved for evaluation.
A variable cannot be named 'and' or 'or'
:param input_string: This string to be tokenized
:return: An array of the variable tokens
"""
keywords = ["and", "or"]
# get rid of everything within quotes inside the string
input_string = re.sub("\'[^\']*\'", "", input_string)
results = re.findall("[A-Za-z][A-Za-z1-9_\.]*", input_string)
return [token for token in results if token not in keywords]
@staticmethod
def extract_token(open_char, close_char, input_string):
"""
This method extracts a substring enclosed by the specified brackets from the input string.
:param open_char: The open bracket character to extract with
:param close_char: The closed bracket character to extract with
:param input_string: The input string to extract from
:return: The extracted string
"""
# handle the weird case of a null input string
if len(input_string) == 0:
sys.exit("expecting %s character but could not find in string" % open_char)
ret_token = Indices(0, 0)
index = 0
# find first occurrence of open char in input string
while input_string[index] != open_char:
index += 1
# make sure we don't go out of bounds
if index >= len(input_string):
sys.exit("expecting %s character but could not find in string" % open_char)
ret_token.start_index = index + 1
count = 1
# use count to perform bracket matching; continue until open bracket closed successfully
while count > 0:
index += 1
# make sure we don't go out of bounds
if index >= len(input_string):
sys.exit("expecting %s character but could not find in string" % close_char)
# increment/decrement based on the brackets hit
if input_string[index] == open_char:
count += 1
elif input_string[index] == close_char:
count -= 1
ret_token.end_index = index
return ret_token
@staticmethod
def strip_parentheses(input_string):
"""
This method strips all enclosing parentheses from an input string: (((hello))) -> hello
:param input_string: The string to be stripped
:return: The stripped string
"""
working_string = input_string
while True:
# null string case (this should never come up...)
if len(working_string) == 0:
return working_string
# first ensure the first and last chars are parentheses
if working_string[0] != '(' or working_string[-1] != ')':
return working_string
# then ensure the first paren matches the last paren
indices = Parser.extract_token('(', ')', working_string)
if indices.end_index != len(working_string) - 1:
return working_string
# if we get this far, strip the parens from the string
working_string = working_string[1:-1]
@staticmethod
def parse_attribute_name(input_string):
"""
This method determines what the attribute name for the input string should be.
If the string contains the 'AS' keyword, the attribute name is everything following the keyword.
Otherwise the attribute name is simply the entire string.
:param input_string: The string to be parsed
:return: The attribute name for the input string
"""
input_string = input_string.strip()
if " AS " in input_string:
return input_string[input_string.find(" AS ") + len(" AS "):]
else:
return input_string
@staticmethod
def generate_aggregation_object(input_string):
"""
This method takes a string of the form 'sum(a) AS b' and parses it into an aggregation object.
:param input_string: The string to be parsed
:return: The generated aggregation object
"""
input_string = input_string.strip()
valid_agg_functions = ['sum', 'max', 'min', 'avg', 'count']
# make sure we have a valid aggregate function
agg_function = input_string[:input_string.find('(')].lower()
if agg_function not in valid_agg_functions:
sys.exit("invalid aggregate function specified")
# grab the aggregation attribute from inside the parentheses
agg_attribute_indices = Parser.extract_token('(', ')', input_string)
agg_attribute = input_string[agg_attribute_indices.start_index:agg_attribute_indices.end_index]
# make sure a result name was specified
if " AS " not in input_string:
sys.exit("aggregation result must be renamed")
result_name = input_string[input_string.find(" AS ") + len(" AS "):].strip()
return pn.Aggregation(agg_function, agg_attribute, result_name)
def parse_select(self, input_string):
"""
This method parses a select query into a plan node.
:param input_string: The query string. Assumed to be a select query.
:return: A SelectNode containing the parsed query
"""
# parse the predicate first, chucking it and all previous text from the working string
pred_token = self.extract_token('[', ']', input_string)
pred_str = input_string[pred_token.start_index:pred_token.end_index]
working_string = input_string[pred_token.end_index:]
# next parse the relation from the working string
relation_token = self.extract_token('(', ')', working_string)
relation_str = working_string[relation_token.start_index:relation_token.end_index]
relation_object = self.parse(relation_str)
# use the predicate and relation to construct a select node
return pn.SelectNode(pred_str, self.tokenize_string(pred_str), relation_object)
def parse_project(self, input_string):
"""
This method parses a project query into a plan node.
:param input_string: The query string. Assumed to be a project query.
:return: A ProjectNode containing the parsed query.
"""
# grab the projection arguments from inside the square brackets
projection_token = self.extract_token('[', ']', input_string)
projection_str = input_string[projection_token.start_index:projection_token.end_index]
# grab the input relation from inside the parentheses
relation_token = self.extract_token('(', ')', input_string[projection_token.end_index:])
relation_str = (input_string[projection_token.end_index:])[relation_token.start_index:relation_token.end_index]
relation_object = self.parse(relation_str)
# tokenize the projection arguments into an array and use this to generate the schema
projection_attributes = projection_str.split(',')
schema = [self.parse_attribute_name(attr) for attr in projection_attributes]
# once the schema has been generated, strip the 'AS' clause from each argument
for i in range(len(projection_attributes)):
if ' AS ' in projection_attributes[i]:
projection_attributes[i] = projection_attributes[i][:projection_attributes[i].find(' AS ')]
# generate a list of arguments for each projection in the array
projection_args = [self.tokenize_string(attribute) for attribute in projection_attributes]
return pn.ProjectNode(schema, relation_object, projection_attributes, projection_args)
def parse_aggregation(self, input_string):
"""
This method parses an aggregate query.
:param input_string: The input query. Assumed to be an aggregate query.
:return: An AggregationNode object built from the query
"""
# grab the aggregate function
aggregate_indices = self.extract_token('[', ']', input_string)
aggregate_expression = input_string[aggregate_indices.start_index:aggregate_indices.end_index]
working_string = input_string[aggregate_indices.end_index + 1:]
# grab the relation
relation_indices = self.extract_token('(', ')', working_string)
relation_expression = working_string[relation_indices.start_index:relation_indices.end_index]
relation_object = self.parse(relation_expression)
# build and return the object
aggregation = Parser.generate_aggregation_object(aggregate_expression)
return pn.AggregationNode(relation_object, None, aggregation)
def parse_grouping(self, input_string):
"""
This method parses a grouping/aggregation query.
:param input_string: The grouping query.
:return: An AggregatioNode object built from the query
"""
# TODO: combine common code from parse_aggregation into a helper function
# grab the grouping attributes
grouping_indices = self.extract_token('[', ']', input_string)
grouping_attribute = input_string[grouping_indices.start_index:grouping_indices.end_index]
working_string = input_string[grouping_indices.end_index + 1:]
# grab the aggregate function
aggregate_indices = self.extract_token('[', ']', working_string)
aggregate_expression = working_string[aggregate_indices.start_index:aggregate_indices.end_index]
working_string = working_string[aggregate_indices.end_index + 1:]
# grab the relation
relation_indices = self.extract_token('(', ')', working_string)
relation_expression = working_string[relation_indices.start_index:relation_indices.end_index]
relation_object = self.parse(relation_expression)
# build and return the object
aggregation = Parser.generate_aggregation_object(aggregate_expression)
return pn.AggregationNode(relation_object, grouping_attribute, aggregation)
def parse_rename(self, input_string):
# TODO
return
def parse_union(self, input_string):
args = self.parse_infix(input_string)
left_relation = self.parse(args[0])
right_relation = self.parse(args[2])
return pn.UnionNode(left_relation, right_relation)
def parse_intersect(self, input_string):
args = self.parse_infix(input_string)
left_relation = self.parse(args[0])
right_relation = self.parse(args[2])
return pn.IntersectionNode(left_relation, right_relation)
def parse_setdiff(self, input_string):
args = self.parse_infix(input_string)
left_relation = self.parse(args[0])
right_relation = self.parse(args[2])
return pn.SetDifferenceNode(left_relation, right_relation)
def parse_crossjoin(self, input_string):
args = self.parse_infix(input_string)
left_relation = self.parse(args[0])
right_relation = self.parse(args[2])
return pn.CartesianProductNode(left_relation, right_relation)
def parse_thetajoin(self, input_string):
# TODO
return
def natural_join_helper(self, input_string, is_left_outer, is_right_outer):
args = self.parse_infix(input_string)
left_relation = self.parse(args[0])
right_relation = self.parse(args[2])
return pn.NaturalJoinNode(left_relation, right_relation, is_left_outer, is_right_outer)
def parse_leftouter(self, input_string):
return self.natural_join_helper(input_string, True, False)
def parse_rightouter(self, input_string):
return self.natural_join_helper(input_string, False, True)
def parse_fullouter(self, input_string):
return self.natural_join_helper(input_string, True, True)
def parse_naturaljoin(self, input_string):
return self.natural_join_helper(input_string, False, False)
def parse_assignment(self, input_string):
args = self.parse_infix(input_string)
self.relations[args[0]] = self.parse(args[2]).execute()
return self.relations[args[0]]
# this maps prefix operator strings to the appropriate parser function
prefix_parsers = {
"SELECT": parse_select,
"PROJECT": parse_project,
"GROUPBY": parse_grouping,
"RENAME": parse_rename,
"AGGREGATE": parse_aggregation
}
# this maps infix operator strings to the appropriate parser function
infix_parsers = {
"UNION": parse_union,
"CROSSJOIN": parse_crossjoin,
"THETAJOIN": parse_thetajoin,
"NATURALJOIN": parse_naturaljoin,
"LEFTOUTERJOIN": parse_leftouter,
"RIGHTOUTERJOIN": parse_rightouter,
"FULLOUTERJOIN": parse_fullouter,
"SETDIFF": parse_setdiff,
"INTERSECT": parse_intersect,
"<--": parse_assignment
}
def parse_infix(self, input_string):
"""
This helper function parses an input string known to be in infix form into an [arg1, operator, arg2] array
:param input_string: The string to be parsed
:return: The array of argument tokens as strings: [arg1, operator, arg2]
"""
output_strings = []
working_string = input_string
# nested first arg
if input_string[0] == '(':
indices = self.extract_token('(', ')', input_string)
first_arg = input_string[indices.start_index: indices.end_index]
output_strings.append(first_arg)
working_string = input_string[indices.end_index + 1:]
# simple first arg
else:
tokens = input_string.split(' ')
first_arg = tokens[0]
if first_arg not in self.relations:
sys.exit("invalid relation: %s" % first_arg)
output_strings.append(first_arg)
working_string = working_string[working_string.find(' ') + 1:]
# operator parsing
working_string = working_string.strip()
tokens = working_string.split(' ')
operator = tokens[0]
if operator not in self.infix_parsers:
sys.exit("invalid infix operator: %s" % operator)
output_strings.append(operator)
# second arg parsing
second_arg = working_string[working_string.find(' ') + 1:].strip()
output_strings.append(second_arg)
return output_strings
def parse(self, input_string):
"""
This is the entry function into the parser object. It takes an input string and passes it off
to the appropriate parser.
:param input_string: The query string to be parsed.
:return: An execution plan for the query.
"""
# strip spaces and redundant parentheses
input_string = input_string.strip()
input_string = Parser.strip_parentheses(input_string)
tokens = input_string.split(' ')
# simple relation case
if len(tokens) == 1:
if tokens[0] in self.relations:
return self.relations[tokens[0]]
else:
sys.exit("invalid relation: %s" % tokens[0])
# check for a nested relation expression (e.g. left side of a join)
# in this case we know we must have an infix operator
elif input_string[0] == '(':
infix_args = self.parse_infix(input_string)
return self.infix_parsers[infix_args[1]](self, input_string)
# check for a prefix operator
elif tokens[0] in self.prefix_parsers:
return self.prefix_parsers[tokens[0]](self, input_string)
# check for an infix operator
elif tokens[1] in self.infix_parsers:
return self.infix_parsers[tokens[1]](self, input_string)
# every valid input will have either a prefix or infix operator, so at this point the input is invalid
else:
sys.exit("Could not match to a prefix or infix operator - check parentheses?")
|
0c165506419020e3caed700299fcc9d81749aad4 | hyeyin97/boj | /boj_11650.py | 218 | 3.578125 | 4 | N=int(input())
location=[]
for _ in range(N):
location.append(list(map(int,input().split())))
location=sorted(location,key=lambda x:(x[0],x[1]))
for i in range(N):
print(location[i][0],location[i][1],sep=' ') |
34a711989320741984d07e160a58022371f4cf57 | andreplacet/reiforcement-python-tasks-2 | /exe01.py | 539 | 4.09375 | 4 | # Exercicio 1
lista = []
for _ in range(2):
num = int(input(f'{_ + 1}º número: '))
lista.append(num)
print(f'O maior número digitado foi {max(lista)}')
'''
Lógica pura, sem uso de funções built-in
num1 = int(input('Informe o primeiro número: '))
num1 = int(input('Informe o segundo número: '))
if num1 > num2:
maior = num1
print(f'O maior número digitado foi: {maior}')
elif num1 == num2:
print(f'Os números são iguais')
else:
maior = num2
print(f'O maior número digitado foi: {maior}')
'''
|
e21ce727f2eb591e6fef9c7081087f58a2b83dbc | anantkaushik/Competitive_Programming | /Python/GeeksforGeeks/two-digit-sum.py | 1,030 | 3.984375 | 4 | """
You are given a two digit number n. Find the sum of its digits
Input Format:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input containing n.
Output Format:
For each testcase, in a new line, print the sum of digits of n.
Your Task:
This is a function problem. You do not need to take any input. Complete the function digitsSum and return the sum of digits of n.
Constraints:
1 <= T <= 100
10 <= n <= 99
Example:
Input:
1
25
Output:
7
"""
{
#Initial Template for Python 3
def main():
testcases=int(input()) #testcases
while(testcases>0):
a=int(input())
print(digitsSum(a))
testcases-=1
if __name__=='__main__':
main()
}
''' Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above. '''
#User function Template for python3
def digitsSum(n):
##Your code here
return n%10 + n//10 |
aa2930d58b86498d1e4308d6d2d4a0e1e49837ab | erjan/coding_exercises | /long_pressed_name.py | 1,312 | 3.703125 | 4 | '''
Your friend is typing his name into a keyboard. Sometimes, when typing a
character c, the key might get long pressed, and the character will be typed 1 or more times.
You examine the typed characters of the keyboard. Return
True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.
'''
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
f = lambda x: [list(group) for c, group in itertools.groupby(x)]
name, typed = f(name), f(typed)
if len(name) != len(typed): return False
for i in range(len(name)):
if not (name[i][0] == typed[i][0] and len(name[i]) <= len(typed[i])):
return False
return True
# 2 pointer solution
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
n=len(name)
m=len(typed)
if m<n:
return False
i=j=0
while(True):
print(i,j)
if i==n and j==m:
return True
if i<n and j<m and name[i]==typed[j]:
i+=1
j+=1
elif j>0 and j<m and typed[j-1]==typed[j]:
j+=1
else:
return False
|
53d4c555fb24d2cfe9dde0c0f197e3a7ef7b9ef5 | daniel-reich/turbo-robot | /KCmjq9m5dKoRFyHBd_5.py | 2,730 | 4.09375 | 4 | """
This challenge concerns non-convex polygons, such as the two polygons depicted
below. 
One special property of non-convex polygons is that, for some of their
vertices, the angle around that vertex that is contained inside the polygon is
a _reflex angle_ , i.e. an angle of more than 180 degrees. For this reason:
* In the left polygon above we say that `(1, 1), (3, 1)` are _reflex vertices_ (since the angle inside the polygon is a reflex angle) while `(0, 0), (4, 0), (2, 5)` are _regular vertices_.
* In the right polygon we say that `(1, 1)` is a reflex vertex while all the other vertices are regular vertices.
Write a function which given:
* A polygon described as a list of vertices where each vertex connects to the next and the last connects to the first (e.g. the polygons above are described by `[(0, 0), (4, 0), (3, 1), (2, 5), (1, 1)]` and `[(0, 0), (4, 0), (3, 1), (1, 1), (2, 5)]`) and ...
* One of the vertices of the polygon.
**Determines if the given vertex is a`"regular"` vertex or a `"reflex"`
vertex.**
### Examples (using the polygons depicted above)
which_side([(0, 0), (4, 0), (3, 1), (2, 5), (1, 1)], (3, 1)) ➞ "reflex"
which_side([(0, 0), (4, 0), (3, 1), (2, 5), (1, 1)], (0, 0)) ➞ "regular"
which_side([(0, 0), (4, 0), (3, 1), (1, 1), (2, 5)], (3, 1)) ➞ "regular"
which_side([(0, 0), (4, 0), (3, 1), (1, 1), (2, 5)], (1, 1)) ➞ "reflex"
### Notes
* The order of the vertices is important when specifying the polygon and thus affects whether each vertex is reflex or not (e.g. the two polygons above have the exact same vertices, but `(3,1)` is reflex in the left polygon and regular in the right polygon).
* In both examples above the vertices of the polygons are listed in counter-clockwise order, but the tests will include both clockwise and counter-clockwise order cases.
"""
def edge_sum(poly):
S = 0
for i in range(len(poly)):
x1, y1 = poly[i]
x2, y2 = poly[(i+1)%len(poly)]
S += (x2 - x1) * (y2 + y1)
return S
def is_to_the_left(p1, p2, p3):
# determine whether point p3 is to the left from the line from p1 to p2
position = (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0])
return position < 0
def which_side(poly, vert):
i2 = poly.index(vert)
i1 = (i2 - 1) % len(poly)
i3 = (i2 + 1) % len(poly)
v1, v2, v3 = poly[i1], poly[i2], poly[i3]
clockwise = edge_sum(poly) > 0
left = is_to_the_left(v1, v2, v3)
if clockwise:
return "regular" if left else "reflex"
else:
return "reflex" if left else "regular"
|
7c8d800f4850ad5af6725950cab3514d74b7e411 | TechAcademyBootcamp/week_9_day2_python_automation | /exceptions/unsolved.py | 517 | 4.03125 | 4 | def parse_input(user_input):
input_list = user_input.split()
## write codes and exceptions
## this function must return number1, operation, number2
def calculate(n1, op, n2):
if op == '+':
return n1 + n2
if op == '-':
return n1 - n2
if op == '*':
return n1 * n2
if op == '/':
return n1 / n2
#write exception
while True:
user_input = input('>>> ')
if user_input == 'quit':
break
n1, op, n2 = parse_input(user_input)
result = calculate(n1, op, n2)
print(result) |
dc8c3317c2a265ea65a2283c30fb6a5ef9ed2324 | davidhaas6/4-in-a-row-AI | /board_helper.py | 5,383 | 3.75 | 4 | from itertools import chain, groupby
def get_major_diagonals(arr2d, x_range, y_range):
"""
Returns major diagonals (they go like this: \)
@:param: x_range The number columns to the right (of arr[0][0]) to get the diagonals of
@:param: y_range The number of rows down (from arr[0][0]) to get the diagonals of
"""
rows, columns = 6, 7
diagonals = [[arr2d[r + y_offset][r] for r in range(rows - y_offset)] for y_offset in range(y_range, -1, -1)]
diagonals += [[arr2d[r][r + x_offset] for r in range(rows - (x_offset - 1))] for x_offset in range(1, x_range + 1)]
'''
# DECOMPRESSED VERSION OF THE TWO ABOVE LINES:
for y_offset in range(y_range, -1, -1):
for r in range(rows - y_offset):
temp_diag += [arr2d[r + y_offset][r]]
diagonals += [temp_diag]
temp_diag = []
for x_offset in range(1, x_range + 1):
for r in range(rows - (x_offset - 1)):
temp_diag += [arr2d[r][r + x_offset]]
diagonals += [temp_diag]
temp_diag = []
'''
return diagonals
def get_minor_diagonals(arr2d, x_range, y_range):
"""
Returns major diagonals (they go like this: /)
@:param: x_range The number columns to the right (of bottom left) to get the diagonals of
@:param: y_range The number of rows up (from bottom left) to get the diagonals of
"""
return get_major_diagonals(arr2d[::-1], x_range, y_range)
def get_sequence(arr, val, index, array_length):
# TODO: OPTIMIZE!!!!!!!
# Initialize the sequence length to two
sequence_length = 2
end_val = array_length
# See if sequence is longer than two
for j in range(index + 2, array_length):
# Increment the sequence length if it's continued
if arr[j] == val:
sequence_length += 1
# If the sequence is broken:
else:
# The index of the last item in the sequence
end_val = j
# Only save the sequence if it has a 0 on either side of it and sequence is in middle of row
if index > 0:
if not (arr[j] == 0 or arr[index - 1] == 0) and sequence_length < 4:
sequence_length = -1
# If the sequence starts at the first column, only save if it has a 0 after it
elif index == 0:
if arr[j] != 0 and sequence_length < 4:
sequence_length = -1
# If there's some case such as 1, 1, 0, 1 count it as a sequence of 3
if j < array_length - 1 and arr[j] == 0 and arr[j+1] == val:
sequence_length = 3 if sequence_length == 2 else sequence_length
break
# If the sequence goes until the end of the array, remove it unless it has a 0 before it
if end_val == array_length and arr[index - 1] != 0 and sequence_length < 4:
sequence_length = -1
# Set the for loop to start where the sequence ended
return end_val, sequence_length
def sequences_of_each(arr, val1=1, val2=2):
"""Returns array of sequence lengths of a value in an array"""
# List of lengths of sequences
seq1 = []
seq2 = []
i = 0
array_length = len(arr) # Saved as variable to reduce len() calls
while i < array_length - 1:
# If there's a row of at least two, start counting more
if arr[i] == arr[i + 1] == val1:
f = get_sequence(arr, val1, i, array_length)
i = f[0]
if f[1] != -1:
seq1 += [f[1]]
elif arr[i] == arr[i + 1] == val2:
f = get_sequence(arr, val2, i, array_length)
i = f[0]
if f[1] != -1:
seq2 += [f[1]]
else:
i += 1
# Rounds any value greater than 4 down to 4
seq1 = [4 if val > 4 else val for val in seq1]
seq2 = [4 if val > 4 else val for val in seq2]
return [seq1, seq2]
def seq_short(board_orientations):
# TODO: Needs to omit sequence if it has no 0s on either end.
seq = [[], []]
for row in chain(*board_orientations):
groups = [(g[0], len(list(g[1]))) for g in groupby(row)]
num_groups = len(groups)
for i in range(num_groups):
player_id, sequence_length = groups[i]
if player_id != 0 and sequence_length >= 2:
# Sorry for multiple if statements!.. couldn't think of any cleaner way to write it
# If it starts at beginning, check if followed by a 0 (empty space)
if i == 0 and groups[i + 1][0] == 0:
seq[player_id - 1] += [sequence_length]
# If it's in the middle, check if a 0 is on either side
elif (0 < i < num_groups - 1) and (groups[i + 1][0] == 0 or groups[i - 1][0] == 0):
seq[player_id - 1] += [sequence_length]
# If it's at the end, check if it's 4 in a row, or has a 0 before it
elif i == num_groups - 1 and (groups[i - 1][0] == 0 or sequence_length >= 4):
seq[player_id - 1] += [sequence_length]
return seq
def is_game_over(board_orientations):
for line in chain(*board_orientations):
for player_id, group in groupby(line):
if player_id != 0 and len(list(group)) >= 4:
return player_id
# Checks if the game board is full (tied)
return 0 not in board_orientations[0][0]
|
96fb7a2143c2341b300df0b6bd0b57a99ac3a4ca | TheChanRProject/PieranDataAssistance | /miller_time/circle.py | 403 | 3.953125 | 4 | import math
class Circle():
#class object attribute
def __init__(self, radius):
self.radius = radius
self.pi = math.pi
#method
def get_circumference(self):
return round((self.radius * self.pi * 2), 2)
def get_area(self):
return round(self.pi * self.radius**2 ,2)
circ = Circle(radius=10)
print(circ.get_circumference())
print(circ.get_area())
|
b08bbaded1323ce8961cf3ee92d36a3e87f4d0d5 | PercyT/-offer-Python- | /剑指offer/反转链表.py | 653 | 3.765625 | 4 | class node():
def __init__(self, item):
self.item = item
self.next = None
def createLinkList(l):
"""创建一个链表"""
if not l:
return
head = node(l[0])
p = head
for i in l[1:]:
p.next = node(i)
p = p.next
return head
def PrintLinklist(head):
while head:
print(head.item)
head = head.next
def reverseLinklist(head):
pre = None
pnode = head
reverseNode = None
while pnode is not None:
pnext = pnode.next
pnode.next = pre
pre = pnode
pnode = pnext
reverseNode = pre
return reverseNode
if __name__ == '__main__':
l = [1,2,3,4,5]
head = createLinkList(l)
reverse = reverseLinklist(head)
PrintLinklist(reverse) |
7faad1024acf7c9711b4b629ae705c8de27060b1 | caglar/prmlp | /post_mlp.py | 11,618 | 3.734375 | 4 | import numpy
import theano
from theano import tensor as T
from hidden import HiddenLayer
from log_reg import *
import pickle as pkl
DEBUGGING = False
class Costs:
Crossentropy = "crossentropy"
NegativeLikelihood = "negativelikelihood"
class PosttrainMLP:
"""Post training:- Second phase MLP.
A multilayer perceptron is a feedforward artificial neural network model
that has one layer or more of hidden units and nonlinear activations.
Intermediate layers usually have as activation function thanh or the
sigmoid function (defined here by a ``SigmoidalLayer`` class) while the
top layer is a softamx layer (defined here by a ``LogisticRegression``
class).
"""
def __init__(self,
input,
n_in,
n_hidden,
n_out,
rng=None,
is_binary=False,
params_first_phase=None):
"""
Initialize the parameters for the multilayer perceptron
:type rng: numpy.random.RandomState
:param rng: a random number generator used to initialize weights
:type input: theano.tensor.TensorType
:param input: symbolic variable that describes the input of the
architecture (one minibatch)
:type n_in: int
:param n_in: number of input units, the dimension of the space in
which the datapoints lie
:type n_hidden: int
:param n_hidden: number of hidden units
:type n_out: int
:param n_out: number of output units, the dimension of the space in which
the labels lie.
"""
self.input = input
if rng == None:
rng = numpy.random.RandomState(1234)
if DEBUGGING:
theano.config.compute_test_value = 'raise'
self.input.tag.test_value = numpy.random.rand(1800, n_in)
# Since we are dealing with a one hidden layer MLP, this will
# translate into a TanhLayer connected to the LogisticRegression
# layer; this can be replaced by a SigmoidalLayer, or a layer
# implementing any other nonlinearity
self.hiddenLayer = HiddenLayer(rng=rng, input=self.input,
n_in=n_in, n_out=n_hidden,
activation=T.tanh)
self.state = "train"
self.is_binary = is_binary
self.out_dir = "out/"
# The logistic regression layer gets as input the hidden units
# of the hidden layer
self.logRegressionLayer = LogisticRegressionLayer(
input=self.hiddenLayer.output,
n_in=n_hidden,
n_out=n_out,
is_binary=is_binary,
rng=rng)
# L1 norm ; one regularization option is to enforce L1 norm to
# be small
self.L1 = abs(self.hiddenLayer.W).sum() \
+ abs(self.logRegressionLayer.W).sum()
# square of L2 norm ; one regularization option is to enforce
# square of L2 norm to be small
self.L2_sqr = (self.hiddenLayer.W ** 2).sum() \
+ (self.logRegressionLayer.W ** 2).sum()
# negative log likelihood of the MLP is given by the
# crossentropy of the output of the model, computed in the
# logistic regression layer
if is_binary:
self.crossentropy = self.logRegressionLayer.crossentropy
else:
self.crossentropy = self.logRegressionLayer.crossentropy_categorical
# negative log likelihood of the MLP is given by the negative
# log likelihood of the output of the model, computed in the
# logistic regression layer
self.negative_log_likelihood = self.logRegressionLayer.negative_log_likelihood
# same holds for the function computing the number of errors
self.errors = self.logRegressionLayer.errors
# Class memberships
self.class_memberships = self.logRegressionLayer.get_class_memberships(self.hiddenLayer.get_outputs(self.input))
self.train_pkl_file = "post_train_n_hidden_" + str(n_hidden) + "n_out_" + str(n_out)
self.test_pkl_file = "post_test_n_hidden_" + str(n_hidden) + "n_out_" + str(n_out)
if params_first_phase is not None:
self.params = params_first_phase
# the parameters of the model are the parameters of the two layer it is
# made out of
self.params = self.hiddenLayer.params + self.logRegressionLayer.params
self.data_dict = { 'Ws':[],
'costs':[],
'test_probs':[],
'train_probs':[],
'test_scores':[]}
def _shared_dataset(self, data_x, name="x"):
shared_x = theano.shared(numpy.asarray(list(data_x), dtype=theano.config.floatX))
shared_x.name = name
return shared_x
def save_data(self):
output = None
if self.state == "train":
output = open(self.out_dir + self.train_pkl_file + ".pkl", 'wb')
else:
output = open(self.out_dir + self.test_pkl_file + ".pkl", 'wb')
pkl.dump(self.data_dict, output)
self.data_dict['Ws'] = []
self.data_dict['costs'] = []
self.data_dict['test_scores'] = []
def posttrain(self,
learning_rate=0.1,
L1_reg=0.00,
L2_reg=0.0001,
n_epochs=80,
data=None,
labels=None,
cost_type=Costs.Crossentropy,
save_exp_data=False,
batch_size=20):
if data is None:
raise Exception("Post-training can't start without pretraining class membership probabilities.")
if labels is None:
raise Exception("Post-training can not start without posttraining class labels.")
self.state = "train"
self.learning_rate = learning_rate
train_set_x = self._shared_dataset(data, name="training_set")
train_set_y = labels
# compute number of minibatches for training
n_examples = train_set_x.get_value(borrow=True).shape[0]
n_train_batches = n_examples / batch_size
######################
# BUILD ACTUAL MODEL #
######################
print '...postraining the model'
# allocate symbolic variables for the data
index = T.lscalar('index') # index to a [mini]batch
y = T.ivector('y') # the labels are presented as 1D vector of int32
mode = "FAST_COMPILE" #DEBUG_MODE"
if DEBUGGING:
self.input.tag.test_value = numpy.random.rand(self)
index.tag.test_value = 0
y.tag.test_value = numpy.ones(n_examples)
mode = "DEBUG_MODE"
# the cost we minimize during training is the negative log likelihood of
# the model plus the regularization terms (L1 and L2); cost is expressed
# here symbolically.
cost = None
if cost_type == Costs.NegativeLikelihood:
cost = self.negative_log_likelihood(y) \
+ L1_reg * self.L1 \
+ L2_reg * self.L2_sqr
elif cost_type == Costs.Crossentropy:
cost = self.crossentropy(y) \
+ L1_reg * self.L1 \
+ L2_reg * self.L2_sqr
gparams = []
for param in self.params:
gparam = T.grad(cost, param)
gparams.append(gparam)
# specify how to update the parameters of the model as selfa dictionary
updates = {}
# given two list the zip A = [a1, a2, a3, a4] and B = [b1, b2, b3, b4] of
# same length, zip generates a list C of same size, where each element
# is a pair formed from the two lists :
# C = [(a1, b1), (a2, b2), (a3, b3) , (a4, b4)]
for param, gparam in zip(self.params, gparams):
updates[param] = param - learning_rate * gparam
# compiling a Theano function `train_model` that returns the cost, butx
# in the same time updates the parameter of the model based on the rules
# defined in `updates`
# p_y_given_x = self.class_memberships
train_model = theano.function(inputs=[index],
outputs=cost,
updates = updates,
givens = {
self.input: train_set_x[index * batch_size:(index + 1) * batch_size],
y: train_set_y[index * batch_size: (index + 1) * batch_size]
},
mode=mode)
if DEBUGGING:
theano.printing.debugprint(train_model)
epoch = 0
costs = []
Ws = []
while (epoch < n_epochs):
for minibatch_index in xrange(n_train_batches):
print "Postraining in Minibatch %i " % (minibatch_index)
minibatch_avg_cost = train_model(minibatch_index)
costs.append(float(minibatch_avg_cost))
Ws.append(self.params[2])
epoch +=1
if save_exp_data:
self.data_dict['Ws'].append(Ws)
self.data_dict['costs'].append([costs])
self.save_data()
return costs
def posttest(self,
data=None,
labels=None,
save_exp_data = False,
batch_size=20):
if data is None:
raise Exception("Post-training can't start without pretraining class membership probabilities.")
if labels is None:
raise Exception("Post-training can not start without posttraining class-membership probabilities.")
test_set_x = shared_dataset(data)
test_set_y = labels
self.state = "test"
# compute number of minibatches for training, validation and testing
n_examples = test_set_x.get_value(borrow=True).shape[0]
n_test_batches = n_examples / batch_size
print '...post-testing the model'
# allocate symbolic variables for the data
index = T.lscalar() # index to a [mini]batch
y = T.ivector('y') # the labels are presented as 1D vector of
# [int] labels
mode = "FAST_RUN"
if DEBUGGING:
theano.config.compute_test_value = 'raise'
index.tag.test_value = 0
y.tag.test_value = numpy.ones(n_examples)
mode = "DEBUG_MODE"
# the cost we minimize during training is the negative log likelihood of
# the model plus the regularization terms (L1 and L2); cost is expressed
# here symbolically
# compiling a Theano function `test_model` that returns the cost, but
# in the same time updates the parameter of the model based on the rules
# defined in `updates`
test_model = theano.function(inputs=[index],
outputs=self.errors(y),
givens={
self.input: test_set_x[index * batch_size:(index + 1) * batch_size],
y: test_set_y[index * batch_size: (index + 1) * batch_size]},
mode=mode)
###############
# TEST MODEL #
###############
test_losses = []
for minibatch_index in xrange(n_test_batches):
test_losses.append(float(test_model(minibatch_index)))
test_score = numpy.mean(test_losses)
print("Minibatch %i, mean test error %f" % (minibatch_index, test_losses[minibatch_index] * 100))
print "In the end test score is %f" %(test_score * 100)
if save_exp_data:
self.data_dict['test_scores'].append(test_losses)
self.save_data()
return test_score, test_losses
|
30c77b2776051cc3ebd3aaf9f9e0a82a19d9e827 | frecklebars/sweatshirt | /learn.py | 3,116 | 4 | 4 | import sys
import json
import os.path
import re
def main():
dictionaryFile, inputFile = readArguments()
dictionary = loadDictionary(dictionaryFile)
if inputFile:
#read data from file
file = open(inputFile, "r", encoding="utf-8")
rawInput = file.read()
dictionary = learn(dictionary, rawInput)
dumpDictionary(dictionaryFile, dictionary)
else:
#read data from console input
while True:
rawInput = input(">> ")
#if nothing was entered, stop
if rawInput == "":
break
dictionary = learn(dictionary, rawInput)
dumpDictionary(dictionaryFile, dictionary)
def readArguments():
#defaults
dictionaryFile = "dictionary.json"
inputFile = ""
arguments = len(sys.argv)-1 #getting the number of arguments passed in the command line
#checking for dictionary
if arguments >= 1:
dictionaryFile = sys.argv[1]
if arguments >= 2:
inputFile = sys.argv[2]
return dictionaryFile, inputFile
def loadDictionary(dfile):
#checking if the dictionary exists
if not os.path.exists(dfile):
#if it doesnt we just make one
file = open(dfile, "w", encoding="utf-8")
json.dump({}, file)
file.close()
#read the existing dictionary
file = open(dfile, "r", encoding="utf-8")
dictionary = json.load(file)
file.close()
return dictionary
def learn(dictionary, rawInput):
rawInput = inputOptimize(rawInput)
words = rawInput.split(" ")
for i in range(len(words)-2):
currentWord = words[i]
secondWord = words[i + 1]
nextWord = words[i + 2]
#making the dict entry two words for better idk whats it called
#natural-er sounder sentences?
wordEntry = currentWord + " " + secondWord
#checking if the current and next words are in the dictionary already
if wordEntry in dictionary:
if nextWord in dictionary[wordEntry]:
dictionary[wordEntry][nextWord] = dictionary[wordEntry][nextWord] + 1
else:
dictionary[wordEntry][nextWord] = 1
else:
dictionary[wordEntry] = {nextWord: 1}
return dictionary
def dumpDictionary(dfile, dictionary):
file = open(dfile, "w", encoding="utf-8")
json.dump(dictionary, file)
file.close()
def inputOptimize(raw):
#makes the input text nicer so "father" and "father," aren't two different words
#and crap like that
raw = raw.lower()
raw = re.sub('\[.*\]', '', raw) #regex to del everything between [ and ]
raw = raw.replace("\n\n", "\n")
raw = raw.replace("\n", " ")
raw = raw.replace(" ", " ")
raw = raw.replace("\"", "")
raw = raw.replace("\\", "")
raw = raw.replace(",", "")
raw = raw.replace(".", "")
raw = raw.replace("(", "")
raw = raw.replace(")", "")
raw = raw.replace("*", "")
raw = raw.replace(":", "")
return raw
main()
|
81f25349bbca308fc6783e55902a3af54210795e | hansewetz/gitrep2 | /src/python/algorithms/isort/isort.py | 237 | 3.765625 | 4 | #!/usr/bin/env python
# execute insertion sort alg
def isort(v):
vlen=len(v)
for i in range(1,vlen):
for j in range(i,0,-1):
if v[j]<v[j-1]: v[j-1],v[j]=v[j],v[j-1]
# test
v=[6,3,4,9,12,45,0,2]
print(v)
isort(v)
print(v)
|
c08c8ba8e3dbd9115ee45f07ae9a2c35b0e2cfb8 | Nikolas2001-13/Universidad | /Nikolas_ECI_182/PIMB-2/W77.py | 419 | 3.515625 | 4 | from sys import stdin
def poderosos(a1,a2,a3,b1,b2,b3):
r=a1**2+a2**2+a3**2
j=b1**2+b2**2+b3**2
if r==j:
print("poderosos")
else:
print("endebles")
def main():
a,b=stdin.readline().strip().split()
a=int(a)
b=int(b)
a1=a//100
a2=(a%100)//10
a3=((a%100)%10)//1
b1=b//100
b2=(b%100)//10
b3=((b%100)%10)//1
poderosos(a1,a2,a3,b1,b2,b3)
main()
|
92b2fbc0a7b48b7531146a05bb19b13736734901 | jigi-33/checkio | /common_words.py | 493 | 3.78125 | 4 |
def checkio(first, second):
lst_1 = first.split(',')
lst_2 = second.split(',')
lst_3 = []
for i in lst_1:
if i in lst_2:
lst_3.append(i)
return ','.join(sorted(lst_3))
if __name__ == '__main__':
assert checkio("hello,world", "hello,earth") == "hello", "Hello"
assert checkio("one,two,three", "four,five,six") == "", "Too different"
assert checkio("one,two,three", "four,five,one,two,six,three") == "one,three,two", "1 2 3" |
d9f9bd6118c33b3d59a25815fcdde1b1be29fb05 | wanglingyun/interview-questions | /leetcode/LCP02.py | 757 | 4 | 4 | # 分式化简
import unittest
import math
from typing import List
class Solution(unittest.TestCase):
def fraction(self, cont: List[int]) -> List[int]:
# 第一位为分子 第二位为分母
result = [1,0]
for n in cont[::-1] :
# 若还存在下一个 先执行1 除以 result
# print(n,result)
result.reverse()
result[0] += n*result[1]
return result
def setUp(self):
self.run = self.fraction
def test_shuffle1(self):
type = self.run([3, 2, 0, 2])
self.assertEqual([13, 4], type)
def test_shuffle2(self):
type = self.run([2])
self.assertEqual([2,1], type)
if __name__ == '__main__':
unittest.main() |
cd7742d7d9773bde50c72d5903e23a6de72f4384 | RomanPutsilouski/M-PT1-37-21 | /Tasks/Lappo_Tasks/Class_Task3/sravnenir spis.py | 241 | 3.71875 | 4 | x = [1,2,3]
y = [1,2,3]
z=0
rez=0
if len(x)!=len(y):
print("Не равны")
else:
while z<len(x):
if x[z]==y[z]:
rez+=1
z+=1
if len(x)==rez:
print("Равны")
else:
print("Не равны")
|
511c80d8e8fdf26858d0ee11e7fcc3c2801af78b | qestar/Data_Sturcture | /selectionSort.py | 586 | 4 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
import numpy as np
import random
def find_smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selectionsort(arr):
newArr = []
for i in range(len(arr)):
smallest = find_smallest(arr)
newArr.append(arr.pop(smallest))
return newArr
arr = list(np.random.randint(10, 100, 10))
print('原数组: ', arr)
print('选择排序后:', selectionsort(arr)) |
a8bed7a7905f62adadece083bcba9bd2e8551b8f | donc1everon/Algorithm | /les01/task_1.py | 655 | 4.125 | 4 | # Задание - 1
# Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
#
# Блок - схема
# https://drive.google.com/file/d/1RI4u-DGMvbfC7f_qaUMVbSWK1Pmy7F7Q/view?usp=sharing
print('Введите трехзначное число')
a = int(input('a = '))
if 99 < a < 1000:
a_1 = a // 100
a_2 = a // 10 % 10
a_3 = a % 10
summ = a_1 + a_2 + a_3
prod = a_1 * a_2 * a_3
print(f'Сумма цифр числа равна - {summ}, произведение цифр - {prod}')
else:
print('Число не верное!') |
cccd07dd83abe0e0dfe3820c788090cf426999ff | Shammy0786/Python-learning | /main1.py | 295 | 3.546875 | 4 | def shm(str):
return f"give this string {str}"
def add(n1,n2):
return n1+n2+5
print("and the name is",__name__) # this will tell us the name
if __name__ == '__main__': # this main used only for this exicution after import
print(shm("shammy"))
b=add(6,4)
print(b) |
c827c54cb5e4d7c474ea091497a2d0a3226d88f8 | Screwlim/Algorithms | /JCF/p1-8.py | 1,009 | 3.6875 | 4 | #pb1
print('pb1')
nums = [100, 200, 300, 400, 500]
'''
nums.remove(400)
nums.remove(500)
'''
'''
del nums[3]
del nums[3]
'''
nums = nums[:3]
print(nums)
#pb2
print('pb2')
l = [200, 100, 300]
l.insert(2, 100000)
print(l)
#pb3
print('pb3')
l = [100, 200, 300]
print(type(l))
#class 'list'
#pb4
print('pb4')
a = 1
print(type(a))
#class 'int'
a = 2.22
print(type(a))
#class 'float'
a = 'p'
print(type(a))
#class 'str'
#char가 아님
a = [1, 2, 3, 4]
print(type(a))
#class 'list'
#pb5
print('pb5')
a = 10
b = 2
for i in range(1, 5, 2):
a += 1
# a = 12, b = 2 즉 14
print(a+b)
#pb6
print('pb6')
print(bool(None))
print(bool(1))
print(bool(""))
print(bool(0))
print(bool(bool(0)))
#1 이상은 참이다.
#pb7
print('pb7')
#as는 예약어로 이미 지정되어 있고 변수명은 숫자로 시작할 수 없다.
#pb8
print('pb8')
d = {'height':180, 'weight':78, 'weight':84, 'temperature':36, 'eyesight':1}
print(d['weight'])
#같은키가 존재할 경우 가장 뒤에 있는 값을 출력 |
8a7fe76887e698383b7191797aa527c287dd5743 | 95Satyen/Python-Practice | /Automate the boring stuff with Python Programming/Lists/IN and NOT IN Operators.py | 227 | 3.71875 | 4 | x = 'Kaju Katli' in ['Candies', 'Fudge', 'Kaju Katli'] #IN Operator
y = 'Soan Papdi' in ['Candies', 'Fudge', 'Kaju Katli'] #IN Operator
z = 'Soan Papdi' not in ['Candies', 'Fudge', 'Kaju Katli'] #NOT IN Operator
print(x)
print(y)
print(z)
|
fbdb69d609a9e23b1cc329815417f585aeb1f024 | vicky53/PythonTestCodes | /StringToNumberConversion.py | 2,516 | 3.59375 | 4 | import math
import re
def str_to_int(num):
j = 0
number = 0
for i in num[::-1]:
if i == "-":
number = number * -1
else:
digit_value = ord(i) - ord('0')
number = number + (digit_value * 10 ** j)
j += 1
return number
def correct_signs(txt):
result = False
lst = txt.strip().split()
for i in range(0, len(lst)):
if lst[i] == "<":
if int(lst[i - 1]) < int(lst[i + 1]):
result = True
else:
return False
elif lst[i] == ">":
if int(lst[i - 1]) > int(lst[i + 1]):
result = True
else:
return False
return result
def square_areas_difference(r):
square2 = (2 * r) * (2 * r)
square1 = square2 // 2
return square2 - square1
def century_from_year(num):
number = num // 100
if num % 100 == 0:
return number
else:
return number + 1
def validate_card(num):
if len(str(num)) < 13 or len(str(num)) > 19:
return False
last_digit = num % 10
reverse_num = str(num)[:-1][::-1]
sum_card = 0
for i in range(0, len(reverse_num)):
if (i + 1) % 2 == 1:
val = int(reverse_num[i]) * 2
count = 0
for j in str(val):
count = count + int(j)
sum_card = sum_card + count
else:
sum_card = sum_card + int(reverse_num[i])
if last_digit == (10 - (sum_card % 10)):
return True
else:
return False
def sqrt_num(num):
print(math.sqrt(num))
# lst = ["bad cookie", "good cookie", "bad cookie", "good cookie", "good cookie"]
# pattern = "*.bad.*"
# print(len(re.findall(pattern, ", ".join(lst))))
# print(str_to_int("-123"))
# print(correct_signs("3 < 7 < 11"))
# print(correct_signs("13 > 44 > 33 > 1"))
# print(correct_signs("1 < 2 < 6 < 9 > 3"))
# print(correct_signs("4 > 3 > 2 > 1"))
# print(correct_signs("5 < 7 > 1"))
# print(correct_signs("5 > 7 > 1"))
# print(correct_signs("9 < 9"))
# print(square_areas_difference(5))
# print(square_areas_difference(6))
# print(square_areas_difference(7))
# print(square_areas_difference(17))
# print(century_from_year(2005))
# print(century_from_year(2020))
# print(century_from_year(200))
# print(century_from_year(1700))
# print(century_from_year(1705))
print(validate_card(4400663686628309))
# print(validate_card(79927398713))
# print(validate_card(45391424543493400011))
# sqrt_num(1)
|
decbad7e6427c33c24c4e4cb5316d44e113aa631 | Ntaylor1027/Python-InterviewPrep | /Chapter 13 Sorting/Sorts.py | 2,537 | 4.34375 | 4 | import unittest
def quickSort(A):
def partition(A, low, high):
pivot = A[high]
i = low - 1
for j in range(low, high):
if A[j] < pivot:
i+=1
temp = A[i]
A[i] = A[j]
A[j] = temp
temp = A[i+1]
A[i+1] = A[high]
A[high] = temp
return i + 1
def quickSortDriver(A, low, high):
if(low < high):
pi = partition(A, low, high)
quickSortDriver(A, low, pi - 1)
quickSortDriver(A, pi+1, high)
A = quickSortDriver(A, 0, len(A)-1)
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 # Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+= 1
else:
arr[k] = R[j]
j+= 1
k+= 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i+= 1
k+= 1
while j < len(R):
arr[k] = R[j]
j+= 1
k+= 1
def bubbleSort(A):
"""
Description: Loop through array by len(A) times. Each time placing the last item at the correct spot
"""
for iterator in range(len(A)):
less_than = 0
greater_than = less_than + 1
while(greater_than < len(A) - iterator):
if (A[less_than] > A[greater_than]):
temp = A[less_than]
A[less_than] = A[greater_than]
A[greater_than] = temp
less_than += 1
greater_than += 1
return A
class TestSorts(unittest.TestCase):
def test_quickSort(self):
a = [1,1,2,2,4,6]
quickSort(a)
self.assertEqual(a, [1,1,2,2,4,6], "Should be [1,1,2,2,4,6]")
def test_mergeSort(self):
a = [2,2,1,1,6,4]
mergeSort(a)
self.assertEqual(a, [1,1,2,2,4,6], "Should be [1,1,2,2,4,6]")
def test_bubbleSort(self):
a = [2,2,1,1,6,4]
self.assertEqual(bubbleSort(a), [1,1,2,2,4,6], "Should be [1,1,2,2,4,6]")
if __name__ == "__main__":
unittest.main() |
cb43c486a50924ecc8ff765e9a2c50379feb28ab | jjspetz/digitalcrafts | /py-exercises2/de-dup.py | 181 | 4.25 | 4 | # deletes multiples in a list
list = [2,2,3,4,5,6,6,7,9,"a","b","a"]
mylist = []
for things in list:
if things not in mylist:
mylist.append(things)
print(mylist)
|
e57166b067ece46b42bdb0334c4d853471ca2d6d | Bappy200/Python | /OOPALL/Hakrrank_problem/namedTuples.py | 297 | 3.546875 | 4 | from collections import namedtuple
n = int(input())
items = input().split()
Student = namedtuple('student', items)
sum = 0
for i in range(n):
items1, items2, items3, items4 = input().split()
S = Student(items1, items2, items3, items4)
sum += S.MARKS
print('{0:.2f}'.format(sum/n))
|
0d0bdd4c9213540cee77657777b10a580a03daac | himanshush200599/codingPart | /geeksforgeeksproblem/leftlessrighthigh.py | 1,339 | 3.59375 | 4 | """
Given an unsorted array of size N. Find the first element in array such that all of its left elements
are smaller and all right elements to it are greater than it.
Note: Left and right side elements can be equal to required element. And extreme elements cannot
be required element.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow.
Each test case consists of two lines. First line of each test case contains an Integer N denoting size of array
and the second line contains N space separated array elements.
Output:
For each test case, in a new line print the required element. If no such element present in array then print -1
.
Constraints:
1<=T<=100
3<=N<=106
1<=A[i]<=106
Example:
Input:
3
4
4 2 5 7
3
11 9 12
6
4 3 2 7 8 9
Output:
5
-1
7
"""
# solution source - geeksforgeeks
for _ in range(int(input())):
n = int(input())
arr = list(map(int,input().split()))
l=[0]*n
r=[0]*n
l[0]=arr[0]
r[n-1]=arr[n-1]
for i in range(1,n):
l[i]=max(l[i-1],arr[i])
for i in range(n-2,-1,-1):
r[i]=min(r[i+1],arr[i])
flag=0
# print l
# print r
for i in range(1,n-1):
if arr[i]>=l[i-1] and arr[i]<=r[i+1]:
print (arr[i])
flag=1
break
if flag==0:
print (-1)
|
e87aa406efe2826d157adc3c45a95a6ad06b98ed | omkarkhade/ga-learner-dsmp-repo | /OmkarKhade_1/code.py | 996 | 3.75 | 4 | # --------------
# Code starts here
class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 =['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class= class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
new_class.remove('Carla Gentry')
print(new_class)
# Code ends here
# --------------
# Code starts here
courses={'Math':65, 'English': 70, 'History':80, 'French':70, 'Science':60}
total=0
for x in courses :
total +=courses[x]
percentage = (total/500)*100
print(percentage)
# Code ends here
# --------------
# Code starts here
mathematics={'Geoffrey Hinton':78, 'Andrew Ng':95,'Sebastian Raschka':65, 'Yoshua Benjio':50,
'Hilary Mason':70, 'Corinna Cortes':66, 'Peter Warden':75
}
max_marks_scored =max(mathematics,key = mathematics.get)
topper=max_marks_scored
print(topper)
# Code ends here
# --------------
# Given string
topper = 'andrew ng'
first_name=(topper.split()[0])
last_name= (topper.split()[1])
full_name= last_name+" "+first_name
certificate_name =full_name.upper()
print(certificate_name)
# Code starts here
# Code ends here
|
10ae0d9a5ca4df0cc68ad8b49733c9d26e38d0b4 | ZhicongChu369/ChatBot | /tokenization.py | 1,779 | 3.5625 | 4 | def sep_input_label(paired_txt):
'''Separate input and label sentences from paired txt'''
input_words = [ ]
label_words = [ ]
input_len = [ ]
label_len = [ ]
for i in range( len(paired_txt) ):
input_txt, label_txt = paired_txt[i][0], paired_txt[i][1]
input_words_cur = input_txt.split()
label_words_cur = label_txt.split()
input_words.append(input_words_cur)
label_words.append(label_words_cur)
# original length +2 to take SOS and EOS into consideration
input_len.append( len(input_words_cur) + 2)
label_len.append( len(input_words_cur) + 2)
return input_words, label_words, input_len, label_len
def indexesFromSentence(voc, sentence_words):
'''Transform words to index and add Start and END tokens'''
SOS_token = 1 # Start-of-sentence token
EOS_token = 2 # End-of-sentence token
return [SOS_token] + [voc.word2index[word] for word in sentence_words] + [EOS_token]
def zeroPadding( sentence_token, window_size ):
'''Pad tokenized sentence to the length of window size (excluding start and end sentence token)'''
PAD_token = 0 # Used for padding short sentences
sentence_token_padded = sentence_token
if len(sentence_token) < window_size:
sentence_token_padded = sentence_token + [PAD_token]* (window_size - len(sentence_token))
return sentence_token_padded
def tokenize( voc, txt_words, window_size ):
'''loop through input_words or label_words to tokenize every sentences'''
txt_tokenized = [ ]
for i in range(len(txt_words)):
txt_tokenized.append( zeroPadding( indexesFromSentence(voc, txt_words[i]), window_size) )
return txt_tokenized
|
3cefd2c215726b29d598aab573b6dc5f2dc479e5 | mtmcgowan/hort503 | /Assignment2/PythonApplication1/ex3.py | 1,637 | 4.59375 | 5 | # EXERCISE 3: Numbers and Math
print("")
print("I will now count my chickens:")
print("Hens", 25 + 30 / 6)
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("Is it true that 3 + 2 < 5 - 7?")
print(3 + 2 < 5 - 7)
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)
print("Oh, that's why it's False.")
print("How about some more.")
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
# Study Drills
# 1. Above each line, use the # to write a comment to yourself explaining what the line does.
# Actually, commenting EVERY line is a bad style to use and is unnecessary to convey to a reader what the code is doing.
# Instead it is better to comment blocks of code that group together for a specific purpose and comment the block.
# 2. Remember in Exercise 0 when you started python 3.6? Start it and use Python as a calculator.
# Done
# 3. Find something you need to calculate and write a new .py file that does it.
# Instead, I will perform calculations here so I can keep my coding script consolidated in a single .py file:
print("The integer remainder of 564/56:", 564%56)
# 4. Rewrite ex3.py to use floating point numbers so it's more accurate. 20.0 is floating point
# Technically, Python 3 appears to be using "true division" even when an operand is applied to two integer values.
# Furthermore, the more technical way to 'force' floating point division on an integer is to coerce it:
print("The integer quotient of 564/56:", float(564)/56) |
36481a3b51c9658f40acd544142f5e5e79d6a91d | paopee/paopee_memory | /Remainder (Modulo) Checker Challenge #7.py | 218 | 4.40625 | 4 | number= int(input ("What number do u want to check is it's divisible by 3?"))
if number % 3 == 0:
print ("Your number can be divided by 3 exactly")
else:
print ("Your number cannot be divided by 3 exactly")
|
ba62384d0e2d6c86d6e326965b42642f2ce73593 | DminGerasimov/C-1.9.1 | /figures2.py | 692 | 3.921875 | 4 | from figures import Rectangle, Square, Circle
#прямоугольники
rect1 = Rectangle(2, 3)
rect2 = Rectangle(3, 4)
#штаны спанчбоба
square1 = Square(5)
square2 = Square(6)
#окружности
circle1 = Circle(6)
circle2 = Circle(7)
figures = [rect1, square1, circle1, rect2, circle2, square2 ]
for figure in figures:
if isinstance(figure,Rectangle):
print(f"Figure Rectangle with area {figure.get_area()}")
elif isinstance(figure,Square):
print(f"Figure Square with area {figure.get_area()}")
elif isinstance(figure,Circle):
print(f"Figure Circle with area {figure.get_area()}")
else:
print("Error in head)")
|
444d87b27a39f0ef8355f9d8beb7df3fb5b93892 | callmesuji/python_assignments | /for_loop/Que_17.py | 214 | 4.4375 | 4 | # Write a program to generate the first 'N' natural numbers and print them in descending order.
num = int(input("Enter the number of natural numbers to be generated:"))
for num in range(num,0,-1):
print(num)
|
679ca6dd5971c369727e658753a17569bc394276 | AdamGoins/back | /python/PycharmProjects/CS-126SI/FunctionPractice.py | 1,667 | 4.0625 | 4 |
"""
" Write a function that accepts two integer arguments and returns the sum of those two arguments
" Call the function using arbitrary values and display the appropriate output
"""
someNumber = 6
def add_numbers(n1, n2):
sum_of_numbers = n1 + n2
return sum_of_numbers
def sub_num(n1,n2):
subtraction = n2 - n1
return subtraction
def main():
points_acquired = []
points_total = [20]
homework_score_one = int(input("Enter your first homework score:"))
points_acquired.append(homework_score_one)
homework_weighted_percent = get_total_percent(points_acquired, points_total, .2)
print(homework_weighted_percent)
test_points_acquired = [50, 75, 100]
test_points_total = [100, 100, 100]
test_weighted_percent = get_total_percent(test_points_acquired, test_points_total, .5)
print("weighted test percent: ", test_weighted_percent)
def get_total_percent(points_acquired, points_total, weight):
total_points_acquired = sum(points_acquired)
total_points_overall = sum(points_total)
percent_total = (total_points_acquired / total_points_overall) * 100
weighted_percent = percent_total * weight
return weighted_percent
main()
""" What is the output of these functions? """
def sayHi():
print("Hi!")
# sayHi()
def saySomething(something):
print(something)
# saySomething("This is something meaningful to say")
""" Now lets add returns statements """
def roundMyNumber(number, place_to_round_to):
return round(number, place_to_round_to)
print("Your number is rounded!")
# roundMyNumber(1.6180339887498948482045868345, 5)
|
76c740228f96fc713a496ac39487a0b0486b54c9 | cjulliar/home | /python/learn/cours1/annee_bissextile.py | 248 | 4.0625 | 4 | annee = input("Saisissez une année: ")
if int(annee) % 400 == 0 or (int(annee) % 4 == 0 and int(annee) % 100 != 0):
print("l'année", annee, "est bien une année bisséxtile")
else:
print("l'année", annee, "n'est pas une année bisséxtile")
|
60d1492ff2a599059bef5339dc45480eaf258ad4 | xiaotuzixuedaima/PythonProgramDucat | /PythonPrograms/python_program/decorator_fun_ex4.py | 322 | 3.984375 | 4 | # decorators example 2 now no touch decorators now toword the decorators by this moves program in the decorators ..??
def Sample(fun):
def example():
fun()
print("In example")
print("In sample")
return example
def add():
print("In add")
b = Sample(add)
b()
'''
output ==
In sample
In add
In example
''' |
8cfbc15785677971d40bb46adfaac3b271dc66eb | stand-by/MachineLearning_algorithms | /ml_toolbox/gradient_descent.py | 1,365 | 4.03125 | 4 | import numpy as np
class Batch(object):
"""
Batch class provides simple interface to gradient descent which is able to find local optimum.
The class has a constructor that takes user's function as callable which takes np.array as argument
and callable gradient of this function that returns gradient as np.array in certain point;
also, constructor takes learning rate and maximum number of iterations to converge.
Minimize method simply takes initial point to start descent and returns local optimum.
"""
def __init__(self, func, grad, rate, tolerance, max_iters):
"""
func=your callable function that takes np.array and returns np.array;
grad=callable gradient to your function that takes np.array and returns np.array
rate=model parameter that defines learning rate
num_iter=maximum number of iterations
"""
self.function = func
self.gradient = grad
self.max_iterations = max_iters
self.learning_rate = rate
self.tolerance = tolerance
self.x_min = None
def minimize(self, initial_guess):
x = initial_guess
x_hist = [x]
f_hist = [self.function(x)]
for i in range(self.max_iterations):
x_prev = x
x = x - self.learning_rate*self.gradient(x)
x_hist.append(x)
f_hist.append(self.function(x))
if (np.abs(x_prev-x) < self.tolerance).all(): break
self.x_min = x
return (x,np.array(x_hist),np.array(f_hist))
|
cf1285088904c04298b3f07d06cfc30722ca636a | stellakaniaru/practice_solutions | /learn-python-the-hard-way/ex19.py | 1,035 | 3.90625 | 4 | '''Functions and Variables.'''
'''there different ways to pass values to the
function:can be math,variables, straight numbers or a combination.
'''
#define a function
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" %cheese_count
print "You have %d boxes of crackers!" %boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
#pass values to the function using direct numbers
print "We can just give the function numbers directly:"
cheese_and_crackers(20,30)
#pass values to the function using variables
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
#pass values to the function using math
print "We can even do math inside too!:"
cheese_and_crackers(10 + 20, 30 + 48)
#pass values to the function using both variables and math
print "AND we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 26, amount_of_crackers + 37)
|
5baa01f85cddbe47216c43f2613f06c0245b1eed | 2621856814/nonebot-dicepp | /src/plugins/DicePP/data_manager/json_object.py | 1,668 | 3.609375 | 4 | """
继承JsonObject的类可以通过DataManager序列化或反序列
"""
import abc
from typing import Type, Dict
JSON_OBJECT_PREFIX = "JSON_OBJ_"
class JsonObject(metaclass=abc.ABCMeta):
"""
可以存在Json中的Object, 并不代表一定要通过Json反序列化和序列化
构造函数不能拥有参数! 原因见construct_from_json
"""
def to_json(self) -> str:
return JSON_OBJECT_PREFIX + type(self).__name__ + "$" + self.serialize().strip()
@classmethod
def construct_from_json(cls, json_str: str) -> 'JsonObject':
"""
从一个json字符串中构造一个json object并返回
Args:
json_str: 格式见JsonObject.to_json方法
Returns:
"""
json_str = json_str[len(JSON_OBJECT_PREFIX):]
cls_name, json_str = json_str.split("$", 1)
json_cls: Type[JsonObject] = ALL_JSON_OBJ_DICT[cls_name]
json_obj: JsonObject = json_cls()
json_obj.deserialize(json_str)
return json_obj
@abc.abstractmethod
def serialize(self) -> str:
"""
将自身序列化为任意字符串
"""
raise NotImplementedError()
@abc.abstractmethod
def deserialize(self, json_str: str) -> None:
"""
通过字符串将自身反序列化
"""
raise NotImplementedError()
ALL_JSON_OBJ_DICT: Dict[str, Type[JsonObject]] = {}
def custom_json_object(cls):
"""
类修饰器, 将自定义JsonObject注册到列表中
"""
assert issubclass(cls, JsonObject)
assert cls.__name__ not in ALL_JSON_OBJ_DICT
ALL_JSON_OBJ_DICT[cls.__name__] = cls
return cls
|
f1bc4306fc243826095adba9895e0f41e2c30bd6 | psangli/cpe101 | /lab6/groups/groups.py | 545 | 3.609375 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Psangli
#
# Created: 04/02/2015
# Copyright: (c) Psangli 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
pass
def groups_of_3(list):
array = []
newArray = []
g = 3
for i in range(0, len(list),g):
array = list[i:i+g]
newArray.append(array)
return newArray
if __name__ == '__main__':
main()
|
79533523cefcc4c271ceff648ee44443507ed117 | khulifi/route_finder | /main.py | 3,681 | 3.96875 | 4 | # written by asaah18
from data_structure import Graph, Stack
def get_user_choice(choices) -> int:
"""
ask the user to choose from the given choices
:param choices : list of choices as a string
:return index_of_user_input: int
"""
# print choices
for index, choice in enumerate(choices):
print("[" + str(index) + "] " + choice)
# get user input
while True:
user_input = input("\n" + "input: ")
if (user_input.isdigit() is False) or (int(user_input) not in range(len(choices))):
print("wrong input!")
else:
return int(user_input)
class FindRoute:
"""a class to find route between 2 cities using depth first search"""
graph = Graph()
stack = Stack()
start_city = None
target_city = None
def __init__(self):
self.setup_graph()
self.set_starting_city()
self.set_target_city()
self.depth_first_search()
def setup_graph(self):
self.graph.add_node("Buraydah", ["Unayzah", "Riyadh-Alkhabra", "Al-Bukayriyah"])
self.graph.add_node("Unayzah", ["AlZulfi", "Al-Badai", "Buraydah"])
self.graph.add_node("Riyadh-Alkhabra", ["Buraydah", "Al-Badai"])
self.graph.add_node("Al-Bukayriyah", ["Buraydah", "Sheehyah"])
self.graph.add_node("AlZulfi", ["Unayzah", "UmSedrah"])
self.graph.add_node("Al-Badai", ["Unayzah", "Riyadh-Alkhabra", "AlRass"])
self.graph.add_node("Sheehyah", ["Al-Bukayriyah", "Dhalfa"])
self.graph.add_node("UmSedrah", ["AlZulfi", "Shakra"])
self.graph.add_node("AlRass", ["Al-Badai"])
self.graph.add_node("Dhalfa", ["Sheehyah", "Mulaida"])
self.graph.add_node("Shakra", ["UmSedrah"])
self.graph.add_node("Mulaida", ["Dhalfa"])
print("graph has been setup.")
def set_starting_city(self):
"""set the starting city as a string"""
cities = self.graph.get_all_nodes()
print("Choose a city number to start with:" + "\n")
self.start_city = cities[get_user_choice(cities)]
print("you will start at", self.start_city, "city")
def set_target_city(self):
"""set the starting city as a string"""
cities = self.graph.get_all_nodes()
print("Choose a city number as a target:" + "\n")
self.target_city = cities[get_user_choice(cities)]
print("your target city is", self.target_city, "city")
def depth_first_search(self):
"""travel form start_city to target_city from left to right while logging the traveled cities"""
visited_cities = []
print("----------Depth First Search Traverse-------------")
self.stack.unique_push(self.start_city)
while not self.stack.is_empty():
current_city = self.stack.pop()
visited_cities.append(current_city)
print("I am at", current_city, "city")
self.stack.display()
print("Visited cities are:", visited_cities)
if current_city is self.target_city:
print("I have reached the target city")
break
else:
children_of_city = self.graph.get_children_of_node(current_city)
print("The children cities are:", children_of_city)
for city in children_of_city:
# push to stack if not visited and not in stack
if city not in visited_cities:
self.stack.unique_push(city)
# print(city, "has been added to stack")
self.stack.display()
print("-----------------------------------------")
FindRoute()
|
c51326e4f12b569efe2d768842fe1cd1df852cb6 | ASairithwikmahateja/cspp-1-assignment | /Problem Set 1/ps4a.py | 5,899 | 3.984375 | 4 | # The 6.00 Word Game
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3,
'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10}
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
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')
# wordList: list of strings
wordList = []
for line in inFile:
wordList.append(line.strip().lower())
print(" ", len(wordList), "words loaded.")
return wordList
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
#
# Problem #1: Scoring a word
#
def getWordScore(word, n):
sum_1 = 0
SCRABBLE_LETTER_VALUES = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2,
'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1,'m': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10,
'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10}
len_1 = len(word)
for i in word:
if i in SCRABBLE_LETTER_VALUES.keys():
sum_1 = sum_1+SCRABBLE_LETTER_VALUES[i]
sum_1 = sum_1*len_1
if len_1 == n:
sum_1 = sum_1+50
return sum_1
#
# Problem #2: Make sure you understand how this function works and what it does!
#
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print() # print an empty line
#
# Problem #2: Make sure you understand how this function works and what it does!
#
def dealHand(n):
"""
Returns a random hand containing n lowercase letters.
At least n/3 the letters in the hand should be VOWELS.
Hands are represented as dictionaries. The keys are
letters and the values are the number of times the
particular letter is repeated in that hand.
n: int >= 0
returns: dictionary (string -> int)
"""
hand={}
numVowels = n // 3
for i in range(numVowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(numVowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
return hand
#
# Problem #2: Update a hand by removing letters
#
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
new_hand = dict(hand)
for i in word:
if i in new_hand.keys():
new_hand[i] -= 1
return new_hand
#
# Problem #3: Test word validity
#
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
if word_1 not in word_list:
return False
for i_1 in word_1:
if i_1 not in hand_1.keys():
return False
return True
#
# Problem #4: Playing a hand
#
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
sum_1 = 0
for i_1 in hand_1.keys():
sum_1 = sum_1 + hand_1[i_1]
return sum_1
def playHand(hand, wordList, n):
print(displayHand(hand))
for i in len(hand):
if (i is not isValidWord()):
print("Enter a valid word or .")
user_input = input("Enter a valid word")
elif (i is isValidWord()):
return updateHand(hand)
return getWordScore(hand)
user_input = input("Enter another word")
#
# Problem #5: Playing a game
#
def playGame(wordList):
"""
Allow the user to play an arbitrary number of hands.
"""
user_input = input("Enter 'n'(new_hand) or 'r'(last hand) or 'e'(exit)")
# * If the user inputs 'n', let the user play a new (random) hand.
if(user_input == "n"):
dealHand(HAND_SIZE)
# * If the user inputs 'r', let the user play the last hand again.
elif(user_input == "r"):
playHand(hand, wordList, HAND_SIZE)
# * If the user inputs 'e', exit the game.
elif(user_input == "e"):
exit()
# * If the user inputs anything else, tell them their input was invalid.
else:
print("invalid input")
"""
2) When done playing the hand, repeat from step 1
"""
#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
wordList = loadWords()
playGame(wordList)
|
d22298e9f7b0ac53429f54d993bf68c7f1458177 | XinyuYun/cs1026-labs | /lesson7/task3/task.py | 282 | 3.53125 | 4 | # Replace the placeholders and complete the Python program.
f = open("filmdata.csv","r",encoding="utf-8")
for Process each line in the file:
entries = Split into separate items
if Test to see if year is earlier than 1990:
print(Print year and film title)
f.close()
|
6f06f653a5f61dbf56d93ae954ca2826a1698b79 | BrianFs04/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 389 | 4.03125 | 4 | #!/usr/bin/python3
"""minOperations"""
def minOperations(n):
"""Calculates the fewest number of operations
needed to result in exactly n H characters"""
if not n or n < 2:
return 0
mov = 0
min_op = 2
while min_op <= n:
if n % min_op == 0:
mov += min_op
n = n // min_op
else:
min_op += 1
return mov
|
699b0f610d110fc9d702b3d3344a4eaf873d6e30 | Evegen55/study_Python | /src/exercise9_4.py | 1,257 | 3.703125 | 4 | """
9.4 Write a program to read through the mbox-short.txt and figure out who has the sent
the greatest number of mail messages. The program looks for 'From ' lines and takes
the second word of those lines as the person who sent the mail. The program creates
a Python dictionary that maps the sender's mail address to a count of the number of times
they appear in the file. After the dictionary is produced, the program reads through
the dictionary using a maximum loop to find the most prolific committer.
"""
#for python ver 2.7
name = raw_input("Enter file:")
if len(name) < 1 : name = "../data/mbox-short.txt"
handle = open(name)
d = dict()
count = 0
for line in handle:
splt = line.split()
if len(splt) == 0 : continue
#find a sender
if splt [0] != 'From' : continue
try:
fr = splt[1]
#test code
#print fr
if (not fr in d.keys()):
#test code
#print 'a'
d[fr] = 1
else:
d[fr] = d[fr] + 1
except:
print 'No data element at index sub-2'
continue
#test code
#print d
for k,v in d.items():
if v>count:
count = v
for k,v in d.items():
if v == count:
print k,v
|
dcada599b49dfdc8659ad50e9579dde372bea696 | RomanPutsilouski/M-PT1-37-21 | /Tasks/Sushchynskiy_Tasks/Task6/Task6_module.py | 1,619 | 3.5 | 4 | priority = {"(": 0, ")": 0, "+": 1, "-": 1, "*": 2, "/": 2}
stack_numb = []
stack_oper = []
def calculate(last_oper):
global stack_numb
global stack_oper
x = stack_numb.pop()
y = stack_numb.pop()
if last_oper[-1] == "-":
return stack_numb.append(y - x), stack_oper.pop()
elif last_oper[-1] == "+":
return stack_numb.append(y + x), stack_oper.pop()
elif last_oper[-1] == "*":
return stack_numb.append(y * x), stack_oper.pop()
elif last_oper[-1] == "/":
return stack_numb.append(y / x), stack_oper.pop()
def main(math):
for idx,el in enumerate(math):
if el.isdigit():
if math[idx-1].isdigit() and idx != 0:
a = str(stack_numb.pop())
stack_numb.append(int(a+el))
else:
stack_numb.append(int(el))
elif el == "-" and (idx == 0 or math[idx-1] == "("):
stack_numb.append(-1)
stack_oper.append("*")
elif el == "(":
stack_oper.append(el)
elif el == ")":
while priority.get(stack_oper[-1]) != 0:
calculate(stack_oper[-1])
else:
if el == ")" and stack_oper[-1] == "(":
stack_oper.pop()
elif stack_oper == []:
stack_oper.append(el)
elif stack_oper:
while stack_oper and priority.get(el) <= priority.get(stack_oper[-1]) and len(stack_numb) >= 2:
calculate(stack_oper[-1])
stack_oper.append(el)
while stack_oper:
calculate(stack_oper[-1])
return stack_numb[0] |
b20d05b425553cd7f82163084404e2ef0bbe77db | akshaysmin/IV-plotter | /FuncAnimation.py | 465 | 3.828125 | 4 | import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animateFunc(i):
print(i)
x = np.linspace(-10,10,i+1)
y = x**2
print(x[0],x[-1])
ax1.clear()
ax1.plot(x,y,x,y+2)
time.sleep(1)
i += 1
ani = animation.FuncAnimation(fig, animateFunc, interval = 100)#interval= milliseconds for refresh rate
plt.show()
|
8d982d0ca5f78890c3375bf1b573213234c7578a | grzeborz/codeme_pyth_adv | /zajecia02/iter02.py | 604 | 4.1875 | 4 | class EvenNumbers:
def __init__(self):
self.number = 0
def __next__(self):
self.number += 2
if self.number > 100: # najwyraźniej, nie chcemy liczb parzystych większych niż 100 :)
raise StopIteration
return self.number
def __iter__(self):
return self
if __name__ == '__main__':
numbers = EvenNumbers()
for number in numbers:
print(number)
numbers = EvenNumbers() # UWAGA! aby kod poniżej działał, należy stworzyć nowy iterator EvenNumbers
list_of_numbers = list(numbers)
print(list_of_numbers)
|
4506354df336fb3ee61b06656d9259094b69aa52 | RocKr96/Infosys-Training | /Day-1/20.py | 655 | 3.6875 | 4 | '''
Assignment 20: Iteration Control Structure – Debugging - Guided Activity
Objective: Given a real world problem, implement the logic and solve the problem using appropriate constructs (sequential, selection, iteration) using an object oriented programming language (Python)
Problem Description: The code given below is written to display all the even numbers between 50 and 80 (both inclusive). Debug the program to get the correct output.
developer:Aman Zadafiya
date & time: 10/12/2018 3:20 PM
'''
print("Even numbers between 50 to 80.")
for i in range(50,81):
if i%2==0:
print(i)
print("Using While loop.")
while i>=50:
if i%2==0:
print(i)
i-=2
|
8cb70055135d5d0700e528c02ca0d2857659abe8 | joybree/leetcode | /Two Sum/twosum.py | 1,353 | 3.5625 | 4 | class Solution:
"""
##Bruce Force
"""
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
nums_sorted = sorted(nums)
#print(nums_sorted)
part1_list = list(filter(lambda x:x < target/2, nums_sorted))
part2_list = list(filter(lambda x:x >= target/2, nums_sorted))
indices = []
#print(part1_list)
#print(part2_list)
indices_equal = [indice for indice,value in enumerate(nums) if value == target/2]
#print(indices_equal)
if len(indices_equal) ==2:
return indices_equal
else:
for item in part1_list:
val1 = target - item
if val1 in part2_list:
indices = [nums.index(item),nums.index(val1)]
return indices
"""
##Hash Function
"""
def twoSum1(self, nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
if __name__ == "__main__":
Solution1 = Solution()
indices = Solution1.twoSum1([-3,-6,3,3,-90], 6)
print(indices) |
155e3d6345b6a16844e2daf522d5aabda236ad95 | saarangbond/Python-Projects | /Functions/2/function1.py | 152 | 3.5 | 4 |
total = 0
##variable number of arguments
def sum(*args):
global total
for i in args:
total += i
print(total)
sum(10, 30, 40, 70, 7)
|
b6fb2b47505aa0bb9ef53bcc32951f8a47e0a685 | ChandraSiva11/sony-presamplecode | /tasks/final_tasks/dictionary/7.remove_dict.py | 207 | 4.15625 | 4 | # Python Program to Remove the Given Key from a Dictionary
def main():
dict_ = {'a' : 'aaaa', 'b' : 'bbbb', 'c' : 'cccc'}
rm_key = 'a'
del dict_[rm_key]
print(dict_)
if __name__ == '__main__':
main() |
3354bc3d05df31dab230fc80fb4a732b0c404396 | yanfriend/python-practice | /licode/perm2.py | 1,425 | 3.609375 | 4 | import copy
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ret=[]
nums.sort()
self.perm(ret,nums,0)
return ret
def perm(self,ret, nums, ind):
if ind==len(nums)-1:
ret.append(nums)
return
for i in range(ind,len(nums)):
if i!=ind and (nums[i]==nums[ind]): continue
nums[ind],nums[i]=nums[i],nums[ind]
self.perm(ret, copy.deepcopy(nums), ind+1) # python, and c++ vector are diff.
class Solution2(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ret=[]
nums.sort()
self.perm(ret,nums,0)
return ret
def perm(self,ret, nums, ind):
if ind==len(nums)-1:
ret.append(copy.deepcopy(nums))
return
for i in range(ind,len(nums)):
if i!=ind and (nums[i]==nums[ind]): continue
nums[ind],nums[i]=nums[i],nums[ind]
self.perm(ret, nums, ind+1) # python, and c++ vector are diff.
nums[ind],nums[i]=nums[i],nums[ind]
l1=[1,1,2]
l2=[1,1,2,2]
l3=[1,2,2,3]
# print Solution().permuteUnique(l2)
# print Solution2().permuteUnique(l2) # not work
print Solution().permuteUnique(l3)
print Solution2().permuteUnique(l3) # not work
|
ebc3e9911aec8dc097375e6dce4e32fc2a51819b | iforaa/volksmundbot | /main.py | 8,016 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
"""
This Bot uses the Updater class to handle the bot.
First, a few callback functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Example of a bot-user conversation using ConversationHandler.
Send /start to initiate the conversation.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from telegram import ReplyKeyboardMarkup
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
ConversationHandler)
import states
import logging
import constants
from time import sleep
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
AW_COMMAND, AW_POLL_QUESTION, AW_POLL_ANSWER, AW_CHOOSING_RATE, AW_RATE_NEXT_OR_BACK, AW_RANKING = range(6)
RP_COMMAND_CREATE = "Create Poll"
RP_COMMAND_RATE = "Rate"
RP_COMMANT_BACK = "Back"
RP_COMMAND_NEXT_WORD = "Next Word"
RP_WELCOME = "Welcome! I'm Volksmund Bot. Let's be creative and find new german words for anglicisms. What do you want to do?"
"Let's start a new open case. Send me word you want to change"
reply_keyboard = [[RP_COMMAND_CREATE, RP_COMMAND_RATE],
["Done"]]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
rate_reply_keyboard = [["1", "2", "3"],["4", "5"],['Done']]
rate_markup = ReplyKeyboardMarkup(rate_reply_keyboard, one_time_keyboard=True)
def keys(bot, update):
update.message.reply_text(states.allKeys())
def keys(bot, update):
update.message.reply_text(states.showAnswers())
def clear(bot, update):
states.clearRedis()
def start(bot, update):
update.message.reply_text(
u"Welcome! I'm Volksmund Bot. Let's be creative and find new german words"
u"for anglicisms. What do you want to do?",
reply_markup=markup)
states.set_state(update.message.chat_id, AW_COMMAND)
def receiver(bot, update):
chat_id = update.message.chat_id
text = update.message.text
chat_state = int(states.get_state(chat_id))
if chat_state == AW_COMMAND:
if text == RP_COMMAND_CREATE:
poll_keyboard = [[RP_COMMANT_BACK]]
poll_markup = ReplyKeyboardMarkup(poll_keyboard, one_time_keyboard=False)
update.message.reply_text(
u"Let's start a new open case. Send me word you want to change",
reply_markup=poll_markup)
states.set_state(chat_id, AW_POLL_QUESTION)
elif text == RP_COMMAND_RATE:
states.set_state(chat_id, AW_CHOOSING_RATE)
question = states.get_random_question(chat_id)
if question is False:
update.message.reply_text("No words",
reply_markup=markup)
states.set_state(update.message.chat_id, AW_COMMAND)
else:
update.message.reply_text(u"Bad word: " + question,
reply_markup=rate_markup)
sleep(1)
update.message.reply_text("Variant: " + states.get_random_answer(chat_id))
# elif text == RP_COMMAND_RANKING:
# states.set_state(chat_id, AW_RANKING)
# ranking_keyboard = [[RP_COMMANT_BACK]]
# ranking_markup = ReplyKeyboardMarkup(ranking_keyboard, one_time_keyboard=True)
# update.message.reply_text(states.prepare_ranking(),
# reply_markup=ranking_markup)
elif chat_state == AW_POLL_QUESTION:
if text == RP_COMMANT_BACK:
update.message.reply_text(u"<<<",
reply_markup=markup)
states.set_state(chat_id, AW_COMMAND)
else:
update.message.reply_text(
u"Please send me the print answer option")
states.set_question(chat_id, text)
states.set_state(chat_id, AW_POLL_ANSWER)
elif chat_state == AW_POLL_ANSWER:
if text == RP_COMMANT_BACK:
update.message.reply_text(u"<<<",
reply_markup=markup)
states.set_state(chat_id, AW_COMMAND)
else:
states.add_answ_var(chat_id, text)
if states.get_answ_len(chat_id) < 4:
update.message.reply_text(
u"Please send me the print answer option")
else:
update.message.reply_text(u"Thank you!",
reply_markup=markup)
states.set_state(chat_id, AW_COMMAND)
elif chat_state == AW_CHOOSING_RATE:
if text.isdigit():
states.add_rate(chat_id, text)
answer = states.get_random_answer(chat_id)
if answer is None:
states.add_rated_question(chat_id)
states.set_state(chat_id, AW_RATE_NEXT_OR_BACK)
next_or_back_keyboard = [[RP_COMMANT_BACK, RP_COMMAND_NEXT_WORD]]
next_or_back_markup = ReplyKeyboardMarkup(next_or_back_keyboard, one_time_keyboard=True)
update.message.reply_text("?",
reply_markup=next_or_back_markup)
else:
update.message.reply_text("Variant: " + answer,
reply_markup=rate_markup)
else:
update.message.reply_text("Try again",
reply_markup=rate_markup)
elif chat_state == AW_RATE_NEXT_OR_BACK:
if text == RP_COMMANT_BACK:
states.set_state(chat_id, AW_COMMAND)
update.message.reply_text(
u"Welcome! I'm Volksmund Bot. Let's be creative and find new german words"
u"for anglicisms. What do you want to do?",
reply_markup=markup)
elif text == RP_COMMAND_NEXT_WORD:
states.set_state(chat_id, AW_CHOOSING_RATE)
question = states.get_random_question(chat_id)
if question is False:
update.message.reply_text("No words",
reply_markup=markup)
states.set_state(update.message.chat_id, AW_COMMAND)
else:
update.message.reply_text(u"Bad word: " + question,
reply_markup=rate_markup)
sleep(1)
update.message.reply_text("Variant: " + states.get_random_answer(chat_id))
elif chat_state == AW_RANKING:
if text == RP_COMMANT_BACK:
states.set_state(chat_id, AW_COMMAND)
update.message.reply_text(
u"Welcome! I'm Volksmund Bot. Let's be creative and find new german words"
u"for anglicisms. What do you want to do?",
reply_markup=markup)
def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
def main():
# Create the Updater and pass it your bot's token.
updater = Updater(constants.TELEGRAM_KEY)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("keys", keys))
dp.add_handler(CommandHandler("clear", clear))
dp.add_handler(MessageHandler(Filters.text, receiver))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until the you presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
|
0ae0752980aa25eb6c8524010017a40d924f06cc | KampfWut/CodeGeneratedDuringLearning | /Base Machine Learning/04_2FeaNormalEquation.py | 2,249 | 3.5 | 4 | # 04. 正规方程方法
# 徐进 2019.02.02
import math
import numpy as np
import scipy as sp
import random as rd
import matplotlib.pyplot as plt
import sympy as smp
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
# Step1. 生成数据
print("\n >>> Step 1 <<< \n")
origal_x = np.array(np.arange(200, 1800, 4))
origal_y = np.array(np.arange(50, 450, 1))
origal_z = 13 + 24 * origal_x + 43 * origal_y
m = len(origal_x)
x, y, z = [], [], []
for i in range(0, m):
if i % 3 == 0:
temp = origal_x[i] + rd.randint(-1000, 1000)
else:
temp = origal_x[i] + rd.randint(-200, 200)
x.append(temp)
for i in range(0, m):
if i % 3 == 0:
temp = origal_y[i] + rd.randint(-200, 200)
else:
temp = origal_y[i] + rd.randint(-50, 50)
y.append(temp)
for i in range(0, m):
if i % 3 == 0:
temp = origal_z[i] + rd.randint(-20000, 20000)
else:
temp = origal_z[i] + rd.randint(-5000, 5000)
z.append(temp)
# Output
print(">> Data: ")
print(" origal_x: {}".format(origal_x[1:10]))
print(" origal_y: {}".format(origal_y[1:10]))
print(" origal_z: {}".format(origal_z[1:10]))
print(" x: {}".format(x[1:10]))
print(" y: {}".format(y[1:10]))
print(" z: {}".format(z[1:10]))
fig = plt.figure(1)
ax = fig.gca(projection='3d')
plt.title("Data Plot")
surf = ax.scatter(x, y, z, "rx", label = "random data")
surf = ax.scatter(origal_x, origal_y, origal_z, "go", label = "origal data")
# Step.2 数据处理
print("\n >>> Step 2 <<< \n")
X = []
for i in range(0, m):
temp = [1]
temp.append(x[i])
temp.append(y[i])
X.append(temp)
X = np.matrix(X)
Y = np.matrix(z).T
# Step.3 计算
theta = (X.T * X).I * X.T * Y
# Output
print(">> Normal Equation Answer:")
print(" theta0: {}, theta1: {}, theta2: {}".format(theta[0, 0], theta[1, 0], theta[2, 0]))
print(" Function: z = {} + {}x + {}y".format(theta[0, 0], theta[1, 0], theta[2, 0]))
stepx = np.array(np.arange(-500, 2500, 1))
stepy = np.array(np.arange(-100, 650, 0.25))
ans = theta[0, 0] + theta[1, 0] * stepx + theta[2, 0] * stepy
surf = ax.plot(stepx, stepy, ans, "b-", label = "answer line")
plt.legend(loc='best')
plt.savefig("04_Fig1_DataPlot.pdf")
plt.show()
|
7d13ff90949b970ae59f161c4d79f23b6a6b5aaa | happy-yu1/PythonProjects | /第1章python基础/py_Python基础二/py_22字典函数.py | 1,005 | 3.765625 | 4 | t=('name','sex','age')
d1=dict.fromkeys(t)
print(d1)
d2=dict.fromkeys(t,'aaa') # 对d2中键对应的值进行统一赋值
print(d2)
d = {'name': 'zhang3', 'score': 34, 'age': 10}
# 以下两种方法均可以调出键对应的值,第二个比较常用
print(d['name'])
print(d.get('name'))
print('%s:%s' % ('name',d['name'])) # 同时输出键值对
print('-'*40)
dict = {'sex': 'zhang3', 'score': 34, 'age': 10}
print(dict.items())
for (k,v) in dict.items(): # 遍历dict中的每队键值对,并简单明了的输出(法一)
print('%s:%s' % (k,v))
for k in dict.keys(): # 输出所有的键(法一)
print(k)
print('-'*40)
for v in dict.values(): # 输出所有键对应的值
print(v)
for k in dict.keys(): # 输出所有的键值对(法二),不常用
print('%s:%s'% (k,dict[k]))
for k in dict: # 输出所有的键 (法二),因为键是唯一的,可以这样用,但是值不是唯一的,不可以这么用,必须加上.values()
print(k) |
42195281807b8284f4752d6242eef345595f0172 | DavidC117/prueba_python1 | /repetir.py | 244 | 3.734375 | 4 | a= input ("escribe:")
print ("tu palabra es:", a)
b=int (input ("escribe el caracter a visualizar(numerico)"))
print ("caracter:",a[b])
c=int (input("cuantas veces quieres que se imprima"))
d= a [b]
res=c*d
print (res)
input ("...")
|
907e822f2aa6c90b295e766bfc0b5c46b0d6abf0 | ChungViet/Homework | /Homework/homework11.py | 318 | 3.6875 | 4 | # Дана строка, состоящая из слов, разделенных пробелами. Определите, сколько в ней слов. Используйте для решения задачи функцию `count()`
s = input('enter smth')
print('слов в строке =',s.count(' ')+1)
|
535600a7d78777db352d0931a83676bbe5b03b81 | sharanya405/enigma | /reflector.py | 1,953 | 3.546875 | 4 | class Reflector:
# The name of the rotor.
_name = ""
# The permutation implemented by this rotor in its 0 position.
_permutation = None
# The setting of the rotor.
_setting = 0
# A rotor named NAME whose permuation in its default setting is PERM, and whose notches are at the positions indicated in NOTCHES. The Rotor is initially in its 0 setting (first character of its alphabet).
def __init__(self, name, perm, notches):
_name = name
_permutation = perm
_notches = notches
_setting = 0
# Return my name.
def name(self):
return self._name
# Return my alphabet.
def alphabet(self):
return self._permutation.alphabet()
# Return my permutation.
def permutation(self):
return self._permutation
# Return the size of my alphabet.
def size(self):
return self._permutation.size()
# Return true iff I have a ratchet and can move.
def rotates(self):
return False
# Return true iff I reflect.
def reflecting(self):
return True
# Return my current setting.
def setting(self):
return self._setting
# Set setting() to POSN.
def set(self, posn):
if self._setting == posn:
raise Exception("Reflector doesn't change positions")
# Set setting() to character CPOSN.
def setChar(self, cposn):
_setting= self._permutation.alphabet().toInt(cposn)
# Return the conversion of P (an integer in the range 0..size()-1) according to my permutation.
def convertForward(self, p):
p = self._permutation.permute(p + self._setting)
return self._permutation.wrap(p - self._setting)
# Return the conversion of E (an integer in the range 0..size()-1) according to the inverse of my permutation.
def convertBackward(self, e):
e = self._permutation.inverse(e + self._setting)
return self._permutation.wrap(e - self._setting)
def atNotch(self):
return False
# Advance me one position, if possible.
def advance(self):
pass |
1fd1d7f6688fb7ed5638a75ae119a0669df620de | fabionunesdeparis/Fundamentos-em-python3 | /exer009.py | 911 | 3.90625 | 4 | # @Fábio C. Nunes 04/05/2020
# Escreva um programa que leia um número inteiro qualquer e mostre na tela a sua tabuada.
valor = int(input('Digite um valor inteiro: '))
tab = 0
print('-' *12)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
tab = (tab+1)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
tab = (tab+1)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
tab = (tab+1)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
tab = (tab+1)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
tab = (tab+1)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
tab = (tab+1)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
tab = (tab+1)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
tab = (tab+1)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
tab = (tab+1)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
tab = (tab+1)
print('{} x {:2} = {}'.format(valor,tab,valor*tab))
print('-' *12)
|
5748998a5a570edbe587c15d4dee854849d5c0d4 | monnn/Zoo-Problem | /animal.py | 2,224 | 3.625 | 4 | import random
import json
class Animal(object):
DEAD_RATIO = 0.8
DEAD_CHANCE_RATIO = 0.8
LIFE_EXPECTANCIES = {'Snake': 12,
'Horse': 30,
'Wolf': 25,
'Tiger': 24,
'Bear': 40
}
AVERAGE_WEIGHTS = {'Snake': 65,
'Horse': 280,
'Wolf': 60,
'Tiger': 180,
'Bear': 400}
def __init__(self, species, name, age, gender, weight):
self.species = species
self.age = age
self.name = name
self.gender = gender
self.weight = weight
def can_eat(self):
if self.species in Animal.AVERAGE_WEIGHTS:
average_weight = Animal.AVERAGE_WEIGHTS[self.species]
if average_weight < self.weight:
return True
else:
return False
def grow(self):
self.age += 1
self.weight += self.weight * 0.1
def eat(self):
if self.can_eat():
self.weight += 0.5
else:
return
def chance_to_die(self):
if self.species in Animal.LIFE_EXPECTANCIES:
life_expectancy = Animal.LIFE_EXPECTANCIES[self.species]
return self.age / life_expectancy
def is_dead(self):
if self.chance_to_die() > Animal.DEAD_RATIO:
if random.random() > Animal.DEAD_CHANCE_RATIO:
return True
return False
def __str__(self):
return "{0}: {1} {2} months {3} kg".format(
self.name,
self.species,
self.age,
self.weight)
def load_config(self, file_name):
config = open(file_name, 'r')
data = json.loads(config.read())
config.close()
return data
# def jsonify(self, instance):
# fp = open('animals.json', 'a+')
# data = json.dumps(str(instance.__dict__), indent=4, sort_keys=True)
# fp.write(data)
# fp.close()
# a = Animal('Snake', 'Pesho', 12, 'male', 43)
# # print(a)
# # print(a.is_dead())
# data = a._load_config('config.json')
# print(eval(data['animals']))
|
ef905ee12cf9fbfd72350d646eba1478e6b04d03 | sowndarya1299/guvi | /codekata/basics/side-tri.py | 235 | 3.9375 | 4 | # Given 3 numbers A,B,C process and print 'yes' if they can form the sides of a triangle otherwise print 'no'
A, B,C = map(int, input().split())
if (A + B <= C) or (A + C <= B) or (B + C <= A) :
print("no")
else:
print("yes")
|
b70a43ab8773ce6ed45e524322f6dfaca9bc6058 | shaziya21/PYTHON | /brcopa.py | 752 | 4.09375 | 4 |
# using while loop
av = 5
x= int(input("how many candies you want?"))
i=1
while i<=x:
if i>av:
print("out of stock")
break
print("candy")
i+=1
# using for loop
t=5
x=int(input("how many candies you want?"))
for i in range(0,x):
if i<t:
print('candy')
else:
print('out of stock')
break
continue will not jum out of the loop it will only skip the remaining statements.
for i in range(1,101):
if i%3==0:
continue
print(i)
print('bye')
# using pass will execute the statement without any condition.
for i in range(1,101):
if i%2!=0:
pass
else:
print(i)
# QUES1: Print first 50 fibonacci numbers.
#
# Ques2: Check a given number is prime or not.
|
ed56c1351c4602482b26e15df036ab3c775cb522 | stronger-jian/learn_python3 | /python/eleven/e1.py | 525 | 3.84375 | 4 | '''
枚举:描述类型
'''
from enum import Enum
class VIP(Enum):
YELLOW=1
# YELLOW=2
GREEN=1
BLACK=3
# for x in VIP:
# print(x)
print(VIP.GREEN)#此时 YELLOW 和 GREEN 的值相等 会输出YELLOW,会把GREEN看做YELLOW别名
# print(type(VIP.YELLOW.value))
# print(type(VIP.YELLOW.name))
# print(type(VIP.YELLOW))
# print(VIP['YELLOW'])
# print(type(VIP['YELLOW']))
# VIP.YELLOW=10
#普通类 的变量可以的更改,python 没有真正的常量
class Common():
YELLOW=1
|
e107ed9c5ca165cd69286ba0667d16b2c9d1c052 | martk4/btw2102 | /Aufgaben/l03-02_das_kleine_EinMalEins.py | 106 | 3.578125 | 4 | for i in range(1,7):
for x in range (1,7):
print(x*i, end= "\t")
print()
|
48e27047c8d06913d7f2047ee3d98ad467add03f | feberhardt/TextMining | /python text_mining.py | 3,472 | 3.671875 | 4 | import requests
import re, math
from collections import Counter
from operator import itemgetter
import operator
def text_preprocessing(text):
"""Check if the the input is a string or pathfile. convert it to string
>>> text_preprocessing(4)
>>> text_preprocessing('4')
'4'
"""
if isinstance(text, str):
if text.endswith('.txt'):
path = text
text = open(path,'r')
return text.read()
else:
return text
else:
return None
def word_counter(text):
"""return a list with word frequencies
>>>
"""
word = re.compile(r'\w+')
text = text_preprocessing(text)
words = word.findall(text)
wordcount = Counter(words)
return wordcount
def word_frequency(text):
"""Take a string, count the word frequencies in it and display it in a descending order
>>> word_frequency('text text hello text python')
[('text', 3), ('hello', 1), ('python', 1)]
"""
text = text.lower() # Preprocessor: all lower case letters
word_frequency = word_counter(text) #Calling the function
return sorted(word_frequency.items(), key=lambda pair: pair[1], reverse=True)
def cosine(vec1, vec2):
""" Calculate the cosine between two vectors, used as a measurment of similarity
"""
intersection = set(vec1.keys()) & set(vec2.keys())
numerator = sum([vec1[x] * vec2[x] for x in intersection])
sum1 = sum([vec1[x]**2 for x in vec1.keys()])
sum2 = sum([vec2[x]**2 for x in vec2.keys()])
denominator = math.sqrt(sum1) * math.sqrt(sum2)
# Check if denominator is any kind of zero, empty container or False
if denominator is not None:
return float(numerator) / denominator
else:
return 0.0
def Cosine_similarity(text_1, text_2):
"""find similarities between two text files, by looking at the number of word usage
>>> Cosine_similarity('This is a test.', 'This is the second test.')
0.6708203932499369
"""
# WORD = re.compile(r'\w+')
# transform the two input strings into a vector
vector_1 = word_counter(text_1)
vector_2 = word_counter(text_2)
return cosine(vector_1, vector_2)
def listmaker(*texts):
"""Make a list that gets iterated in the Text_similarity function
>>> listmaker('a', 'c', 'y', 'x', 'gfhj')
['a', 'c', 'y', 'x', 'gfhj']
"""
text_list=[]
for a in texts:
text_list.append(text_preprocessing(a))
return text_list
def Text_similarity(*texts):
"""compare an indefinite number of texts with each other
>>> Text_similarity('This is the first test', 'This is the second test, what a Test. One more Test', 'This is the firs test')
[[0.9999999999999998, 0.49613893835683387, 0.7999999999999998], [0.49613893835683387, 1.0000000000000002, 0.49613893835683387], [0.7999999999999998, 0.49613893835683387, 0.9999999999999998]]
"""
# print(*texts)
# Loop through list of Texts
text = listmaker(*texts)
sims1 =[]
for p in range(len(text)):
sims2 =[]
for i in range(len(text)):
sim = Cosine_similarity(text[p], text[i])
sims2.append(float("{0:.2f}".format(sim)))
sims1.append(sims2)
return sims1
def final_function():
"""sum the program up and uses every .txt file in the folder """
from os import listdir
a = listdir()
a = tuple(f for f in a if ".txt" in f)
return Text_similarity(*a)
final_function()
|
cff641ca43235bb38f3a587168c67c61ca2c9b46 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/MaximalSquare2.py | 872 | 3.625 | 4 | from typing import List
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
def getWidth(num):
w = 0
while num > 0:
num &= num << 1
w += 1
return w
if not matrix:
return 0
nums = [int(''.join(n), base=2) for n in matrix]
n = len(nums)
result = 0
for i in range(n):
temp = nums[i]
for j in range(i, n):
temp &= nums[j]
if getWidth(temp) < j - i + 1:
break
result = max(result, j - i + 1)
return result ** 2
if __name__ == "__main__":
n = int(input())
matrix = []
for i in range(n):
matrix.append([ch for ch in input().split()])
solution = Solution()
print(solution.maximalSquare(matrix)) |
ca97353979ccec598c593131c5b22e1df12d1a74 | sohnryang/has-informatics | /coin_exchange.py | 360 | 3.59375 | 4 | money = int(input())
coins = [0] * 4
print('money to exchange: %d won' % money)
coins[0] = money // 500
money %= 500
coins[1] = money // 100
money %= 100
coins[2] = money // 50
money %= 50
coins[3] = money // 10
money %= 10
for (val, coin) in zip([500, 100, 50, 10], coins):
print('coin of %d won: %d' % (val, coin))
print('change left: %d won' % money)
|
ac4d5ea471ceb222c9fa48fa72b95f1d4f39c4ab | erija952/project-euler | /python/p20/p20.py | 198 | 3.578125 | 4 | #!/usr/bin/python
mysum = 1
for i in range(1,100) :
mysum = mysum * i
strsum= str(mysum)
print "Factorial is " + strsum
res = sum(map(int, strsum))
print "Sum of digitsis " + str(res)
|
5374bb2cf34494b8b9ea301445be76a5525243b8 | lorenmanu/variado | /python_basico-master/33_jesusgonzaleznovez.py | 215 | 3.84375 | 4 | #!/usr/bin/python
palabra = "inicio"
lista = []
while palabra != "Basta" and palabra != "":
palabra = raw_input("Introduzca palabra:")
if palabra != "Basta" and palabra != "":
lista.append(palabra)
print lista
|
a0ed5451838a79d9496eccd8dba514bff6bbf053 | Chih-YunW/LeapYearTesting | /unittest_leapYear.py | 494 | 3.640625 | 4 | import unittest
import leapYear
class testLeapYear(unittest.TestCase):
def test_is_a_leapYear(self):
self.assertEqual(leapYear.leapYear(2000), "It is a leap year")
def test_not_a_leapYear(self):
self.assertEqual(leapYear.leapYear(1999), "It is not a leap year")
def test_type_error(self):
self.assertRaises(TypeError, leapYear.leapYear, "dog") #invalid type of input
if __name__ == '__main__':
unittest.main()
|
d027b1a8d51384896d34e03600544ada24e807ea | senandtihiro/asyncio_demo | /loop_test.py | 2,446 | 3.609375 | 4 | '''
高并发模式编程中具备的三个要素
事件循环 + 回调(驱动生成器) + IO多路复用(epoll)
asyncio是python用于解决异步io编程的一整套解决方案
tornado实现了web服务器(完成了socket编码,可以直接部署)
但是有一点需要特别需要注意的是,在使用数据库驱动的时候,不能使用平常使用到的传统的阻塞IO驱动
'''
import asyncio
import time
from functools import partial
async def get_html(url):
'''
这是一个协程,需要注意的是协程必须要搭配事件循环一起使用
:param url:
:return:
'''
print('start get url')
# 注意,这里不能简单地使用python自带的time.sleep()函数,因为python的sleep是同步阻塞的接口
# 这样写的话,跟顺序写是同样的慢
# time.sleep(2)
# 这是一个耗时的操作,等待它执行完成需要加await
# asyncio.sleep(2)
# await后面必须跟的是一个awaitable的对象(协程就是awaitable的对象)
# await time.sleep()
# asyncio.sleep(2)
print('stop get url')
def callback(url, future):
'''
带参数的回调函数
:param url:
:param future:
:return:
'''
print('call back function, url:', url)
def main():
start_time = time.time()
# loop可以理解为一个心脏,它不停地调度函数并执行,是单线程模式
# 如果在协程中写了阻塞的代码,一个地方阻塞了,其他的代码都运行不了
# 如何获取协程的返回值呢?
loop = asyncio.get_event_loop()
# 这种task的用法和下面的future的用法是一样的
task = loop.create_task(get_html('www.baidu.com'))
# 还可以为任务添加回调
task.add_done_callback(partial(callback, 'www.baidu.com'))
loop.run_until_complete(task)
print(task.result())
# _future = asyncio.ensure_future(get_html('www.baidu.com'))
# loop.run_until_complete(_future)
# print(_future.result())
# gather与wait的区别
# gather是比wait更高层次的抽象,使用起来也更加灵活
group1 = [get_html('g.cn') for i in range(2)]
group2 = [get_html('g.cn') for i in range(2)]
group1 = asyncio.gather(*group1)
group2 = asyncio.gather(*group2)
# group1.cancel()
loop.run_until_complete(asyncio.gather(group1, group2))
print(time.time() - start_time)
if __name__ == '__main__':
main() |
d8343ab40bd5bcfc2d827be99357f7ed5da7d5da | SinduMP/Daspro | /Jobsheet7_datakaryawan.py | 1,572 | 3.65625 | 4 | #class color
class color:
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
# fungsi,rumus data
def rumus():
global anak,gajipokok,gajikotor,persen,jumlahanak,hitunganak,gaji
hitunganak = 100000
anak = jumlahanak * hitunganak
gajikotor = gajipokok + anak
persen = (gajikotor * 5) / 100
gaji = gajikotor - persen
def kesejahteraan():
global keadaan
if gaji > 2000000:
keadaan =("Sejahtera")
else :
keadaan =("Belum Sejahtera")
def cetak ():
print("Jabatan :",jabatan)
print("Gaji : Rp.",gaji)
print("Keadaan :",keadaan)
print('')
#Memasukkan data karyawan
print("==================")
print(color.BOLD + color.BLUE +"PT. POLINES JAYA" + color.END)
print(color.BOLD + color.GREEN + "Data Karyawan" + color.END)
print("==================")
print('')
print(color.BOLD + "Masukkan data :" + color.END)
nama =(input("Nama : "))
#jabatan:
#1. Direktur = Rp.8000000
#2. Supervisor = Rp.4000000
#3. Operator = Rp.2000000
#4. Lainnya = Rp.2000000
golongan =int(input("golongan : "))
jumlahanak =int(input("Jumlah anak( jika tidak punya: 0 ) : "))
if golongan == 1:
jabatan ="Direktur"
gajipokok = 8000000
rumus()
kesejahteraan()
cetak()
elif golongan == 2:
jabatan ="Supervisor"
gajipokok = 4000000
rumus()
kesejahteraan()
cetak()
elif golongan == 3:
jabatan ="Operator"
gajipokok = 2000000
rumus()
kesejahteraan()
cetak()
else:
jabatan ="Karyawan"
gajipokok == 2000000
rumus()
kesejahteraan()
cetak()
|
724178c67b65b28466d63b550ad3dba1a7f647c5 | 5thCorner/WebScraper | /Problems/Healthy Habits/main.py | 149 | 3.546875 | 4 | for i in range(len(walks)):
if i == 0:
res = walks[i]['distance']
else:
res += walks[i]['distance']
print(res // len(walks))
|
76f10126a36f27d1b65debfbbf363e13154d8b02 | MonicaLeonor/Preparcial | /clave_x.py | 564 | 3.890625 | 4 | import math
#Ejercicio 1
def suma():
numero1 = 2
numero2 = 4
suma = numero1 + numero2
return suma
#Ejercicio 2
def multiplicacion():
numero1 = 2
numero2 = 4
numero3 = 5
multiplicacion = numero1*numero2*numero3
return multiplicacion
# Ejercicio 3
def sumarLista():
numerosLista = [2,5,4,6,9,12]
sumaLista = 0
for numberos in numerosLista:
sumaLista = sumaLista + numberos
return sumaLista
# Ejercicio 4 github url-->
def getGithubUrl():
return "https://github.com/MonicaLeonor/Preparcial.git"
|
4ddd2d32a5776b570ace348cd6564e6671569672 | kjjeong104/MD_kjjeong | /py_development/data_process/math/sphere_generation_v01.py | 629 | 3.75 | 4 | #!/usr/bin/env python3
#spherical surface point generation
import math
import numpy as np
def generate_sphere_points(n_points):
inc = math.pi * (3.0 - np.sqrt(5.0))
offset = 2.0 / float(n_points)
sphere_points = np.empty((n_points,3),dtype=np.float32)
for i in range(n_points):
y = i*offset - 1.0 + (offset / 2.0)
r = np.sqrt(1.0 - y*y)
phi = i * inc
sphere_points[i] = np.array([math.cos(phi) * r, y, math.sin(phi) * r], dtype=np.float32)
return sphere_points
sphere_points=generate_sphere_points(100)
for row in sphere_points:
print('X {:8.3f} {:8.3f} {:8.3f}'.format(row[0],row[1],row[2]))
|
b2865beffeb59d2a0917aeb7860a226a7ebdfb6e | urianchang/DojoAssignments | /Python/Python/funwithfunctions.py | 1,401 | 4.34375 | 4 | # Fun with Functions
'''
Odd/Even:
Create a function called odd_even that counts from 1 to 2000.
As your loop executes, have your program print the number of that
iteration and specify whether it's an odd or even number.
'''
def odd_even(start, stop):
for num in range(start, stop+1):
if (num%2 == 0):
print "Number is " + str(num) + ". This is an even number."
else:
print "Number is " + str(num) + ". This is an odd number."
#odd_even(1, 2000)
'''
Multiply:
Create a function called multiply that iterates through each value in a list
and returns a list where each value has been multiplied by 5. The function should
multiply each value in the list by the second argument.
'''
def multiply(arr, num):
newarr = []
for val in arr:
newarr.append(val*num)
return newarr
a = [2, 4, 10, 16]
# b = multiply(a, 5)
# print b
'''
Hacker Challenge:
Write a function that takes the multiply function call as an argument.
Your new function should return the multiplied list as a two-dimensional list.
Each internal list should contain as many ones as the number in the original list.
'''
def layered_multiples(arr):
arr1 = []
arr2 = []
for num in arr:
for digit in range(1, num+1):
arr1.append(1)
arr2.append(arr1)
arr1 = []
return arr2
x = layered_multiples(multiply([2, 4, 5], 3))
print x
|
6c6685ac3adcbcd7ec9b6bba2e702a3de29df570 | kristindubrule/DojoAssignments | /Python/type_list.py | 710 | 4.21875 | 4 | def printList(arr):
newStr = ""
sum = 0
hasNumbers = 0
hasStrings = 0
listType = ""
for val in arr:
if isinstance(val,str):
newStr += val + " "
hasStrings = 1
elif isinstance(val,int) or isinstance(val,float):
sum += val
hasNumbers = 1
if hasNumbers:
print "Number", sum
listType = "numbers"
if hasStrings:
newStr = newStr[:-1]
print "String", newStr
listType = "strings"
if hasNumbers + hasStrings == 2:
listType = "mixed"
print "The list you entered is of {} type.".format(listType)
#input
l = ['magical unicorns',19,'hello',98.98,'world']
#output
printList(l)
# input
l = [2,3,1,7,4,12]
#output
printList(l)
# input
l = ['magical','unicorns']
#output
printList(l)
|
22bdc0b9491aa5e4f77780da11accf356a2cfb6a | mackorone/euler | /src/062.py | 361 | 3.671875 | 4 | from collections import defaultdict
from itertools import count
def ans():
groups = defaultdict(list)
for num in count():
num_cubed = num ** 3
key = tuple(sorted(str(num_cubed)))
groups[key].append(num_cubed)
if len(groups[key]) == 5:
return groups[key][0]
if __name__ == '__main__':
print(ans())
|
6254274e77671f4621c9f6c4735bcd02c1212e87 | Gizmotronn/python-learning | /Applets/impractical-projects/14. Mars Orbiter/marsorbiter.py | 12,550 | 3.703125 | 4 | # Program Contents:
"""
Lines 8-11: Pip Imports
Lines 13-17: Colour Codes/Colour Table
Lines 19- : Satellite Class & Initialization Method
"""
import os # importing the following packages/python modules; pygame is installed via pip. // Game launches in full screen, but there are options to escape (esc key) to a window. // The "OS" module allows the player to control the window after the "esc" key is pressed
import math # For gravity and trigonometric functions/calculations
import random # to start the satellite off with a random position and velocity
import pygame as pg
WHITE = (255, 255, 255) # sets colour code for white variable (hex code) - 255, 255, 255 = white
BLACK = (0, 0, 0) # sets the colour code for black to 0, 0, 0
RED = (255, 0, 0)
GREEN = (0, 255, 0)
LT_BLUE = (173, 216, 230)
class Satellite(pg.sprite.Sprite): # creates a class object - Satellite Object // Uses pygame (pg, see importing modules) to create a sprite - using the pg.sprite.Sprite function // Defines class object.
# Satellite object // Rotates to face planet // Crashses & Burns - nostarch.com
# It is passed through pygame (pg) so that any object in this class will be sprites
def __int__(self, background): # initializes object
super().__init__()
self.background = background # needs to pass the class a background object
self.image_sat = pg.image.load("satellite.png").convert() # uses pygame to load the "satellites.png" img file in this directory by using pg.image.load, and sets the image_sat (image of satellite) to this
self.image_crash = pg.image.load("satellite_crash_40x33.png").convert() # // And converts it "//" continuing on from above line comments // Convert function converts image into a graphic format that pygame can run efficiently when the game loop starts
self.image = self.image_sat
self.rect = self.image.get_rect()
self.image.set_colorkey(BLACK) # sets transparent colour - colour hex code (0, 0, 0) - defined in Colour Codes/Colour Table (see Program Contents)
self.x = random.randrange(315, 425) # sets the x coordinate of the object (using random py module) to anywhere in the range of x = 315-425
self.y = random.randrange(70,180) # does the same thing as above line, just with the y-axis
self.dx = random.choice([-3, 3]) # Randomly sets the velocity of the class object to -3, 3 (x) // Neg values (-) - counter/anticlockwise orbit // Pos values (+/ ) - clockwise orbit
self.dy = 0 # delta y. // Eventually the gravity module (import section) will establish dy values
self.heading = 0 # initialises satellite's dish orientation // Satellite dish should always point towards Mars // This needs to overcome inertia (more to come for this)
self.fuel = 100
self.mass = 1
self.distance = 0 # initialises distance between satellite object and planet
self.thrust = pg.mixer.Sound('thurst_audio.ogg') # uses pygame(pg).mixer.Sound to use the "thrust_audio.ogg" sound file as the file of choice for self.thrust function // It is in .ogg rather than .mp3/other format because .ogg works well with python and pygame
self.thrust.set_volume(0.07) # Sets the volume of the audio file (above line) to 7% (0.07) // 1 = 100%, 0 = 0%
def thruster(self, dx, dy): # defines thruster function for the Satellite class object
self.xd += dx # sets the value for delta x for the thruster object
self.dy += dy
self.fuel -= 2 # when thruster is used, empties the fuel tank of the satellite slightly // thruster function in satellite class object // fuel function
self.thrust.play() # makes the hissing sound // Call play() method
def check_keys(self): # takes self as an argument // defines check_keys (like getKeyDown in Unity/C#) function
keys = pg.key.get_pressed() # uses pygame to detect which key was pressed, sends this to the keys variable
# Firing thrusters
if keys[pg.K_RIGHT]: # if key pressed call thruster() method/function, pass it some dx and dy values (see below). // this is the same for the elifs in this block as well
self.thruster(dx=0.05, dy=0) # sets what happens if right arrow is pressed - dx is change by +0.05, dy (delta y) is still set to 0 (initialized value)
elif keys[pg.K_LEFT]: # uses pygame (pg)
self.thruster(dx=-0.05, dy = 0)
elif keys[pg.K_UP]:
self.thruster(dx=0, dy=-0.05)
elif keys[pg.K_DOWN]:
self.thruster(dx=0, dy=0.05)
# Locating the Satellite
def locate(self, planet): # defines locate function/method for self, and planet // Self refers to the Satellite // Locating the satellite - calculates the distance of the satellite from the planet // Then determines the heading for pointing the dish at the planet // The locate mmethod needs to be passed the satellite (self) and the planet objects
px, py = planet.x, planet.y # for determining the distance between the planet and self objects in space (next 2 lines)
dist_x = self.x - px # the distance (x-coord) is the x coord of the self minus the coord of the planet's x
dist_y = self.y - py # same thing as above line
# getting direction to planet to point the dish of the satellite
planet_dir_radians = math.atan2(dist_x, dist_y) # calculate angle between the satellite's heading and the planet // So that you can rotate the satellite dish towards the planet
self.heading = planet_dir_radians * 180 / math.pi
self.heading -=90 # sprite is travelling tail first // In pygame, the front of a sprite is to the east (default) - self object is orbiting planet object tail-first // You need to subtract 90 degrees from the heading for the dish to point towards the planet object (Mars) - neg angles return clockwise rotation in pygame of objects (in this case self)
self.distance = math.hypot(dist_x, dist_y) # uses math's module - hypotunese function - to calculate the distance // Get the Euclidian distance between both objects
# Rotating the satellite and drawing its orbit
def rotate(self): # pygame - rotate self game object by passing it the rotate(self): method
# Rotates satellite using degrees so the dish faces the planet
self.image = pg.transform.rotate(self.image_sat, self.heading) # the self.image function is equal/set to pygame rotating (a transformation - maths) the image_sat of self, and the heading of the self object // Rotates the IMAGE of the satellite (which is part of the self object)
self.rect = self.image.get_rect() # end the function be getting the transformed image's rect object
# Update satellite's position & draw line to face orbital path
last_center = (self.x, self.y)
self.x += self.dx # sets the x coordinate of the self object using delta (physics)
self.y += self.xy # delta y/delta x (above line)
pg.draw.line(self.background, WHITE, last_center, (self.x, self.y)) # the orbital line/path
# Updating the Satellite object
def update(self): # update satellite object during the game
self.check_keys()
self.rotate()
self.path()
self.rect.center = (self.x, self.y)
# Change image to fiery red if in atmosphere of planet (Mars)
if self.dx == 0 and self.dy == 0: # delta - so not moving
self.image = self.image_crash # changes the image of self game object
self.image.set_colorkey(BLACK)
# Defining the Planet Class Initialization Method // Creating planet game object
class Planet(pg.sprite.Sprite): # Planet object that rotates, projects/creates gravity/gravitational field (higgs - physics)
def __init__(self): # defines initialization method for self game object (right now, it is the planet, as we are in the Planet class object)
super().__init()
self.image_mars = pg.image.load("mars.png").convert # sets the image of the object to an image in this directory
self.image_water = pg.image.load("mars_water.png").convert()
self.image_copy.set_colorkey(BLACK)
self.rect = self.image_copy.get_rect()
self.image = self.image_copy # see initialization of satellite game object
self.mass = 2000 # planet object is 2000 times as massive as the satellite!
self.x = 400 # coordinates of (now) self game object
self.y = 320
self.rect.center = (self.x, self.y)
self.angle = math.degrees(0)
self.rotate_by = math.degrees(0.01)
# Rotating the planet
def rotate(self):
# Rotates the image with each game loop
last_center = self.rect.center
self.image = pg.transform.rotate(self.image_copy, self.angle)
self.rect = self.image.get_rect()
self.rect.center = last_center
self.angle += self.rotate_by
# Defining gravity() & update() Methods
def gravity(self, satellite): # defines this for both the current self object (the planet) but also for the satellite game object
# Calculate impact of gravity on satellite
G = 1.0 # gravitational constant for the game/applet
dist_x = self.x - satellite.x # get distance (x)
dist_y = self.y - satellite.y # get distance (y)
distance = math.hypot(dist_x, dist_y) # get the Euclidian distance - represents r in the gravity equation
# Normalize to a unit vector
dist_x /= distance # The magnitude of the distance (physics, size/amount) is defined in the gravity equation // Therefore we only need to determine the direction from the distance vector here (see below line for more)
dist_y /= distance # Divide dist_x/y by distance to "normalize" the vector - to a unit vector with a magnitude of 1 (times the actual magnitude still gives correct calculation.)
# Apply gravity
force = G * (satellite.mass * self.mass) / (math.pow(distance, 2)) # Force of gravity // The Laws of Universal Gravity
satellite.dx += (dist_x * force) # Add these results (above line - force = G...) to the coordinates
satellite.dy += (dist_y * force)
def update(self):
# Calls the rotate method // Called every game loop
self.rotate()
# Calculating Eccentricity // oval-orbit amount
def calc_eccentricity(dist_list): # define and pass it a list of distances
# Calculate & return eccentricity from list of radii
apoapsis = max(dist_list) # get the apoapsis & periapsis by finding the max and min distances in the list defined above
periapsis = min(dist_list)
eccentricity = (apoapsis - periapsis) / (apoapsis + periapsis)
return eccentricity
# Functions to make labels
def instruct_label(screen, text, color, x, y): # Take screen, list of strings, color, & origin and render text to screen // For displaying instructions on the game screen
instruct_font = pg.font.SysFont(None, 25) # uses pygame (pg) module (via pip) to set the font // Uses the same readout as the sys/error output in Python's default IDLE // None invokes the default pygame font
line_spacing = 22 # 22 pixels
for index, line in enumerate(text): # Start looping through the list of text strings. // The enumerate is used to get an INDEX // the index value will be used with the line_spacing variable to post the strings in the correct locations
label = instruct_font.render(line, True, color, BLACK) # The text needs to be placed on a surface, which has been given the name "label"
screen.blit(label, (x, y + index * line_spacing)) # Finish by blitting the text to the screen
def box_label(screen, text, dimensions): # make fixed-sized label from screen // text & left, top, width, height // For the data readout labels that will appear as gauges at the top of the game screen // Screen, text, dimensions are the parameters
readout_font = pg.font.SysFont(None, 27)
base = pg.Rect(dimensions) # the surfaces made my "instruct_label" will automatically change size to accomodate the amount of text being displayed (see line 162). // As the data will change constantly, if this continues to occur the gauges and their size will also change constantly // To mitigate this, a stand-alone "rect" object of a specified size will form the base for the text object
pg.draw.rect(screen, WHITE, base, 0)
label = readout_font.render(text, True, BLACK)
label_rect = label.get_rect(center=base.center)
screen.blit(label, label_rect) # blit to the screen |
a4f9e8370120d4f0600e0b744e4ac82456cd0dbe | tosunufuk/pEuler | /Python/pProblem_4.py | 465 | 3.5625 | 4 | from datetime import datetime
startTime = datetime.now()
largestPalindrome = 0
for i in range(100, 1000):
for j in range(100, 1000):
palindrome = i * j
if str(palindrome) == str(palindrome)[::-1] :
if palindrome > largestPalindrome :
largestPalindrome = palindrome
print(largestPalindrome)
print("Runtime is ", datetime.now() - startTime)
|
89bc7e81dc3454d7a4ae2412c7db0130d7097e02 | hziling/Algorithms | /Introduction-to-Algorithms/linked_list.py | 911 | 3.875 | 4 |
class Node(object):
def __init__(self, value):
self.value = value
self.next = self.prev = None
class List(object):
def __init__(self):
self.head = None
def search(self, k):
x = self.head
while x != None and x.value != k:
x = x.next
return x
def insert(self, node):
node.next = self.head
if self.head != None:
self.head.prev = node
self.head = node
node.prev = None
def delete(self, node):
if node.prev != None:
node.prev.next = node.next
else:
self.head = node.next
if node.next != None:
node.next.prev = node.prev
if __name__ == '__main__':
lst = List()
lst.insert(Node(5))
lst.insert(Node(2))
lst.insert(Node(1))
lst.insert(Node(5))
lst.delete(lst.search(5))
lst.delete(lst.search(2))
|
100cf26661e730aa38efa2852aaa63e87067bac4 | 4anajnaz/Devops-python | /largestnumber.py | 460 | 4.375 | 4 | #Python program to find largest number
try:
num1= input("Enter first number")
num2= input("Enter second number");
num3= input("Enter third number");
if (num1>num2) and (num1>num3):
largest = num1
elif (num2>num1) and (num2>num3):
largest = num2
else:
largest = num3
print("The largest number is :", largest)
except Exception as e:
print ("Exception block called:")
print (e) |
20a181aee8efcaf7f058863720a9f9b490bdcc7e | kwbarrett/Real-Python-Exercise | /ch4/ex4_8.py | 586 | 4.40625 | 4 | # 1. In one line of code, display the result of trying to .find() the substring
# "a" in the string "AAA". The result should be -1.
print("AAA".find("a"))
# Replace every occurrence of the character "s" with "x" in the string
# "Somebody said something to Samantha.".
my_string = "Somebody said something to Samantha."
print(my_string.replace("s","x"))
# 3. Write and test a script that accepts user input using the input()
# function and displays the result of trying to .find() a particular
# letter in that input.
my_string2 = input("Enter a string: ")
print(my_string2.find("x"))
|
91a14364d6c99d53de2b3031a4627d818c581292 | GudiVaraprasad/Python | /Numpy/typesOfArrays.py | 1,515 | 3.953125 | 4 | from numpy import *
# using array()
arr0=array([1,2,3,4,5])
print(arr0)
print(arr0.dtype)
# array data type
arr1=array([1.2,5.0,3,4.5,6,7])
print(arr1)
print(arr1.dtype)
# using linspace()
arr2=linspace(0,15) #default 50 parts
print(arr2)
arr3=linspace(0,15,20) #divides 20 parts
print(arr3)
#using arange()
arr4=arange(1,15,2) # steps 2 numbers
print(arr4)
#using logspace()
arr5=logspace(1,40,5) #
print(arr5[0]) # 1st element
print('%.2f' %arr5[2]) # 3rd element upto 2 decimals
#using zeros()
arr6=zeros(5)
print(arr6)
arr7=zeros(5,int) # want output in integers
print(arr7)
# using ones()
arr8=ones(5)
print(arr8)
arr9=ones(5,int) # want output in integers
print(arr9)
print("")
print("")
# All at once :
print("-----------------------------------------------------")
print("")
print("")
print("1. using array() --> ",arr0)
print("")
print("")
print("2. using float datatype array() --> ",arr1)
print("")
print("")
print("3. using default linspace() --> ",arr2)
print("")
print("")
print("4. using 20 parts linspace() --> ",arr3)
print("")
print("")
print("5. using arange() --> ",arr4)
print("")
print("")
print("6. using logspace() --> ",arr5)
print("")
print("")
print("7. using zeros() --> ",arr6)
print("")
print("")
print("8. using int datatype zeros() --> ",arr7)
print("")
print("")
print("9. using ones() --> ",arr8)
print("")
print("")
print("10. using int datatype ones() --> ",arr9)
print("")
print("")
print("-----------------------------------------------------")
|
e33ed88f06bf7e41225e132a2303a8bbfffd886b | alynsther/RIPSHKCICC | /movingaverage.py | 2,239 | 3.84375 | 4 | from pandas import *
from import_data_csv import *
from sys import exit
#from __future__ import division
"""
file assumes a pre-existing .csv file filled with data in the following format from import_data_csv or l.csv example
calculates the rsi from input of n days and entry threshold
[0] [1] [2] [3] [4] [5]
date open last price RSI_9D RSI_14D RSI_30D
"""
#The initialization of lists
date = []
open_price = []
last_price = []
RSI_9D = []
RSI_14D = []
RSI_30D = []
"""
main function that runs the RSI algorithm with input of n-days and entry thresholds
returns:
b: buy
s: sell
n: neither
"""
def mainMA():
aggData = mainImportDataCsv()
# entry threshold and n is determined by the user
shortma = int(raw_input('Enter days to calculate the short average: '))
longma = int(raw_input('Enter the days for the long average: '))
differencereq = int(raw_input('Enter the difference required between short and long average to buy or sell:'))
init(aggData)
movingaverage = MA(shortma, longma)
if movingaverage > differencereq:
print("buy")
return "b"
elif movingaverage < -differencereq:
print("sell")
return "s"
else:
print("neither")
return "n"
#calculates RSI give n-days
def MA(s, l):
pastprices = []
SMA = []
LMA = []
if s > l:
print(len(date))
print(s)
print(l)
print("Error: the number of days in your short moving average is longer than your long moving average.")
exit(0)
if s > len(date) or l > len(date):
print(len(date))
print(s, l)
print("Error: not enough data")
exit(0)
for t in range(len(date)-l, len(date)):
LMA.append(last_price[t])
for t in range(len(date)-s, len(date)):
SMA.append(last_price[t])
#make sure its a float
shortMA = sum(SMA)/s
longMA = sum(LMA)/l
print(shortMA, 'short moving average')
print(longMA, 'long moving average')
return shortMA - longMA
# given an input of a dictionary, it extract the columns into the following categories
def init(aggData):
for i in range(len(aggData.values()[0])):
date.append(aggData.values()[0][i][0])
for i in range(len(aggData.values()[0])):
open_price.append(aggData.values()[0][i][1])
for i in range(len(aggData.values()[0])):
last_price.append(aggData.values()[0][i][2])
mainMA()
|
cb589195a50c541737163a15e8a8ccc9d1bd01d4 | EchuCompa/Cursos-Python | /documentacion.py | 1,812 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 14 23:25:12 2020
@author: Diego
"""
def sumar_enteros(desde, hasta):
'''Calcula la sumatoria de los números entre desde y hasta.
Si hasta < desde, entonces devuelve cero.
Pre: desde y hasta son números enteros
Pos: Se devuelve el valor de sumar todos los números del intervalo
[desde, hasta]. Si el intervalo es vacío se devuelve 0
'''
assert (int,int) == (type(desde), type(hasta)), "Tienen que ser números enteros"
suma = 0
if hasta<desde or desde == hasta:
return suma
for x in range(desde,hasta+1):
suma = suma + x
#Gracias Algebru, asumo que ambos son números positivos
# suma = ( hasta*(hasta+1) - (desde+1)*desde ) /2
return suma
def valor_absoluto(n):
""" Recibe un número real y devuelve su valor absoluto"""
if n >= 0:
return n
else:
return -n
def suma_pares(l):
""" Suma los elementos pares de una lista"""
res = 0
for e in l:
if e % 2 ==0:
res += e
else:
res += 0
return res
def veces(a, b):
""" Suma "a" "b" veces. "b" debe ser un número entero positivo"""
res = 0
nb = b
while nb != 0:
#print(nb * a + res)
res += a
nb -= 1
""" Invariante de ciclo res= a*(b-nb) """
return res
def collatz(n):
res = 1
""" Devuelve la cantidad de pasos que toma un número para llegar a 1 siguiendo
el algortimo de la conjetura de Collatz. "n" debe ser un número entero positivo"""
while n!=1:
if n % 2 == 0:
n = n//2
else:
n = 3 * n + 1
res += 1
""" No se me ocurre cuál podría ser un invariante de ciclo si es que tiene"""
return res |
b1dd25767fb7b9424e3d592e4e81f7bc454a4ae3 | JoseJunior23/Iniciando-Python | /aprendendo_python/ex050.py | 363 | 3.828125 | 4 | '''
Desenvolva um programa que leia seis numeros inteiros e mostre a soma apenas daqueles que forem pares.Se for impar, desconsidere-os.
'''
soma = 0
cont = 0
for c in range(1, 7):
n = int(input('Digite o {} valor: '.format(c)))
if n % 2 == 0:
soma += n
cont += 1
print('Você informou {} numeros PARES e a soma foi {}'.format(cont, soma)) |
1d62c6553222e0f654de6d5ee15f4e5d85be0122 | AiZhanghan/Leetcode | /剑指offer/剑指 Offer 31. 栈的压入、弹出序列.py | 687 | 3.640625 | 4 | class Solution:
def validateStackSequences(self, pushed, popped):
"""
Args:
pushed: list[int]
popped: list[int]
Return:
bool
"""
stack = []
push_index = 0
for pop_val in popped:
while not stack or stack[-1] != pop_val:
if push_index >= len(pushed):
return False
stack.append(pushed[push_index])
push_index += 1
stack.pop()
return True
if __name__ == "__main__":
pushed = [1,2,3,4,5]
popped = [4,5,3,2,1]
print(Solution().validateStackSequences(pushed, popped)) |
17c605363a3d1e0bdbb3b33060d52d14536bd180 | tthefe/Practice | /1111.py | 296 | 3.78125 | 4 | '''
total=0
for i in range(1,100,2):
total=total+i
print("%d"%total)
'''
'''
sum=0
for i in range(1,6):
num=int(input())
sum=sum+num
print("평균은 %f입니다."%int(sum/5))
'''
for i in range(2,10):
for j in range(1,10):
print(i*j)
print(' ')
|
19491d442f03531d13adb259ecf845ee492e60dc | j-mciver/f28wp.github.io | /build-html.py | 4,483 | 3.515625 | 4 | """
Helper file to generate the index page
Search through subdirectories to find/build the homepage
* Help identify files incorrectly named
* Ensure consistency (structure/filenames)
Example:
\> python build-html.py > index.html
"""
import os
import sys
#print "This is the name of the script: ", sys.argv[0]
#print "Number of arguments: ", len(sys.argv)
#print "The arguments are: " , str(sys.argv)
showDetails = 0
if ( len(sys.argv)>1 ):
if ( sys.argv[1] == "details" ):
showDetails = 1
"""
(Lecture 23 - Web Services in action Prt 2.pptx)
(Notes 22.pdf)
(Lab 23 - Web Services in action Prt 2.docx)
(Revision 22 - Web Services in action Prt 1.docx)
(Revision 02 Ans - Forms and Tables.docx)
cw
"""
lectures = []
handouts = []
notes = []
labs = []
quizzes = []
cws = []
games = []
if 0:
for currentpath, dirs, files in os.walk('.'):
for file in files:
if 'images' in currentpath:
continue
if 'build' in currentpath:
continue
if '.py' in file:
continue
if '.txt' in file:
continue
if '.html' in file:
continue
#print(os.path.join(currentpath, file))
fn = file
pathandfn = os.path.join(currentpath, file)
print( "(%s) %s" % (fn, pathandfn) )
def finddir( str, str2=0 ):
for currentpath, dirs, files in os.walk('.'):
for file in files:
if 'images' in currentpath:
continue
if 'build' in currentpath:
continue
if '.py' in file:
continue
if '.txt' in file:
continue
if str in file:
if str2==0:
return [file, os.path.join(currentpath, file)]
else:
if str2 in file:
return [file, os.path.join(currentpath, file)]
#print(os.path.join(currentpath, file))
#fn = file
#pathandfn = os.path.join(currentpath, file)
return 0
def findNum( fileNameAndPath, subStr ):
fp = open( fileNameAndPath, 'rt' );
if ( fp == 0 ):
return 0;
txt = fp.read();
fp.close();
return txt.count( subStr );
# print( finddir('Lecture 01') )
str = ''
str += """
<link rel="shortcut icon" type="image/x-icon" href="./material/lectures/images/favicon.ico" />
<br>
<table align="center"><tr><td>
F28WP - <a href='http://www.macs.hw.ac.uk/students/cs/courses/f28wp-web-programming/'>Web Programming</a>
<br>
<br>
<table>
<tr>
<td>Wk </td>
<td>No </td>
<td>Topic </td>
<td>Lecture </td>
<td> </td>
<td>Notes </td>
<td>Tasks </td>
<td>Quizzes </td>
<td>Crossword </td>
</tr>
""";
week = 1
no = 0
for i in range(0,25):
s = 'Lecture %02d' % (no)
val = finddir( s, 'html' )
if val == 0:
no = no + 1
continue
str += '<tr>'
topic = val[0].split('.')
topic = topic[0].split(' -')[1]
topic = topic.strip()
if ( (no+1) % 2 == 0 or no==1) and no>0:
str += "<td>%2d</td>" % (week)
week+=1
else:
str += "<td> </td>"
if week == 7:
str += ' <td colspan="8">-</td></tr>\n'
str += '<tr><td colspan="1"></td><td colspan="8">-</td></tr>\n'
continue
str += "<td>%2d</td>" % (no)
str += "<td>%s</td>" % (topic)
if ( showDetails ):
str += "<td><a href='%s'>Slides (%d)</td>" % (val[1], findNum(val[1], '</section>') )
else:
str += "<td><a href='%s'>Slides</td>" % (val[1]) # , findNum(val[1], '</section>') )
str += '<td> </td>';
tmp = finddir( 'Notes %02d' % (no), 'html' )
if tmp == 0:
str += "<td> - </td>"
else:
str += "<td><a href='%s'>Notes</td>" % tmp[1]
tmp = finddir( 'Task %02d' % (no), 'html' )
if tmp == 0:
str += "<td> - </td>"
else:
str += "<td><a href='%s'>Task</td>" % tmp[1]
tmp = finddir( 'Quiz %02d -' % (no) )
if tmp == 0:
str += "<td> - </td>"
else:
if ( showDetails ):
str += "<td><a href='%s'>Revision (%d)</td>" % (tmp[1], findNum(tmp[1], 'question:') )
else:
str += "<td><a href='%s'>Revision</td>" % tmp[1]
tmp = finddir( 'Crossword %02d' % (no), 'html' )
if tmp == 0:
str += "<td> - </td>"
else:
str += "<td><a href='%s'>Crossword</td>" % tmp[1]
str += '</tr>\n'
no = no + 1
#if 'Review' in topic:
# str += '<tr><td> </td></tr>'
str += '</table>'
str += '<br>'
str += "Assessment:<br>"
str += "Exam 50% <br>"
# str += "Courseworks 50%<br>"
str += "Coursework (50%) (Composed of Labs/Class Tests - see VLE for details)"
str += "<br>"
#str += '<br><br>'
#str += "Coursework (50%%) <a href='%s'>Link</a> <br>" % ( finddir( 'cw01')[1] )
str += "</td></tr></table>"
print( str )
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.