blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
6c7017961787cfad52e209540622285e06ac2722 | dashboardijo/TechWrap | /Interviews/Problems/LeetCode/1001-1100/1122_RelativeSortArray.py | 1,439 | 4.1875 | 4 | """
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order.
Example 1:
Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]
Constraints:
arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
Each arr2[i] is distinct.
Each arr2[i] is in arr1.
"""
from collections import defaultdict
class Solution:
def relativeSortArray(self, arr1, arr2):
ret = []
all_v = defaultdict(int)
for i in arr1:
all_v[i] += 1
for j in arr2:
if j in all_v:
ret.extend([j] * all_v[j])
unseen = [(k, v) for k, v in all_v.items() if k not in arr2]
sort_unseen = sorted(unseen, key=lambda item: item[0])
for item in sort_unseen:
ret.extend([item[0]] * item[1])
return ret
def topSolution(self, arr1, arr2):
dic = {arr2[i]: i for i in range(len(arr2))}
arr1.sort(key=lambda x: (dic.get(x, 1001), x))
return arr1
if __name__ == '__main__':
s = Solution()
arr1 = [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19]
arr2 = [2, 1, 4, 3, 9, 6]
ret = s.relativeSortArray(arr1, arr2)
print(ret)
|
ee6f33dc2e675c8e56e4a986f5c4672e7ea30ead | kstseng/dsa-ml-tool-note | /DSA/ProblemSolvingWithAlgorithmsAndDataStructures/CODE/BasicDataStructure/stack_postfix.py | 4,693 | 3.703125 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
def infixToPostfix(infixexpr):
""" 中綴轉後綴
infixexpr = "A * B + C * D"
範例:
1.
infixexpr = A * B + C
| current | postfixList | opStack |
|---------|-------------|---------|
| A | A | [] |
| * | A | [*] |
| B | AB | [*] |
| + | AB* | [+] |
| C | AB*C | [+] |
==> AB*C+
2.
infixexpr = (A + B) * C
| current | postfixList | opStack |
|---------|-------------|---------|
| ( | | [(] |
| A | A | [(] |
| + | A | [(, +] |
| B | AB | [(, +] |
| ) | AB+ | [] |
| * | AB+ | [*] |
| C | AB+C | [*] |
==> AB+C*
3.
infixexpr = A * B + C * D
| current | postfixList | opStack |
|---------|-------------|---------|
| A | A | |
| * | A | [*] |
| B | AB | [*] |
| + | AB* | [+] |
| C | AB*C | [+] |
| * | AB*C | [+, *] |
| D | AB*CD | [+, *] |
==> AB*CD*+
"""
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
opStack = Stack()
postfixList = []
tokenList = infixexpr.split()
for token in tokenList:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
## 假設是字母或是數字,則直接 append
postfixList.append(token)
elif token == '(':
## 把 "(" 記起來,以便紀錄當遇到 ")" 時,需操作所有在括弧內的運算。
opStack.push(token)
elif token == ')':
## 把屬於這組括弧內的操作清空,直到遇到最上層的右括號為止
## (利用最上層的右括弧作為停止點)
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
## 基本運算符號
while not opStack.isEmpty() and (prec[opStack.peek()] >= prec[token]):
## 若當前的 token 順位比 opStack 中的 pop 操作符來得小,
## 則需要先把 opStack 的 pop item 先放到 postfixList 中
## ==> 代表先進行 opStack 優先次序高的操作
##
## eg: A * B + C
## 當 token 是 '+',而 top token 是 "*"
## 則需要先操作 top token ==> 把 '*' 加入 postfixList
postfixList.append(opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return "".join(postfixList)
def postfixEval(postfixExpr):
""" 後綴求值
"""
operandStack = Stack()
tokenList = postfixExpr.split()
for token in tokenList:
if token in "0123456789":
operandStack.push(int(token))
else:
## 一但碰到運算符號,則取 Stack 最後兩個數字進行運算
## 然後再附加回原來的 stack,以便做後續的運算
topOperand = operandStack.pop()
secondOperand = operandStack.pop()
result = doMath(token, topOperand, secondOperand)
operandStack.push(result)
return operandStack.pop()
def doMath(token, operand1, operand2):
"""
"""
if token == "+":
return operand1 + operand2
elif token == "-":
return operand1 - operand2
elif token == "*":
return operand1 * operand2
elif token == "/":
return operand1 / operand2
else:
ValueError("Token is not recognizable.")
def main():
print("[TEST] infixToPostfix")
assert infixToPostfix("( A + B ) * ( C + D )") == 'AB+CD+*'
assert infixToPostfix("( A + B ) * C") == 'AB+C*'
assert infixToPostfix("A + B * C") == 'ABC*+'
print("[TEST] postfixEval")
print(postfixEval('7 8 + 3 2 + /'))
if __name__ == '__main__':
main()
|
c5652c63b77025cbe3633a72da4ca1c635a44485 | prasadmule25/Group_B | /setterANDgetter_method.py | 3,156 | 4.0625 | 4 |
# class Student:
# def __init__(self,name,marks):
# self.name=name
# self.marks=marks
# def display(self):
# print("hi",self.name)
# print("your markd is",self.marks)
# s=Student('swastik',100)
# print(s.name)
# s.display()
class Student:
def setname(self,name): # used only for single variable
self.name=name
def getname(self):
return self.name
def setmarks(self,marks):
self.marks=marks
def getmarks(self):
'''we can write some validation code''' # in constructor we can not write validation code
return self.marks
def display(self):
print('hi',)
n=int(input('enter no of student :- '))
for i in range(n):
name=input('enter name:- ')
marks=int(input('enter marks :-'))
s=Student()
print(id(s))
s.setname(name)
s.setmarks(marks)
print('hi',s.getname())
print('your marks is:- ',s.getmarks())
print("*"*10)
# # exaple 3:
# class Test:
# def __init__(self):
# self.var = 10
# self._var1 = 11
# self.__var2 = 12
# def setter__var2(self,num):
# self.__var2 = num
# def get__var2(self):
# return self.__var2
# def fun1(self):
# print(self.var)
# print(self._var1)
# print(self.__var2)
# def __fun2(self): # we can access private methid in same class only , not in child class also
# print(self.var)
# print(self._var1)
# print(self.__var2)
# t=Test()
# t.setter__var2(19)
# t.fun1()
#
# # example :
# 'Using property() function to achieve getters and setters behaviour'''
#
#
# # Python program showing a
# # use of property() function
#
# class Test:
# def __init__(self):
# self.__age = 0 # we can do this for protected variable also
#
#
# # function to get value of _age
# def get__age(self):
# print("getter method called")
# return self.__age
#
# # function to set value of _age
# def set__age(self, a):
# print("setter method called")
# self.__age = a
#
# # function to delete _age attribute
# def del__age(self):
# print('DEL METHOD C')
# del self.__age
#
# num = property(get__age, set__age, del__age) # age as num we should call any action with num regarding age
#
#
# mark = Test()
#
# mark.num = 10
#
# print(mark.num)
# del mark.num
#
# # Using @property decorators to achieve getters and setters behaviour
#
# # Python program showing the use of
# # @property
#
# class Test:
# def __init__(self):
# self._age = 0
#
# # using property decorator
# # a getter function
# @property
# def get1(self):
# print("getter method called")
# return self._age
#
# # a setter function
# @get1.setter # to take decorater name as @getterMethodName.setter for setter
# def set1(self, a):
# if (a < 18):
# raise ValueError("Sorry you age is below eligibility criteria") #validation code
# print("setter method called")
# self._age = a
# mark = Test()
# mark.set1 = 19
# print(mark.get1)
|
311125e60526c545d6c73813a75b8420500126df | KeithPallo/independent_coursework | /1 - MOOC - Intro to CS & Programming/Final Exam/f_problem_6.py | 4,047 | 3.9375 | 4 | # Initial class Container is given from the problem. It represents a simple container that can
# hold hashable objects of any type
class Container(object):
""" Holds hashable objects. Objects may occur 0 or more times """
def __init__(self):
""" Creates a new container with no objects in it. I.e., any object
occurs 0 times in self. """
self.vals = {}
def insert(self, e):
""" assumes e is hashable
Increases the number times e occurs in self by 1. """
try:
self.vals[e] += 1
except:
self.vals[e] = 1
def __str__(self):
s = ""
for i in sorted(self.vals.keys()):
if self.vals[i] != 0:
s += str(i)+":"+str(self.vals[i])+"\n"
return s
# ---------------------------------------------------------------------------------------------------------
# First created subclass Bag - can remove, count, or add objects in a container
class Bag(Container):
def remove(self, e):
""" assumes e is hashable
If e occurs in self, reduces the number of
times it occurs in self by 1. Otherwise does nothing. """
# Using built in function try, attempt to remove one occurance of input e
try:
self.vals[e] -= 1
# If an exception is thrown, do nothing and pass
except:
pass
def count(self, e):
""" assumes e is hashable
Returns the number of times e occurs in self. """
# Using built in function try, check to see if a value is within the current Bag. If it is, then
# return the value. If there is an exception raised instead, return 0
try:
return self.vals[e]
except:
return '0'
def __add__(self,other):
# Class method to add two objects of class bag together
# Create a copy of the current bag
dict_copy = dict(self.vals)
# Check to see if there are common keys within each bag. If there are, add their value to the correct
# key within the copy
for i in sorted(self.vals.keys()):
if i in sorted(other.vals.keys()):
dict_copy[i] = self.vals[i] + other.vals[i]
# For all other keys that are within bag other, but not within the current bag, add them to the
# dictionary copy
for i in sorted(other.vals.keys()):
if i not in sorted(self.vals.keys()):
dict_copy[i] = other.vals[i]
# Resort the dictionary and append all non 0 values to an empty string. Return the string.
statement = ""
for i in sorted(dict_copy.keys()):
if dict_copy[i] != 0:
statement += str(i)+":"+str(dict_copy[i])+"\n"
return statement
# ---------------------------------------------------------------------------------------------------------
# Second created subclass ASet - can remove objects from a hashable input, and test to see if a specified
# user input is contained within itself
class ASet(Container):
def remove(self, e):
"""assumes e is hashable
removes e from self"""
# Using built in function try, attempt to remove one occurance of input e
try:
del self.vals[e]
# If an exception is thrown, do nothing and pass
except:
pass
def is_in(self, e):
# Check to see if input is in the current instance. Return True if it is, otherwise return False
if e in self.vals.keys():
return True
else:
return False
# ------------------------------------------------------------------------------------------------------------
# Example testing script for Bag
print("Bag Example:")
a = Bag()
a.insert(3)
a.insert(5)
b = Bag()
b.insert(5)
b.insert(5)
b.insert(5)
print(a+b)
# Example testing script for ASet
print("ASet Example:")
d1 = ASet()
d1.insert(4)
d1.insert(4)
d1.remove(2)
print(d1)
d1.remove(4)
print(d1) |
ec2bd5cd698aa39dd86716f2d2de207669122484 | Jackyzzk/Algorithms | /字符串-07-0647. 回文子串-优化dp.py | 1,216 | 3.5625 | 4 | class Solution(object):
"""
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
输入: "abc"
输出: 3
解释: 三个回文子串: "a", "b", "c".
输入: "aaa"
输出: 6
说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".
输入的字符串长度不会超过1000。
链接:https://leetcode-cn.com/problems/palindromic-substrings
"""
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
n, count = len(s), 0
opt = [1] * n # 当前的第 i 层,到下标为 j 的区间 i - j 是不是回文串
for i in range(n - 2, -1, -1):
for j in range(n - 1, i, -1):
if s[i] == s[j]:
opt[j] = opt[j - 1]
if opt[j]:
count += 1
else:
opt[j] = 0
return count + n
def main():
s = "aaa"
# s = 'abc'
# s = "fdsklf" # 6
test = Solution()
ret = test.countSubstrings(s)
print(ret)
if __name__ == '__main__':
main()
|
e38a57a23ea7a4fff2542b18f8b978b02be92550 | UncleBob2/MyPythonCookBook | /Intro to Python book/random 3D walk/random walk sin cos.py | 1,857 | 4.625 | 5 | from random import random
import math
import matplotlib.pyplot as plt
# Define the main function as function call begins from here.
def main():
path = []
printintro()
n = getinput()
steps, path = walkRandomly(n)
printSummary(steps, n)
# print(path)
x_val = [x[0] for x in path]
y_val = [x[1] for x in path]
plt.plot(x_val, y_val)
plt.plot(x_val, y_val, "or")
plt.show()
def printintro():
# prints an introduction to the random walk.
print("This program simulates a random walk")
print("for n steps. The person can go a step")
print("in any random direction ")
print("with equal probability")
def getinput():
n = eval(input("How many steps you want to walk? "))
return n
# The concept of random direction is introduced here. At every point, a random angle is generated
# and the distance in X and Y directions are calculated.
def walkRandomly(n):
distanceX = 0
distanceY = 0
x_axis, y_axis = 0, 0
path = []
# Iterate for loop in range n.
for i in range(n):
path.append(tuple((distanceX, distanceY)))
angle = randomDirection()
distanceX = distanceX + math.cos(angle)
distanceY = distanceY + math.sin(angle)
totalDistance = pow(distanceX, 2) + pow(distanceY, 2)
totalDistance = pow(totalDistance, 0.5)
return totalDistance, path
def randomDirection():
# generates a random angle Uses the random() function to generate a random angle
randomNo = random()
angle = 2 * randomNo * math.pi
return angle
# Prints the distance of the person from the origin
def printSummary(steps, n):
# Prints a summary of the random walk
print("\nTotal steps taken: {0}".format(n))
print("Distance from start: {0}".format(steps))
# Call the main method
if __name__ == "__main__":
main()
|
479c5beca1ca747a2f30fa0f23050bff33010412 | GHDDI-AILab/Targeting2019-nCoV | /util/csv2md.py | 2,246 | 3.734375 | 4 | # coding:utf-8
"""
Convert a csv file to markdown format.
Syntax:
python csv2md.py -csv <csv file> -md <markdown file>
in which <csv file> is the csv file to be converted; <markdown file> is the output path for the generated markdown file, optional;
<encoding> is the encoding of the csv file, optional, the default encoding is set to `utf8`.
You're recommended to make sure the input csv file is encoded in UTF8 scheme.
Created : 2, 2, 2020
Revised : 2, 2, 2020
All rights reserved
"""
__author__ = 'dawei.leng'
import os, csv
def parse_csv_line(csv_line):
items = csv_line.split(',')
results = []
for item in items:
results.append(item.strip())
return results
def parse_csv_file(csv_file):
with open(csv_file, mode='rt') as f:
csv_reader = csv.reader(f, delimiter=',')
records = []
for row in csv_reader:
records.append(row)
return records
def generate_markdown_table(records):
titles = records[0]
content = ''
title_line = '| '
title_sep = '| -'
for item in titles:
title_line += '%s | ' % item
title_sep += '--- | '
content += '%s\n' % title_line
content += '%s\n' % title_sep
for record in records[1:]:
line = '| '
for item in record:
line += '%s | ' % item
content += '%s\n' % line
return content
if __name__ == '__main__':
import argparse
argparser = argparse.ArgumentParser()
argparser.add_argument('-csv', default='SARS_MERS_active.csv', type=str, help='csv file, input')
argparser.add_argument('-md', default=None, type=str, help='markdown file, output, optional')
#argparser.add_argument('-csv_encoding', default='utf8', type=str, help='encoding of csv file, optional')
args = argparser.parse_args()
csv_file = args.csv
md_file = args.md
#csv_encoding = args.csv_encoding
if md_file is None:
md_file = os.path.splitext(os.path.basename(csv_file))[0] + '.md'
records = parse_csv_file(csv_file)
md_table = generate_markdown_table(records)
with open(md_file, mode='wt') as f:
f.write(md_table)
print('markdown file = %s' % os.path.abspath(md_file))
print('All done~')
|
096b88a35550dd914a3c044d62b1ae093d9652d0 | gselva28/100_days_of_code | /DAY 17/class_def.py | 611 | 4.0625 | 4 | # class User:
# def __init__(self):
# print("new user being created..")
#
#
# user_1 = User()
# user_1.id = "001"
# user_1.username = "Selva"
#
# print(f"The id is {user_1.id} and the name is {user_1.username}")
#
# user_2 = User()
# user_2.id = "002"
# user_2.username = "Ganesh"
#
# print(f"The id is {user_2.id} and the name is {user_2.username}")
"""Updated Code which has attributes for the class"""
class User:
def __init__(self, user_id, username):
self.id = user_id
self.username = username
self.follower = 0
user = User("001", "Selva")
print(user.follower)
|
ebaf1a3b8d691b0712f450da76b3726ccd345d9b | Jelle12345/Python-3 | /oefeningen.py | 2,238 | 3.875 | 4 | contacten = {}
def main():
menu()
keuze = input("Maak een keuze")
while keuze != 's':
if keuze == 'm':
nieuw_contact()
elif keuze == 't':
toon_contacten()
elif keuze == 'v':
verwijder_contact()
elif keuze == 'a':
contact_aanpassen()
elif keuze == 'o':
contact_opslaan()
menu()
keuze = input("Maak een keuze")
def menu():
print("m: maak nieuw contact")
print("t: toon je contactenlijst")
print("s: stop je programma")
print("v: verwijder contact")
print("a: contact aanpassen")
print("o: contact opslaan")
def toon_contacten():
print("-"*10)
print("Uw contacten: ")
print("-"*10)
print('\n'.join("{}: {}".format(k, v) for k, v in contacten.items()))
print("\n"*6)
def verwijder_contact():
verwijderen = input("noem het contact dat je wil verwijderen")
del contacten[verwijderen]
def nieuw_contact():
naam = input("geef een naam voor je contact")
nummer = input("geef het telefoonnummer van je contact")
print("dit is je contact " + naam + " " + nummer)
contacten[naam] = nummer
def contact_aanpassen():
print("-"*10)
print("Uw contacten: ")
print("-"*10)
print('\n'.join("{}: {}".format(k, v) for k, v in contacten.items()))
print("\n"*6)
aanpas = input("geef de naam van je contact dat je wil aanpassen")
if aanpas in contacten:
mobielnummer = input("geef je nieuwe telefoonnummer")
contacten[aanpas] = mobielnummer;
print("-" * 10)
print("Uw contacten: ")
print("-" * 10)
print('\n'.join("{}: {}".format(k, v) for k, v in contacten.items()))
print("\n" * 6)
def contact_opslaan():
for contact in contacten:
print("-" * 10)
print("Uw contacten: ")
print("-" * 10)
print('\n'.join("{}: {}".format(k, v) for k, v in contacten.items()))
print("\n" * 6)
with open("contact.txt","w+") as f:
contacten1 = "".join(contacten)
for contact in contacten:
f.write(contact + " " + contacten[contact] + "\n")
f.close()
print("je lijst is opgeslagen in contact.txt")
main() |
7163d57eca4f67dd6e9db8e7eba410c071435127 | sonalipatil1729/SSW-540 | /guessingNumberGame.py | 2,948 | 4.375 | 4 | """Name: Sonali Patil
This program will generate a random number and will ask user to guess the number in 6 guesses.
The program is coded to handle all the below use cases:
- if user provides incorrect input(alphabet): program will give message to user that input is not correct and will ask again to input correct value
- if user provides incorrect input(number beyond the specified range): program will give message to user that input is not correct and will ask again to input correct value in valid range
- if user guesses the number in <6 chances, program will ask user if he wants to continue playing or exit
- if user does not guess the number in 6 gueasses, program will tell the user which was the generated number and will ask for choices to continue or to exit.
Note: User will have 6 chances to guess the number excluding the attempts where he has put incorrect value i.e. number out of range, and non digit number.
"""
import random
def init():
startThegame()
nextActivity()
def nextActivity():
activity = raw_input("\nDo you want to start over(Y/N)?")
if activity == 'Y' or activity == 'y':
init()
elif activity == 'N' or activity == 'n':
exit()
else:
print "Please enter correct choice"
nextActivity()
def startThegame():
print("Well," + name + ", I am thinking of a number between 1 and 20.\n")
randomNumber = random.randint(1, 20)
i = 1
while (i <= 6):
try:
guessedNumber = int(raw_input("Take a guess: "))
except Exception as e:
print("Please enter the correct number \n")
continue # so that user will have exact 6 chances to input correct value
if isInRange(guessedNumber) == 1:
print "Please Enter the number which is 20< or >1\n"
continue # so that user will have exact 6 chances to input correct value
result = isTheGuessCorrect(guessedNumber, randomNumber)
if result == 0:
print("Good job," + name + "! You guessed my number in " + str(i) + " guesses!")
break
elif result == -1:
print("Your guess is too low.\n")
elif result == 1:
print("Your guess is too high.\n")
i = i + 1 # to iterate the loop
if i > 6:
print("You have not guessed the number correctly!!!The number I was thinking of was " + str(randomNumber))
def isTheGuessCorrect(guessedNumber, randomNumber):
if guessedNumber == randomNumber:
return 0
elif guessedNumber < randomNumber:
return -1
elif guessedNumber > randomNumber:
return 1
def isInRange(guessedNumber):
if guessedNumber < 1 or guessedNumber > 20:
return 1
else:
return 0
# Program will start from here
print("*****Guess the Number Game*****\n")
name = raw_input("Hello! What is your name? ")
init()
|
03fc03590cbafe6aae800756944009acb7128623 | TheOneAndOnlyAbe/astar | /helperFiles/nodeFunctions.py | 6,775 | 4.0625 | 4 | import math
# The Node class is in here because these functions require the node class and so do the other classes.
# I would remake this so that the Map class hold all of these functions, but that would take more time than I have.
# If I were to leave this class in the classes.py file, I would get an error because the classes.py file would
# import nodeFunctions.py, and nodeFunctions.py would import classes.py
class Node:
"""
This class makes a node with the parent node and the position this node would be in.
"""
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.g = 0 # The distance from the starting node to this node
self.h = 0 # The distance from this node to the end
self.f = 0 # g and h added together
def __str__(self): # Prints the coordinates of the node
string_to_print = "Coordinates: {0}".format(self.position)
return string_to_print
def current_node_and_index(open_list):
"""
Returns a tuple that has the current workable node and its index in the open list
:param open_list: The list containing all available nodes
:return: A tuple with (current_node, index)
"""
# By default, choose the first node.
current_node = open_list[0]
index_of_current = 0
for i in range(0, len(open_list)):
if open_list[i].f < current_node.f: # Judge based on f because the lower the f, the better. A lower
current_node = open_list[i] # f means that taking that node would lead to a more optimal path
index_of_current = i
return current_node, index_of_current
def get_neighbors(current_node, maze):
"""
Gets the neighbors of the current node
:param current_node: The current node
:param maze: The whole map
:return: A list with the available neighbors of the current node.
"""
neighbors = []
potential_neighbors = [ # The positions of the potential neighbors
(-1, 0), # One above
(0, -1), # One left
(1, 0), # One below
(0, 1), # One right
# (1, 1),
# (-1, 1), # These will make it so that diagonal nodes can be neighbors
# (1, -1),
# (-1, -1)
]
for position in potential_neighbors:
pos_of_node = (current_node.position[0] + position[0], current_node.position[1] + position[1])
len_of_maze_y = len(maze) - 1 # Subtract from the length to be able to compare with pos_of_node
len_of_maze_x = len(maze[0]) - 1 # Choose first list because all lists have the same length
if ((pos_of_node[0] > len_of_maze_y) or (pos_of_node[0] < 0) or # If pos is not within the range of the
(pos_of_node[1] > len_of_maze_x) or (pos_of_node[1] < 0) or # first nested list or second nested list
(maze[pos_of_node[0]][pos_of_node[1]] != 0)): # or if the value at that point is not 0
continue # skip that neighbor and move to the next.
created_node = Node(current_node, pos_of_node)
neighbors.append(created_node) # Add the node to the neighbors list
return neighbors
def acceptable_neighbors(neighbors, closed_list, open_list, current_node, end_node):
"""
Returns a list of neighbors that aren't already in the closed list or open list
:param neighbors: The neighbors found by the "get_neighbors" function
:param closed_list: The list with all the nodes that have been run through already
:param open_list: The list with the nodes that are being worked on
:param current_node: The current node
:param end_node: The final node
:return: A list a nodes
"""
useful_neighbors = []
for neighbor in neighbors: # Run through each neighbor
is_in_closed = False
is_in_open = False
for closed_node in closed_list:
if neighbor.position == closed_node.position: # If the position of the neighbor matches one in the closed
is_in_closed = True # list, set is_in closed to True
break # break so that it can immediately continue if True
if is_in_closed: # If it was found in the closed list, skip it.
continue
neighbor.g = current_node.g + 1 # Add one because this node is now one block away from the current node.
neighbor.h = math.sqrt(abs(neighbor.position[0] - end_node.position[0]) + # Find dist from this node to the
abs(neighbor.position[1] - end_node.position[1])) # end node. I used Distance Formula
neighbor.f = neighbor.g + neighbor.h
for open_node in open_list:
if (neighbor.position == open_node.position) and (neighbor.g >= open_node.g):
is_in_open = True # If the node matches the position with on in the open list AND the g is greater
break # we don't want it. Why? For a cleaner and more efficient path.
if is_in_open:
continue
useful_neighbors.append(neighbor)
return useful_neighbors
def a_star(the_map):
"""
Returns the path from start to finish
the_map: A Map object to use
:return: The path from start to finish. If no path is possible, return None
"""
maze = the_map.map
start = the_map.startPoint
end = the_map.endPoint
starting_node = Node(None, start)
ending_node = Node(None, end)
open_list = [starting_node]
closed_list = []
while len(open_list) != 0:
# print(open_list)
current_node, index_of_current = current_node_and_index(open_list)
open_list.pop(index_of_current) # Remove from open list because it is chosen
closed_list.append(current_node) # Move to the closed list because it is chosen
if current_node.position == ending_node.position:
start_to_finish = [] # List of coordinates from start to finish
while current_node is not None: # current_node will be set to its parent. The beginning
start_to_finish.append(current_node.position) # node has a parent of None, so the loop will break
current_node = current_node.parent
start_to_finish.reverse()
return start_to_finish # Return the list of coordinates
neighbors = get_neighbors(current_node, maze)
useful_neighbors = acceptable_neighbors(neighbors, closed_list, open_list, current_node, ending_node)
for node in useful_neighbors:
open_list.append(node)
return None
|
0b4d1ebfcffae7e0c0f7003d552472ec458c669d | emamula/SoftDesSp15 | /toolbox/word_frequency_analysis/frequency.py | 1,747 | 4.5625 | 5 | """ Analyzes the word frequencies in a book downloaded from
Project Gutenberg """
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a list.
All words are converted to lower case.
"""
words = []
#open file and readf lines
f = open(file_name,'r')
lines = f.readlines()
#remove gutengerg's pre-text
curr_line = 0
while lines[curr_line].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1:
curr_line += 1
lines = lines[curr_line+1:]
#remove punctuation, split lines to get words, and cast
#all words to lowercase
for line in lines:
for p in string.punctuation:
line = line.replace(p,"")
words_in_line = line.split()
for word in words_in_line:
words.append(word.lower())
return words
def get_top_n_words(word_list, n):
""" Takes a list of words as input and returns a list of the n most frequently
occurring words ordered from most to least frequently occurring.
word_list: a list of words (assumed to all be in lower case with no
punctuation
n: the number of words to return
returns: a list of n most frequently occurring words ordered from most
frequently to least frequentlyoccurring
"""
word_count = {}
top_n_words = []
for word in word_list:
if word in word_count:
word_count[word] += 1
if word not in word_count:
word_count[word] = 1
ordered_by_frequency = sorted(word_count, key = word_count.get, reverse = True)
for x in range(0,n):
top_n_words.append(ordered_by_frequency[x])
return top_n_words
if __name__ == "__main__":
print get_top_n_words(get_word_list("grimm.txt"), 100) |
49112217b892b9edbffb49dfc8f2450dc0ee4c3e | iansedano/codingame_solutions | /Skynet_revolution/dijkstra.py | 1,792 | 3.8125 | 4 | nodes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
links = [[2, 6], [9, 7], [0, 7], [9, 8], [8, 2], [7, 1], [9, 2], [3, 1], [2, 5], [0, 8], [4, 1], [9, 1], [0, 9], [2, 1]]
def dijkstra(n1, n2, nodes, links):
'''Get shortest distance between two nodes
Assumes unweighted linkes (i.e. each link's value is 1)
'''
node_dict = {i: 999 for i in nodes}
node_dict[n1] = 0
checked = []
traverse_tree(n1, node_dict, links, checked)
distance = node_dict[n2]
return distance
def traverse_tree(node, node_dict, links, checked):
print(node_dict)
distance = node_dict[node] + 1
adjacent_nodes = get_adjacent_nodes(node, links)
for an in adjacent_nodes:
if node_dict[an] > distance:
node_dict[an] = distance
checked.append(node)
current_node = set_current_node(checked, node_dict)
if current_node == 0:
return 0
traverse_tree(current_node, node_dict, links, checked)
def get_adjacent_nodes(node, links):
adjacent_nodes = []
for l in links:
if l[0] == node:
if l[1] not in adjacent_nodes:
adjacent_nodes.append(l[1])
if l[1] == node:
if l[0] not in adjacent_nodes:
adjacent_nodes.append(l[0])
return adjacent_nodes
def set_current_node(checked, node_dict):
# visited is a set that contains the names of the nodes
# marked as visited. E.g. [1, 2].
# currentDistances is a dictionary that contains the
# current minimum distance of each node. E.g. {1: 0, 2: 1, 3: 2}
sorted_dict = {
k: v for k, v in sorted(node_dict.items(), key=lambda item: item[1])
}
for k in sorted_dict.keys():
if k not in checked:
return k
return 0
print(dijkstra(1, 2, nodes, links))
|
b9bff2a8e344dabb03de95bfd95e9f2ac59f1cc5 | WillLuong97/MultiThreading-Module | /openWeatherAPI.py | 4,137 | 3.75 | 4 | '''
OpenWeatherMap API, https://openweathermap.org/api
by city name --> api.openweathermap.org/data/2.5/weather?q={city name},{country code}
JSON parameters https://openweathermap.org/current#current_JSON
weather.description Weather condition within the group
main.temp Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit
wind.speed Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour
'''
import requests # http requests library, e.g. requests.get(API_Call).json()
# Initialize variables, console loop
def main():
# Console loop
print('\nWelcome to the Web Services API Demonstrator\n')
# input('Please press ENTER to continue!\n')
testCases = {1: 'Current Weather, city = Houston',
2: 'Current Weather, enter city name',
3: 'Current Weather, invalid key',
4: 'Current Weather, invalid city',
5: 'Future: current weather, enter zip code',
6: 'Future',
7: 'Future',
99: 'Exit this menu'}
userInput(testCases)
input('\n\nSay Bye-bye'.upper())
# Map user console input to a test case
# userChoices is a dictionary, key points to test case
# Includes user input exception handling
# Loop until user input is '99'
def userInput(userChoices):
while True:
print(' your choices'.upper(), '\t\t\tTest Case\n'.upper(), '-' * 55)
for key, value in userChoices.items():
print('\t', key, ' \t\t\t\t', value)
try:
choice = int(input("\nPlease enter the numeric choice for a Test Case \n\t --> ".upper()))
except:
print("\nSomething went wrong, please enter a numeric value!!!\n")
continue
if choice == 99:
break
menuExcept(choice)
# Map user menu selection (parameter) to module (function call)
def menuExcept(choice):
city = "Houston" #default city
API_key = '5bd2695ec45f88d4c14d7b43fd06a230' # Mulholland's key
invalidAPI_key = 'fd38d62aa4fe1a03d86eee91fcd69f6e' # used by You Tube video, not active 9/2018
units = '&units=imperial' # API default is Kelvin and meters/sec
invalidCity = city + '88' + 'abc'
if choice == 1:
JSON_Response = currentWeatherByCity(API_key, units, 'Houston')
currentWeatherFields(JSON_Response)
elif choice == 2:
city = input('\tPlease enter a city name --> ')
JSON_Response = currentWeatherByCity(API_key, units, city)
currentWeatherFields(JSON_Response)
elif choice == 3:
JSON_Response = currentWeatherByCity(invalidAPI_key, units, 'chicago')
elif choice == 4:
JSON_Response = currentWeatherByCity(API_key, units, invalidCity)
elif choice == 5:
print('test case construction underway, come back soon!')
elif choice == 6:
print('test case construction underway, come back soon!')
elif choice == 7:
print('test case construction underway, come back soon!')
else:
print('Whatchu talking about Willis? Please try a valid choice!')
input('*************** Press Enter to continue ******************\n\n'.upper())
# build the openweathermap REST Request
def currentWeatherByCity(key, units, city):
city = '&q=' + city
API_Call = 'http://api.openweathermap.org/data/2.5/weather?appid=' + key + city + units
print('\tThe api http string --> ' + API_Call)
input('\t*** hit ENTER to execute the API GET request ***\n')
jsonResponse = requests.get(API_Call).json()
print(jsonResponse)
return jsonResponse
# display selected values from the openweathermap REST response
def currentWeatherFields(response):
input('\n\t*** hit ENTER to check out selected JSON values ***\n')
print("\t Entire attribute of weather --> ", response['weather'])
print('\tdescription --> ', response['weather'][0]['main'])
print('\twind speed, mph --> ', response['wind']['speed'])
print('\ttemperature, F --> ', response['main']['temp'])
main() |
99a6a8f58c3b31a201aaef43cf7b7d74598fcfa5 | unouno1224/workspace | /learning/src/excercise/train4.py | 288 | 3.640625 | 4 | def func(li):
li[0]= 'i am your father!' #1
if __name__=="__main__":
li = [1,2,3,4]
func(li)
print(li)
def func1(li):
li= ['i am your father!', 2,3,4]
print(li)
if __name__=="__main__":
li = [1,2,3,4]
func1(li)
li.sort(reverse=True)
print(li)
|
3f97901da34c0283c0fb6f0f41c2fa9dda264345 | yonggqiii/kattis | /cs1010e/2048/2048_template.py | 671 | 4.03125 | 4 | def solve_2048(puzzle: [[int]], move: int) -> [[int]]:
'''
https://open.kattis.com/problems/2048
Define the solve_2048 function which solves the problem given
the puzzle as a list of lists containing ints, and the move.
Your function should return the new puzzle after the move.
The input puzzle must not be amended.
'''
pass
### DO NOT EDIT THE PROGRAM BEYOND THIS LINE ###
def main():
puzzle = [list(map(lambda x: int(x), input().split(' ')))
for _ in range(4)]
move = int(input())
for row in solve_2048(puzzle, move):
print(' '.join(map(lambda x: str(x), row)))
if __name__ == '__main__':
main()
|
454274a954a6173f98d91b42244d873550204af2 | salmonteASC/AllStarCode | /ListLab.py | 659 | 3.546875 | 4 | from random import *
def randomMovies():
lst1 = ["The Adventure of ","The tales of ","The Odyssey of ","The life of ","The hunting of ","The stories of ","The trials of ","The return of ", ]
lst2 = ["David","Sam","Shorlock Homes","Hulk","","Charlie","Joshua","Christina","Shinjini"]
lst3 = [" the killer"," the Great"," the Amazing"," the Magnificient"," the Pharaoh"]
lst4 = [] #empty list for random movie titles
for i in range(len(lst1)):
first = lst1[randrange(len(lst1))]
second = lst2[randrange(len(lst2))]
third = lst3[randrange(len(lst3))]
lst4.append(first + second + third)
print(lst4)
randomMovies() |
40cafc20345aa969a088b103961af6b8b8cd0d13 | RahulLooserR/python-pygames | /Archery/Arrow.py | 1,799 | 3.703125 | 4 | from Globals import *
class Arrow:
# 1/2 length of the arrow
LENGTH = 50
# constructor with parameters, starting point(anchorPoint), angle of projectile and velocity
def __init__(self, anchorPoint, angle, velocity):
self.x, self.y = anchorPoint
self.xoffset, self.yoffset = anchorPoint
# angle fixed for the equation
self.angle = angle
# variable angle for drawing line in each point (tangent)
self.a = self.angle
# start position for drawing
self.startpos = [self.x-Arrow.LENGTH*math.cos(self.a), self.y+Arrow.LENGTH*math.sin(self.a)]
# end position for drawing line
self.endpos = [self.x+Arrow.LENGTH*math.cos(self.a), self.y-Arrow.LENGTH*math.sin(self.a)]
# velocity and their x and y component
self.velocity = velocity
self.velx = velocity * math.cos(angle)
self.vely = velocity * math.sin(angle)
def update(self):
global GRAVITY
global t
# horizontal distance covered
self.x += self.velx * t
if self.angle == math.pi / 2:
self.y -= self.vely * t - (GRAVITY)*t*t / 2
else:
# y position for given x (translating x and y with the offset)
self.y = self.yoffset-(math.tan(self.angle)*(self.x-self.xoffset)-GRAVITY*(self.x-self.xoffset)**2/(2* self.velocity**2 * math.cos(self.angle)**2))
# change in y component of velocity
self.vely = self.vely - GRAVITY * t
# chane in angle on projectile
self.a = math.atan(self.vely/self.velx)
self.startpos = [self.x-Arrow.LENGTH*math.cos(self.a), self.y+Arrow.LENGTH*math.sin(self.a)]
self.endpos = [self.x+Arrow.LENGTH*math.cos(self.a), self.y-Arrow.LENGTH*math.sin(self.a)]
# drawing anti-aliased line
pygame.draw.aaline(WINDOW, BLACK, self.startpos, self.endpos, 6)
def off_screen(self):
return self.x > WIDTH + Arrow.LENGTH or self.y > HEIGHT + Arrow.LENGTH
|
16fdf9cba56f918df91b08d729eabda5eb248ffc | CallmeChenChen/leetCodePractice | /1_twoSum.py | 474 | 3.5625 | 4 | '''
1. two sum
'''
class Solution(object):
def twoSum(self, nums, target):
tmp = {}
for i in nums:
if target - i in tmp:
first_index = tmp.get(target - i)
second_index = len(tmp)
return first_index, second_index
tmp[i] = len(tmp)
if __name__ == '__main__':
nums = [2, 7, 11, 15]
target = 18
s = Solution()
r = s.twoSum(nums=nums, target=target)
print(r) |
1aecee7cc5007bce58d846d4325ea7108af3cde3 | vitorvicente/LearningPython | /Basics/DataTypes.py | 1,528 | 3.640625 | 4 | # Data Types
print("Data Types:")
x = "Hello World"
print(x, type(x))
x = 20
print(x, type(x))
x = 20.5
print(x, type(x))
x = 1j
print(x, type(x))
x = ["apple", "banana", "cherry"]
print(x, type(x))
x = ("apple", "banana", "cherry")
print(x, type(x))
x = range(6)
print(x, type(x))
x = {"name" : "John", "age" : 36}
print(x, type(x))
x = {"apple", "banana", "cherry"}
print(x, type(x))
x = frozenset({"apple", "banana", "cherry"})
print(x, type(x))
x = True
print(x, type(x))
x = b"Hello"
print(x, type(x))
x = bytearray(5)
print(x, type(x))
x = memoryview(bytes(5))
print(x, type(x))
print("\n")
# Setting Specific Data Types
print("Setting Specific Data Types:")
x = str("Hello World")
print(x, type(x))
x = int(20)
print(x, type(x))
x = float(20.5)
print(x, type(x))
x = complex(1j)
print(x, type(x))
x = list(("apple", "banana", "cherry"))
print(x, type(x))
x = tuple(("apple", "banana", "cherry"))
print(x, type(x))
x = range(6)
print(x, type(x))
x = dict(name="John", age=36)
print(x, type(x))
x = set(("apple", "banana", "cherry"))
print(x, type(x))
x = frozenset(("apple", "banana", "cherry"))
print(x, type(x))
x = bool(5)
print(x, type(x))
x = bytes(5)
print(x, type(x))
x = bytearray(5)
print(x, type(x))
x = memoryview(bytes(5))
print(x, type(x))
print("\n")
# Casting
print("Type Casting:")
x = int(1)
y = int(2.8)
z = int("3")
print(x, y, z)
x = float(1)
y = float(2.8)
z = float("3")
w = float("4.2")
print(x, y, z, w)
x = str("s1")
y = str(2)
z = str(3.0)
print(x, y, z)
|
880b9c506880351a87bc24dc4a62a10f0d9cb5a9 | elainedo/python_practice | /Array/NextPermuation.py | 598 | 3.515625 | 4 | def next_permutation(nums):
# find the non increasing part at the end
last_index = len(nums)-2
while (last_index >= 0):
if nums[last_index] < nums[last_index+1]:
break
last_index -= 1
if last_index == -1:
nums[:] = reversed(nums)
return nums
for i in reversed(range(last_index+1, len(nums))):
if nums[i] > nums[last_index]:
nums[i], nums[last_index] = nums[last_index], nums[i]
break
nums[last_index+1:] = reversed(nums[last_index+1:])
return nums
print(next_permutation([6,2,1,5,4,3,0])) |
75b820e4dd9e58513765cbebec227e8d4b059f31 | TrickFF/helloworld | /random_ex.py | 550 | 3.828125 | 4 | from random import randint, choice, sample, shuffle
# 1 загадать случайное число от 0 до 100
print(randint(0, 100))
# 2 выбрать победителя лотереи из списка players
players = ['Max', 'Leo', 'Kate', 'Ron', 'Bill']
print(choice(players))
# 3 Выбрать 3х победителей лотереи
print(sample(players, 3))
# 4 перемешать карты в списке cards
cards = ['6', '7', '8', '9', '6', '7', '8', '9', 'T', 'J', 'K', 'A']
print(cards)
shuffle(cards)
print(cards) |
46900163ce8a1f4f482adf1865a3ef2115cb5757 | futeen/playboy | /usual_code/pandas_sort.py | 1,605 | 3.78125 | 4 | import pandas as pd
import numpy as np
def pandas_sort():
df = pd.DataFrame({'col1': ['A', 'A', 'B', np.nan, 'D', 'C'],
'col2': [2, 1, 9, 8, 7, 7],
'col3': [0, 1, 9, 4, 2, 8]
})
# 依据第一列排序,并将该列空值放在首位
one = df.sort_values(by=['col1'], na_position='first')
'''
col1 col2 col3
3 NaN 8 4
0 A 2 0
1 A 1 1
2 B 9 9
5 C 7 8
4 D 7 2
'''
# 依据第二、三列,数值降序排序
two = df.sort_values(by=['col2', 'col3'], ascending=False)
'''
col1 col2 col3
2 B 9 9
3 NaN 8 4
5 C 7 8
4 D 7 2
0 A 2 0
1 A 1 1
'''
# 根据第一列中数值排序,按降序排列,并替换原数据
three = df.sort_values(by=['col1'], ascending=True, inplace=False, na_position='first')
'''
col1 col2 col3
3 NaN 8 4
0 A 2 0
1 A 1 1
2 B 9 9
5 C 7 8
4 D 7 2
'''
x = pd.DataFrame({'x1': [1, 2, 2, 3], 'x2': [4, 3, 2, 1], 'x3': [3, 2, 4, 1]})
# 按照索引值为0的行,即第一行的值来降序排序, axis=0 列, axis=1, 行
four = x.sort_values(by=0, ascending=False, axis=1)
'''
x2 x3 x1
0 4 3 1
1 3 2 2
2 2 4 2
3 1 1 3
'''
print(x.mean(axis=1))
if __name__ == "__main__":
pandas_sort()
|
7442fabe19959a3c9f056c4e5d6da9f5b8c1b5a9 | agnewfarms/adventofcode | /Day2/Day2.py | 4,574 | 3.59375 | 4 | <<<<<<< HEAD
from operator import itemgetter
def read_input():
rules_with_data = []
with open('Inputday2.txt') as reader:
lines = reader.readlines()
for line in lines:
elements = line.split(' ')
iterations_of_char = elements[0]
char = elements[1][0]
data = elements[2].strip()
try:
iteration_elements = iterations_of_char.split('-')
first_int = int(iteration_elements[0])
second_int = int(iteration_elements[1])
except ValueError:
print("Iterations of char input contained non-int data")
process.exit(1)
rules_with_data.append({
'first_int': first_int,
'second_int': second_int,
'char': char,
'data': data
})
return rules_with_data
def sled_rental_valid_password(rule_with_data):
char_iteration = 0
for character in rule_with_data['data']:
if character == rule_with_data['char']:
char_iteration+=1
if rule_with_data['first_int'] <= char_iteration <= rule_with_data['second_int']:
return True
return False
def char_at_index(char, data, idx):
try:
return data[idx-1] == char
except IndexError:
return False
def toboggan_valid_password(rule_with_data):
char, data, first_int, second_int = itemgetter('char', 'data', 'first_int', 'second_int')(rule_with_data)
found_at_first_pos = char_at_index(char, data, first_int)
found_at_second_pos = char_at_index(char, data, second_int)
return found_at_first_pos != found_at_second_pos
def main():
data_rules = read_input()
sled_rental_valid_password_count = 0
toboggan_valid_password_count = 0
for data_rule in data_rules:
sled_rental_valid_password_count += 1 if sled_rental_valid_password(data_rule) else 0
toboggan_valid_password_count += 1 if toboggan_valid_password(data_rule) else 0
print("Sled rental place valid passwords in input file: %d" % sled_rental_valid_password_count)
print("Toboggan place valid passwords in input file: %d" % toboggan_valid_password_count)
if __name__ == '__main__':
main()
=======
from operator import itemgetter
def read_input():
rules_with_data = []
with open('Inputday2.txt') as reader:
lines = reader.readlines()
for line in lines:
elements = line.split(' ')
iterations_of_char = elements[0]
char = elements[1][0]
data = elements[2].strip()
try:
iteration_elements = iterations_of_char.split('-')
first_int = int(iteration_elements[0])
second_int = int(iteration_elements[1])
except ValueError:
print("Iterations of char input contained non-int data")
process.exit(1)
rules_with_data.append({
'first_int': first_int,
'second_int': second_int,
'char': char,
'data': data
})
return rules_with_data
def sled_rental_valid_password(rule_with_data):
char_iteration = 0
for character in rule_with_data['data']:
if character == rule_with_data['char']:
char_iteration+=1
if rule_with_data['first_int'] <= char_iteration <= rule_with_data['second_int']:
return True
return False
def char_at_index(char, data, idx):
try:
return data[idx-1] == char
except IndexError:
return False
def toboggan_valid_password(rule_with_data):
char, data, first_int, second_int = itemgetter('char', 'data', 'first_int', 'second_int')(rule_with_data)
found_at_first_pos = char_at_index(char, data, first_int)
found_at_second_pos = char_at_index(char, data, second_int)
return found_at_first_pos != found_at_second_pos
def main():
data_rules = read_input()
sled_rental_valid_password_count = 0
toboggan_valid_password_count = 0
for data_rule in data_rules:
sled_rental_valid_password_count += 1 if sled_rental_valid_password(data_rule) else 0
toboggan_valid_password_count += 1 if toboggan_valid_password(data_rule) else 0
print("Sled rental place valid passwords in input file: %d" % sled_rental_valid_password_count)
print("Toboggan place valid passwords in input file: %d" % toboggan_valid_password_count)
if __name__ == '__main__':
main()
>>>>>>> db1c44c90b7e7d467049dbdda56832b530541efb
|
3d984868de8bfeeccb21535df0723d389683da15 | Reginald-Lee/biji-ben | /uoft/CSC148H1F Intro to Comp Sci/@week1_object_oriented/@@Lab1/console.py | 1,386 | 4.15625 | 4 | # Lab 1 - Python (Re-)Introduction
#
# CSC148 Fall 2014, University of Toronto
# Instructor: David Liu
# ---------------------------------------------
"""Lab 1: interactive console.
This module contains a script to run an interactive console,
in which the user types in commands and sees results.
Your task is to add to the (very bare) functionality.
"""
import sys
# Constants in Python generally named with ALL_CAPS
EASTER_EGG = 'I\'m giving up on you'
EASTER_EGG_RESPONSE = 'That\'s not very nice!'
def start_interaction():
""" () -> NoneType
Begin an infinite loop that repeatedly asks for a command
and then executes an action.
"""
# Loop infinitely
while True:
# Prints 'Say something: ' and then waits for user input
# Note: line gets a string value
line = input('Say something: ')
# Right now, not very interesting...?
if line == EASTER_EGG:
print(EASTER_EGG_RESPONSE)
else:
print(repeat(line))
def repeat(s):
""" (str) -> str
Return a string identical to the input.
Note the difference between *returning* a string and printing it out!
Params
- s: string to repeat
"""
return s
# This is the main function; called when program is run.
if __name__ == '__main__':
start_interaction()
|
2af62fb3d3e8a39e5b4f248ff907632b5ab9036b | teslastine08/py_nielit | /programs/tot_avg.py | 195 | 3.8125 | 4 | a=int(input("enter no-1"))
b=int(input("enter no-2"))
c=int(input("enter no-3"))
d=int(input("enter no-4"))
e=int(input("enter no-5"))
x=(a+b+c+d+e)
y=(x/5)
print("total:",x)
print("average:",y)
|
b255fdf34e22a4165490cdca3b6a1c6e64f12f1d | Jeremy277/exercise | /pytnon-month01/month01-shibw-notes/day08-shibw/demo02-函数实参传递方式.py | 1,069 | 3.9375 | 4 | '''
函数传参
实参传递方式
'''
def fun01(a,b,c):#形参 a b c
print(a)
print(b)
print(c)
#位置实参 实参是根据位置与形参对应的
#如果实参位置发生改变 会影响函数结果
# fun01(10,20,30)
# fun01(30,10,20)
#序列实参 用*将序列中的元素拆开然后与形参依次对应
#序列 字符串 列表 元组
list01 = [10,20,30]
fun01(*list01)
# str01 = 'abcd'
# fun01(*str01)#报错
#关键字实参
#实参的值与形参的名称对应
# fun01(a=10,b=20,c=30)
#使用关键字实参 传参的顺序可以不固定
# fun01(c=30,a=10,b=20)
# fun01(a=10,b=20,d=40)#错误
#字典实参 使用**将字典拆开,字典中的键值对以关键字的形式进行对应,传递值
dict01 = {'a':10,'b':20,'c':30}
# a = 10 , b = 20 ,c = 30
fun01(**dict01)
#字典中的键的名字要与形参名对应
# dict01 = {'a':10,'e':20,'d':30}
# fun01(**dict01)#报错
# 混合使用
# 语法规定 先写位置参数 再写关键字参数
# fun01(10,20,c=30)
# fun01(c=30,b=20,10)#报错
# fun01(10,c=30,b=20)
|
2d7a66e54b79c527d2203b57a0e5b1b9ef0a67da | apollokit/snippets | /python/algs/dfs.py | 1,178 | 3.859375 | 4 | from Graph import Graph
from Queue import MyQueue
from Stack import MyStack
def get_children_vertices(graph, vertex):
children = []
edge_list = graph.array[vertex]
if not edge_list.is_empty():
node = edge_list.head_node
while node is not None:
children.append(node.data)
node = node.next_element
return children
def dfs_traversal(g, source):
result = ""
num_of_vertices = g.num_vertices
# Write - Your - Code
# For the above graph, it should return "01234" or "02143" etc
visited = ""
expand_queue = MyStack()
nodes = range(g.num_vertices)
for child in nodes:
expand_queue.push(child)
expand_queue.push(source)
visited_set = set()
while not expand_queue.is_empty():
vertex = expand_queue.pop()
if vertex in visited_set:
continue
visited_set.add(vertex)
visited += str(vertex)
children = get_children_vertices(g, vertex)
print("vertex")
print(vertex)
print("children")
print(children)
for child in children:
expand_queue.push(child)
return visited |
5cfa6cf0ac7fb2fa986a7b0416ba7420fe2aa76c | celsopa/CeV-Python | /mundo02/ex037.py | 704 | 4.1875 | 4 | # Exercício Python 037: Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal.
n = int(input("Digite um número inteiro qualquer: "))
print(f"""--- MENO DE CONVERSÃO ---
[1] Binário
[2] OCTAL
[3] HEXADECIMAL""")
base = int(input("Escolha a base de conversão: "))
if base == 1:
print(f"O decimal {n} para Binário é: {bin(n).strip('0b').upper()}")
elif base == 2:
print(f"O decimal {n} para Octal é: {oct(n).strip('0c').upper()}")
elif base == 3:
print(f"O decimal {n} para Hexadecimal é: {hex(n).strip('0x').upper()}")
else:
print("Base inválida!")
|
ebe53a51ca70f7bb410a1f79089c6edfd282e581 | SaiSharanyaY/HackerRank | /Finding the percentage.py | 988 | 4.15625 | 4 | " " "
The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of the marks array for the student name provided, showing 2 places after the decimal.
Output Format
Print one line: The average of the marks obtained by the particular student correct to 2 decimal places.
Sample Input 0
3
Krishna 67 68 69
Arjun 70 98 63
Malika 52 56 60
Malika
Sample Output 0
56.00
Explanation 0
Marks for Malika are whose average is
Sample Input 1
2
Harsh 25 26.5 28
Anurag 26 28 30
Harsh
Sample Output 1
26.50
" " "
# code
if __name__ == '__main__':
n = int(raw_input())
student_marks = {}
for _ in range(n):
line = raw_input().split()
name, scores = line[0], line[1:]
scores = map(float, scores)
student_marks[name] = scores
query_name = raw_input()
query_scores=student_marks[query_name]
print('{0:.2f}'.format(sum(query_scores)/len(query_scores)))
|
fd64560e5a34c634cb2e49dd6089271c44a2fb56 | krisnadiputra/100knock | /ch1/2.py | 180 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
a = u"パトカー"
b = u"タクシー"
for i in range(len(a)+len(b)):
if i%2:
print b[i/2]
else :
print a[i/2]
|
c478079708e8d4b50e046e7f1a2ce0776374bbc6 | PariaSabet/PythonAlgorithms | /Sum.py | 524 | 4 | 4 | # this program adds the digits of an integer repeatedly
# until the sum is a single digit
number = int(input("please enter a number"))
def sumOfDigits(x):
summary = 0
while x > 0:
add = x%10
summary = add + summary
x = int(x/10)
if summary > 9:
final = summary
sumOfDigits(final)
else:
print(summary)
sumOfDigits(number)
# a better solution
i = input("")
final = sum(list(map(int,i)))
while final > 9:
final = sum(list(map(int,str(final))))
print(final)
|
6812e1de0e1f7e36851db5ac4c1bc2ec5642778d | wenjie-lu/AOC2020 | /day3.py | 605 | 3.640625 | 4 | from pathlib import Path
def read_file_by_line(input_path):
with open(input_path, 'r') as f:
string = f.read().splitlines()
return string
def slide(map, dy, dx):
x = y = 0
trees = 0
while x < len(map) - 1:
y = (y + dy) % len(map[x])
x = x + dx
if map[x][y] == '#':
trees += 1
return trees
# input_path = Path('inputs/day3_test.txt')
input_path = Path('inputs/day3.txt')
map = read_file_by_line(input_path)
trees = 1
for dy, dx in [(1,1), (3,1), (5,1), (7,1), (1, 2)]:
trees *= slide(map, dy, dx)
print(trees)
|
a3373551419399b982f41e3bb8c36bb282eb6b93 | Erihon78/python_start | /children_py/arrays.py | 196 | 4 | 4 | # Generates a list of numbers
# print(list(range(10, 20)))
for x in range(0, 5):
print('You number is %s' % (x + 1))
x = 45
y = 80
while x < 50 and y < 100:
x = x + 1
y = y + 1
print(x, y) |
61d5ca05a684ce20e43dfb935701f9cb1498e2c6 | kitoriaaa/AtCoder | /Problems/abc065_b.py | 231 | 3.75 | 4 | N = int(input())
a_li = [int(input()) for _ in range(N)]
now_i = 1
step = 0
for i in range(1*10**5+10):
step += 1
button = a_li[now_i-1]
now_i = button
if button == 2:
print(step)
exit()
print(-1)
|
6a1c7725575f904ddbf73315fa6211946528529e | Swati213/pythonbasic | /stu.py | 1,683 | 4.03125 | 4 | class student:
"""class variable"""
roll=23
age=23
def __init__(self):
"""global variable"""
self.tot_marks=0
self.percent=0
"""instance variable"""
self.name="Ajay gupta"
self.d_o_b="7/8/1996"
self.age=student.age
self.parent_name="Sumith gupta"
self.collage_name="J.K.COLLAGE"
self.department="IPS"
self.stream="MCA"
self.enroll_no="8000768"
self.roll_no=student.roll
self.gmail="[email protected]"
def getdata(self):
self.subject=["Artificial Intelligence","Data Mining","Digital Communication","Image Processing","Computer Security"]
self.marks=[67,89,56,74,54]
for i in range(0,len(self.marks)):
self.tot_marks=self.tot_marks + self.marks[i]
self.percent=self.tot_marks/5
def printdata(self):
print("name:{0} \n d_o_b:{1} \n age:{2} \n parent_name:{3}\n collage_name:{4}\n department:{5} \n stream:{6}\n enroll_no:{7}\n roll_no:{8} \n gmail:{9} ".format(self.name,self.d_o_b,self.age,self.parent_name,self.collage_name,self.department,self.stream,self.enroll_no,self.roll_no,self.gmail))
print("subject:",self.subject)
print("marks:",self.marks)
print("total marks:",self.tot_marks)
print("percentage:",self.percent)
obj=student()
obj.getdata()
obj.printdata()
print("student.__doc__:",student.__doc__)
print("student.__name__:",student.__name__)
print("student.__bases__:",student.__bases__)
print("student.__module__:",student.__module__)
print("student.__dict__:",student.__dict__)
print (obj.__dict__)
|
e6642965bb3b9eedb196459fdc0b3e1e675b679a | le-n-qui/sentimental-analysis | /rmp_scraper.py | 11,747 | 3.546875 | 4 | import bs4
import requests
import json
import csv
import selenium.webdriver as webdriver
# ----------------------------------------------------------
# Turn webpage into a parseable BeautifulSoup object
# which represents the document as a nested data structure
# ----------------------------------------------------------
def getSoup(url):
get_response = requests.get(url)
soup = bs4.BeautifulSoup(get_response.text, "html.parser")
return soup
# ----------------------------------------------------------
# Get a list of all occurrences of a particular class
# in the soup (note: type can be "div", "a", etc.)
# Returns ResultSet of tags
# ----------------------------------------------------------
def getClassInstances(soup, type, givenClass):
result = soup.find_all(type, class_=givenClass)
return result
# ----------------------------------------------------------
# Get the first of all occurrences of a particular class
# in the soup (note: type can be "div", "a", etc.)
# Returns a tag, which is a list containing a single object
# ----------------------------------------------------------
def getFirstClassInstance(soup, type, givenClass):
result = soup.find_all(type, class_=givenClass)
if (len(result) >= 1):
return result[0]
else:
print("Error: getFirstClassInstance - no class instances found")
exit(0)
# ----------------------------------------------------------
# Sets up selenium webdriver for Chrome
# ----------------------------------------------------------
def getSeleniumDriverForChrome(url):
option = webdriver.ChromeOptions()
option.add_argument("--incognito")
driver = webdriver.Chrome(executable_path='/Users/nsujela/Downloads/chromedriver2', chrome_options=option)
return driver
# ----------------------------------------------------------
# Expands webpage to get all comments for a professor
# ----------------------------------------------------------
def seleniumExpansion(url, driver):
print("Getting driver")
chrome_driver = getSeleniumDriverForChrome(url)
chrome_driver.get(url)
print("Checking for automated test blocker")
close_button = chrome_driver.find_element_by_xpath("//*[@id='cookie_notice']/a[1]")
if close_button is not None:
print("Found close button")
close_button.click()
print("Clicked close button")
else:
print("Did not find close button")
print("Starting expansion")
load_more = chrome_driver.find_element_by_id('loadMore')
print(load_more)
while (True):
if load_more is None:
break
print("Found load more")
load_more.click();
print("Clicked close button")
load_more = chrome_driver.find_element_by_xpath('loadMore')
print("Expansion complete")
# ----------------------------------------------------------
# Compile a database of RMP *reviews* with the following
# column fields: University(K), Professor(K), Average Rating(K),
# Student Ratings (Overall Quality and Level of Difficulty),
# Date, Tags, The Review Itself(K), Would Take Again, Grade
# Received
# ----------------------------------------------------------
def one_iteration(url, global_index):
# HTML Tags
div = "div"
a = "a"
h1 = "h1"
span = "span"
td = "td"
table = "table"
p = "p"
# Expand webpage fully
# Note: load_more button not Selenium-clickable
# Unable to expand
# seleniumExpansion(url, driver)
# Produce BeautifulSoup object for parsing
soup = getSoup(url)
print("-----")
# University Name
uniName = getFirstClassInstance(soup, a, "school").find_all(text=True, recursive=False)
uniName = uniName[0]
print("University: " + uniName)
# Professor Name
profName = getFirstClassInstance(soup, span, "pfname").find_all(text=True, recursive=False) + getFirstClassInstance(soup, span, "plname").find_all(text=True, recursive=False)
profName[0] = profName[0].replace(" ", "").replace('\r', '').replace('\n', '') # First name
profName[1] = profName[1].replace(" ", "").replace('\r', '').replace('\n', '') # Last name
profName = profName[0] + " " + profName[1] # Stringify name
print("Professor: " + profName)
# Average Rating
fivePointRating = getFirstClassInstance(soup, div, "grade").find_all(text=True, recursive=False)
fivePointRating = fivePointRating[0]
print("Average Professor Rating: " + fivePointRating)
# Get all Review Information: Student Ratings, Grade Received, Would Take Again, Date, Tags, Review
table = getFirstClassInstance(soup, table, "tftable")
# Get all reviews
reviewBoxes = getClassInstances(soup, td, "comments")
all_reviews = []
print("-----")
for box in reviewBoxes:
for child in box.children:
if(child.name == 'p'):
print("Review: ")
text = child.text
text_list = text.split(" ")
text_list = text_list[20:] # Get rid of initial 20-ct whitespace
text = " ".join(text_list)
all_reviews.append(text)
# Get all cells
for row in table.find_all("tr")[1:]: # skip header
cells = row.find_all(td)
# Student Ratings: Overall Quality, Level of Difficulty
all_quality = []
all_difficulty = []
quality_set = getClassInstances(soup, span, "score poor")
for i in range(0, len(quality_set)):
all_quality.append(quality_set[i].text)
quality_set = getClassInstances(soup, span, "score average")
for i in range(0, len(quality_set)):
all_quality.append(quality_set[i].text)
quality_set = getClassInstances(soup, span, "score good")
for i in range(0, len(quality_set)):
all_quality.append(quality_set[i].text)
# -- Debugging --
# print("length of all student quality scores")
# print(len(all_quality))
difficulty_set = getClassInstances(soup, span, "score inverse good")
for i in range(0, len(difficulty_set)):
all_difficulty.append(difficulty_set[i].text)
difficulty_set = getClassInstances(soup, span, "score inverse average")
for i in range(0, len(difficulty_set)):
all_difficulty.append(difficulty_set[i].text)
difficulty_set = getClassInstances(soup, span, "score inverse poor")
for i in range(0, len(difficulty_set)):
all_difficulty.append(difficulty_set[i].text)
print("-----")
print("Student Overall Quality Scores: ")
for i in range(0, len(all_quality)):
print(all_quality[i])
print("-----")
print("Student Difficulty Scores: ")
for i in range(0, len(all_difficulty)):
print(all_difficulty[i])
# -- Debugging --
# student_rating_boxes = getClassInstances(soup, td, "rating"_
# print("student rating boxes")
# print(student_rating_boxes[0].text)
# Grade Received
all_letter_grades = []
grade_set = getClassInstances(soup, span, "grade")
for item in grade_set:
grade_text = item.text
grade_text_arr = grade_text.split(": ")
if (len(grade_text_arr) == 2):
letter = grade_text_arr[1]
all_letter_grades.append(letter)
print("-----")
print("Letter Grades: ")
for i in range(0, len(all_letter_grades)):
print(all_letter_grades[i])
all_would_take_again = []
would_take_again_set = getClassInstances(soup, span, "would-take-again")
for item in would_take_again_set:
text = item.text
text_arr = text.split(": ")
if (len(text_arr) == 2):
would_take_again = text_arr[1]
all_would_take_again.append(would_take_again)
print("-----")
print("Would Take Again: ")
for i in range(0, len(all_would_take_again)):
print(all_would_take_again[i])
all_annotations = []
print("-----")
print("Annotation: ")
for i in range(0, len(all_would_take_again)):
if (all_would_take_again[i] == "Yes"):
all_annotations.append("pos")
elif (all_quality[i] == "3") or (all_quality[i] == "4") or (all_quality[i] == "5"):
all_annotations.append("pos")
else:
all_annotations.append("neg")
for annotation in all_annotations:
print(annotation)
filename = "rmp_dump.csv"
with open(filename, 'a') as f1:
writer = csv.writer(f1, delimiter=',')
index = 0;
# Annotate training set, not testing set
for i in range(0, len(all_reviews)):
if (global_index <= 4000):
writer.writerow([index, uniName, profName, fivePointRating, all_reviews[i], all_letter_grades[i], all_quality[i], all_difficulty[i], all_would_take_again[i], all_annotations[i]])
index += 1
elif (global_index > 4000):
writer.writerow([index, uniName, profName, fivePointRating, all_reviews[i], all_letter_grades[i], all_quality[i], all_difficulty[i], all_would_take_again[i], ""])
index += 1
# ------------------------------------------------------------
# * MAIN *
# - Annotated training set: 4000 reviews
# - Non-annotated testing set: 1000 reviews
# ------------------------------------------------------------
def main():
# Set up CSV header
filename = 'rmp_dump.csv'
with open(filename, 'w') as f1:
writer = csv.writer(f1, delimiter=',')
writer.writerow(["#", "University", "Professor", "Average Rating", "Review", "Grade Received", "Quality", "Difficulty", "Would Take Again", "Annotation"])
template_url = "http://www.ratemyprofessors.com/ShowRatings.jsp?tid="
# Get 10 reviews
count = 0
for i in range(111111,999999):
if (count > 5000):
break
url = template_url + str(i)
response = requests.get(url)
bs = getSoup(url)
page_not_found_set = getClassInstances(bs, "div", "header error")
if (len(page_not_found_set) > 0):
print("Page not found")
else:
# driver = getSeleniumDriverForChrome(url)
print(url)
try:
print("Count: ")
print(count)
one_iteration(url, count)
count +=1
continue
except:
print("This iteration failed. Moving to the next one...")
continue
# ----------
# S T A R T
# ----------
main()
# ----------
# E N D
# ----------
# --- OLD SCRAPERWIKI SCRIPT ---
# import scraperwiki
# from bs4 import BeautifulSoup
# import string
# import unicodedata
# import time
# headers = ["Name","Department","Total Ratings","Overall Quality","Easiness","Hot"]
# #Dictionary of school ids (keys) that map to tuple of school name and number of pages
# colleges = {"580":("MIT",16),"1222":("Yale",23),"181":("CMU",28), "1085":("UChicago",28),"1040":("Tufts",46), "1350":("Duke",84),"1255":("UTexas",84),"953":("Stanford",32),"799":("Rice",17),"780":("Princeton",16)}
# for sid in colleges.keys():
# college,pages = colleges[sid]
# print college
# html = scraperwiki.scrape("http://www.ratemyprofessors.com/")
# for i in xrange(1,pages+1):
# response = scraperwiki.scrape("http://www.ratemyprofessors.com/SelectTeacher.jsp?sid=%s&pageNo=%s" % (sid,str(i)))
# time.sleep(5)
# soup = BeautifulSoup(response)
# rows = soup.find_all("div",{"class":"entry odd vertical-center"})
# rows.extend(soup.find_all("div",{"class":"entry even vertical-center"}))
# for row in rows:
# columns = row.find_all('div')
# columns = columns[3:]
# variables = {}
# for i,col in enumerate(columns):
# value = unicodedata.normalize('NFKD', col.text).encode('ascii', 'ignore')
# variables[headers[i]] = value
# variables["College"] = college
# scraperwiki.sqlite.save(unique_keys=['Name',"Department"], data = variables) |
39345774aa9079a34313b4b34e38d1099b8e515c | cnovacyu/python_practice | /automate_the_boring_stuff/Chapter9_FillGaps.py | 991 | 3.578125 | 4 | #! python3
# Find all files with a given prefix such as spam001.txt, spam002.txt, etc
# in a single folder and locate any gaps in the numbering. Rename all later
# files to close the numbering gap.
import os, argparse, shutil
# create args for selecting folder to check numbering of files
parser = argparse.ArgumentParser()
parser.add_argument('src', help='folder to check numbering of files')
parser.add_argument('starts_with', help='file names to check start with:')
parser.add_argument('file_type', help='specify file type to check')
args = parser.parse_args()
# set args to variables
src = args.src
starts_with = args.starts_with
file_type = args.file_type
# change directory to folder arg
os.chdir(src)
# check for gaps in filename numbering. If any gaps, rename file to fill in gap
num = 1
for filename in os.listdir(src):
stdfilename = starts_with + str(num).zfill(3) + file_type
if not os.path.exists(stdfilename):
shutil.move(filename, stdfilename)
num += 1 |
32448cfb69a4251b203344f94fc162d13a173d86 | hyun-soo-park/Algorithm | /18장/65.py | 642 | 3.84375 | 4 | #https://leetcode.com/problems/binary-search/
class Solution:
def search(self, nums: List[int], target: int) -> int:
def binary_search(bin_list, start, end, target):
if start > end:
return -1
mid = (start + end) // 2
if bin_list[mid] == target:
return mid
elif bin_list[mid] < target:
return binary_search(bin_list, mid + 1, end, target)
elif bin_list[mid] > target:
return binary_search(bin_list, start, mid - 1, target)
nums.sort()
return binary_search(nums, 0, len(nums) - 1, target) |
ecebef5015ddfebbc897d7411b42d7658d11ea99 | Dadajon/100-days-of-code | /competitive-programming/hackerrank/algorithms/implementation/039-find-digits/find-digits.py | 603 | 4.28125 | 4 | def find_digits(n):
"""
The function should return an integer representing the number of digits of d that are divisors of d.
:param n: an integer to analyze
:return: for every test case, count the number of digits in n that are divisors of n
"""
cnt = 0
tmp = n
while tmp > 0:
digit = tmp % 10
if digit != 0 and n % digit == 0:
cnt += 1
tmp //= 10
return cnt
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
n = int(input())
result = find_digits(n)
print(str(result) + '\n')
|
3e8f777a01f2a65cb19972bd24a79168710489f8 | Charlie-Toro/automate-Python | /isPhone.py | 749 | 4.21875 | 4 | # isPhone
# Caleb Bell
# Provided a string of numbers, determines if the format is correct for phone number
def isPhoneNumber(text):
"""Checks validity of phone number provided"""
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if text[7] != '-':
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
print(isPhoneNumber('2222222222222222222222'))
print(isPhoneNumber('212-345-1254')) |
3fbb6548abdd5e5f2b3dd7d5bb48af84a40d3a8a | amiraHag/hackerrank-30-days-of-code | /day7.py | 301 | 3.75 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def printArray(array):
for i in range (len(array)):
print(array[len(array) - i -1], end =" ")
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
printArray(arr)
|
7afeb35493bc4d86c898eb568d2a35c8bd8d9634 | BenjiFuse/aoc-2020 | /Day2/Part2.py | 509 | 3.796875 | 4 | import re
from itertools import accumulate
pattern = r'(\d+)-(\d+) (.): (.+)'
regex = re.compile(pattern)
def is_valid(s):
m = regex.fullmatch(s)
min = int(m.group(1))
max = int(m.group(2))
char = m.group(3)
password = m.group(4)
return (password[min-1] == char) ^ (password[max-1] == char)
with open("input.txt") as f:
passwords = [l.strip() for l in f.readlines()]
valid_count = sum(map(is_valid, passwords))
print("Number of valid passwords: {0}".format(valid_count)) |
a01c14496ada76b54b9dfd68daf7ca1d0b2dcc0d | oraocp/pystu | /primitive/base/statical.py | 2,679 | 3.953125 | 4 | """
文档目的:演示Python中的统计模块的用法
创建日期:2017/11/16
演示内容包括:
1. 平均数
2. 中位数
3. 高低中位数
4. 总体方差 = 总体标准差^2
5. 样本方差 = 样本标准差^2
"""
import math
from fractions import Fraction as F
from statistics import mean, median, median_low, median_high, pvariance, pstdev
# ======定义测试数据======== #
data = [i for i in range(1, 5)]
data2 = [i for i in range(1, 6)]
dataF = [F(3, 7), F(1, 21), F(5, 3), F(1, 3)]
def calc_mean():
print('测试平均数 ...')
print("sum(data)/len(data)=", sum(data) / len(data))
print("mean(data)=", mean(data))
print("mean(dataF)=%4.2f" % mean(dataF))
print('')
def calc_median():
print('测试中位数 ...')
print("median(data)=%4.2f" % median(data)) # [1,2,3,4]取中间两数平均值
print("median(data2)=%4.2f" % median(data2)) # [1,2,3,4,5]取中间值
print("median(dataF)=%4.2f" % median(dataF))
print('')
print('测试高、低中位数 ...')
print("median_low(data)=%4.2f" % median_low(data)) # [1,2,3,4]取中间小值2
print("median_high(data)=%4.2f" % median_high(data)) # [1,2,3,4]取中间大值3
print("median_low(data2)=%4.2f" % median_low(data2)) # [1,2,3,4,5]取中间小值3
print("median_high(data2)=%4.2f" % median_high(data2)) # [1,2,3,4,5]取中间大值3
print("median_grouped(dataF)=%4.2f" % median(dataF))
print('')
def calc_pvariance():
print('测试总体方差 ...')
'''
data=[1,2,3,4] 均值为2.5
'''
print((sum([(x - 2.5) ** 2 for x in data]) / len(data)))
print("pvariance(data)=%4.2f" % pvariance(data))
print("pvariance(data, mu)=%4.2f" % pvariance(data, mean(data)))
print("pvariance(data, 12)=%4.2f" % pvariance(data, 12)) # 计算时并不会用给出的平均数值
print("pvariance(data2)=%4.2f" % pvariance(data2))
print("pvariance(data2, mu)=%4.2f" % pvariance(data2, mean(data)))
print("pvariance(dataF)=%4.2f" % pvariance(dataF))
print('')
def calc_pstdev():
print('测试总体标准差 ...')
print("pstdev(data)=sqrt(pvariance(data))=%4.2f" % math.sqrt(pvariance(data)))
print("pstdev(data)=%4.2f" % pstdev(data))
print("pstdev(data, mu)=%4.2f" % pstdev(data, mean(data)))
print("pstdev(data, 12)=%4.2f" % pstdev(data, 12)) # 计算时并不会用给出的平均数值
print("pstdev(data2)=%4.2f" % pstdev(data2))
print("pstdev(data2, mu)=%4.2f" % pstdev(data2, mean(data)))
print("pstdev(dataF)=%4.2f" % pstdev(dataF))
print('')
if __name__ == "__main__":
calc_mean()
calc_median()
calc_pvariance()
calc_pstdev()
|
60fbdacb1cc6560ff23567360f0dcf86cfecca80 | mikerojaswa/PythonSnippets | /Graphs/Graph_DFS_Iterative.py | 375 | 3.796875 | 4 | graph = {'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']}
def dfs(graph, start):
visited = set()
stack = [start]
while stack:
s = stack.pop()
if s not in visited:
visited.add(s)
for node in graph[s]:
if node not in visited:
stack.append(node)
return visited
dfs(graph, 'A')
|
7c6a1ef4d4e2b1d5ba69931dede8cedb762e1454 | hofernandes/python3-mundo-1 | /ex004.py | 530 | 4.09375 | 4 | # Dissecando uma Variável
n=input('Escreva algo: ')
print ('O tipo primitivo é: {}'.format(type(n)))
print('Esta string é número? : {}'.format(n.isnumeric()))
print('Esta string são caracteres? :{}'.format(n.isalpha()))
print('Esta string são números ou caracteres? {}'.format(n.isalnum()))
print('Esra string são maicuscas? {}'.format(n.isupper()))
print('Esta string são minusculas? {}'.format(n.islower()))
print ('Só tem espaços? {}'.format(n.isspace()))
print ('Esta capitalizada? {n.istitle}'.format(n.istitle())) |
ce05b7a544d6d3ea6836f8c249fa6497941da91b | Darpan28/PythonWallet | /untitled1/venv/HomeView.py | 10,038 | 3.53125 | 4 | import mysql.connector
from tkinter import *
import datetime as dt
phone = ""
transferPhone = ""
def dateTime():
global today
today = dt.datetime.today()
class customer:
def __init__(self,name,phone,balance):
self.name = name
self.phone = phone
self.balance = balance
class dbHelper():
def saveCustomerInDB(self,cust1):
sql = "insert into wallets values('{}','{}','{}')".format(cust1.name,cust1.phone,cust1.balance)
con = mysql.connector.connect(user = "root",password ="",host = "localhost",database = "banking")
cursor = con.cursor()
cursor.execute(sql)
con.commit()
def saveCustomerInTransAdd(self,phone,amountEntered,today):
sql1 = "insert into transaction values('{}','{}','Deposite','{}')".format(phone,amountEntered,today)
con1 = mysql.connector.connect(user = "root",password ="",host = "localhost",database = "banking")
cursor1 = con1.cursor()
cursor1.execute(sql1)
con1.commit()
def saveCustomerInTransWithdraw(self,phone,amountEntered,today):
sql1 = "insert into transaction values('{}','{}','Withdraw','{}')".format(phone,amountEntered,today)
con1 = mysql.connector.connect(user = "root",password ="",host = "localhost",database = "banking")
cursor1 = con1.cursor()
cursor1.execute(sql1)
con1.commit()
def saveCustomerInTransTransfer(self,phone,amountEntered,transferPhone,today):
sql1 = "insert into transaction values('{}','{}','transfer to''{}','{}')".format(phone,amountEntered,transferPhone,today)
con1 = mysql.connector.connect(user = "root",password ="",host = "localhost",database = "banking")
cursor1 = con1.cursor()
cursor1.execute(sql1)
con1.commit()
def updateCustomerInDB(self,balance,phone):
sql = "update wallets set balance = '{}' where phone = '{}'".format(balance,phone)
con = mysql.connector.connect(user="root", password="", host="localhost", database="banking")
cursor = con.cursor()
cursor.execute(sql)
con.commit()
def fetchAccount(phone):
sql = "select * from wallets where phone = '{}'".format(phone)
con = mysql.connector.connect(user="root", password="", host="localhost", database="banking")
cursor = con.cursor()
cursor.execute(sql)
global row
row = cursor.fetchone()
def fetchAccountTransfer(transferPhone):
sql = "select * from wallets where phone = '{}'".format(transferPhone)
con = mysql.connector.connect(user="root", password="", host="localhost", database="banking")
cursor = con.cursor()
cursor.execute(sql)
global transferRow
transferRow = cursor.fetchone()
def addCustomer(name,phone,balance):
cust1 = customer(name,phone,balance)
dbhelp = dbHelper()
dbhelp.saveCustomerInDB(cust1)
def updateCustomerAdd(amount,phone):
balance = row[2] + amount
dbhelp = dbHelper()
dbhelp.updateCustomerInDB(balance,phone)
def updateCustomerWithdraw(amount,phone):
balance = row[2] - amount
dbhelp = dbHelper()
dbhelp.updateCustomerInDB(balance,phone)
def updateCustomerTransfer(amount,phone,transferPhone):
balance = row[2] - amount
balance2 = transferRow[2] + amount
dbhelp = dbHelper()
dbhelp.updateCustomerInDB(balance, phone)
dbhelp.updateCustomerInDB(balance2, transferPhone)
def addTransactionAdd(phone, amount,today):
dbhelper = dbHelper()
dbhelper.saveCustomerInTransAdd(phone,amount,today)
def addTransactionWithdraw(phone, amount,today):
dbhelper = dbHelper()
dbhelper.saveCustomerInTransWithdraw(phone,amount,today)
def addTransactionTransfer(phone, amount, transferPhone,today):
dbhelper = dbHelper()
dbhelper.saveCustomerInTransTransfer(phone,amount,transferPhone,today)
def onClickSubmit():
global phone
phone = entryMobile.get()
fetchAccount(phone)
if row is not None:
window.destroy()
exists()
elif row is None:
window.destroy()
notExist()
def onClickAddAccount():
name = entryName.get()
phn = entryPhone.get()
bal = entryAmount.get()
addCustomer(name,phn,bal)
addTransactionAdd(phn,bal,today)
window4.destroy()
AddCustSucc()
def onClickAddMoney():
window1.destroy()
Add()
def onClickWithdrawMoney():
window1.destroy()
Withdraw()
def onClickTransferMoney():
window1.destroy()
Transfer()
def onClickAdd():
amount = int(entryAdd.get())
dateTime()
updateCustomerAdd(amount,phone)
addTransactionAdd(phone,amount,today)
window2.destroy()
AddSucc()
def onClickWithdraw():
amount = int(entryWithdraw.get())
dateTime()
if amount < row[2] and row[2] >= 1000:
updateCustomerWithdraw(amount,phone)
addTransactionWithdraw(phone,amount,today)
window3.destroy()
WithDrawSucc()
else:
balLow()
def onClickTransfer():
global transferPhone
transferAmount = int(entryTransferAmt.get())
transferPhone = entryTransferPhn.get()
fetchAccountTransfer(transferPhone)
if transferAmount < row[2] and row[2] >= 1000:
if transferRow is not None:
dateTime()
updateCustomerTransfer(transferAmount,phone,transferPhone)
addTransactionTransfer(phone,transferAmount,transferPhone,today)
window5.destroy()
TransferDone()
elif transferRow is None:
window5.destroy()
TransferNotDone()
else:
balLow()
def homeView():
global window
window = Tk()
lblTitle = Label(window, text="Wallet App")
lblTitle.pack()
global entryMobile
lblMobile = Label(window, text="Enter Mobile No.")
lblMobile.pack()
entryMobile = Entry(window)
entryMobile.pack()
btnAddCustomer = Button(window, text="Submit", command=onClickSubmit)
btnAddCustomer.pack()
window.mainloop()
def exists():
global window1
window1 = Tk()
lblExist = Label(window1, text="Account Exists!!")
lblExist.pack()
btnADD = Button(window1, text="Add Money", command=onClickAddMoney)
btnADD.pack()
btnWithdraw = Button(window1, text="Withdraw Money", command=onClickWithdrawMoney)
btnWithdraw.pack()
btnTransfer = Button(window1, text="Transfer Money", command = onClickTransferMoney)
btnTransfer.pack()
window1.mainloop()
def notExist():
global window4
window4 = Tk()
lblnotExist = Label(window4, text="Account does not Exists!!")
lblnotExist.pack()
lblName = Label(window4, text="Enter Name")
lblName.pack()
global entryName
entryName = Entry(window4)
entryName.pack()
lblPhone = Label(window4, text="Enter Mobile No.")
lblPhone.pack()
global entryPhone
entryPhone = Entry(window4)
entryPhone.pack()
lblAmount = Label(window4, text="Enter Amount")
lblAmount.pack()
global entryAmount
entryAmount = Entry(window4)
entryAmount.pack()
btnAddAccount = Button(window4,text ="Add Account",command = onClickAddAccount)
btnAddAccount.pack()
window4.mainloop()
def Add():
global window2
window2 = Tk()
lblAdd = Label(window2, text="Enter Amount")
lblAdd.pack()
global entryAdd
entryAdd = Entry(window2)
entryAdd.pack()
btnAdd = Button(window2, text="ADD", command=onClickAdd)
btnAdd.pack()
window2.mainloop()
def Withdraw():
global window3
window3 = Tk()
lblWithdraw = Label(window3, text="Enter Amount")
lblWithdraw.pack()
global entryWithdraw
entryWithdraw = Entry(window3)
entryWithdraw.pack()
btnWithdraw = Button(window3, text="Withdraw",command = onClickWithdraw)
btnWithdraw.pack()
window3.mainloop()
def Transfer():
global window5
window5 = Tk()
lblTransferAmt = Label(window5, text="Enter Amount")
lblTransferAmt.pack()
global entryTransferAmt
entryTransferAmt = Entry(window5)
entryTransferAmt.pack()
lblTransferPhn = Label(window5, text="Enter Mobile ")
lblTransferPhn.pack()
global entryTransferPhn
entryTransferPhn = Entry(window5)
entryTransferPhn.pack()
btnTransfer = Button(window5, text="Transfer", command = onClickTransfer)
btnTransfer.pack()
window5.mainloop()
def TransferDone():
def onClickOk():
window6.destroy()
window6 = Tk()
lbltransferDone = Label(window6, text="Transfer Done!!")
lbltransferDone.pack()
btnOK = Button(window6, text = "OK !!", command = onClickOk)
btnOK.pack()
window6.mainloop()
def TransferNotDone():
def onClickOk():
window7.destroy()
Transfer()
global window7
window7 = Tk()
lbltransferNot = Label(window7, text="Please Enter Valid Mobile No.!!")
lbltransferNot.pack()
btnOK = Button(window7, text="OK !!", command = onClickOk)
btnOK.pack()
window7.mainloop()
def AddSucc():
def onClickOK():
window8.destroy()
window8 = Tk()
lblSucc = Label(window8,text="Money Added SuccessFully!!")
lblSucc.pack()
btnOk = Button(window8,text = "Ok",command = onClickOK)
btnOk.pack()
window8.mainloop()
def WithDrawSucc():
def onClickOK():
window9.destroy()
window9 = Tk()
lblSucc = Label(window9, text="Withdraw SuccessFully!!")
lblSucc.pack()
btnOk = Button(window9, text="Ok", command=onClickOK)
btnOk.pack()
window9.mainloop()
def AddCustSucc():
def onClickOK():
window10.destroy()
window10 = Tk()
lblSucc = Label(window10, text="Customer Added SuccessFully!!")
lblSucc.pack()
btnOk = Button(window10, text="Ok", command=onClickOK)
btnOk.pack()
window10.mainloop()
def balLow():
def onClickOk():
window11.destroy()
window11 = Tk()
lblLow = Label(window11, text = "Insufficient Balance!!")
lblLow.pack()
btnOk = Button(window11, text = "Ok",command = onClickOk)
btnOk.pack()
window11.mainloop()
homeView()
|
05654cc27295a6bbfbecaaf428be6da29f10127d | kimbumsoo0820/codeup | /20200714_codeup_3/codeup3_16junsoo.py | 79 | 3.578125 | 4 | a = input()
b = int(a,16)
for i in range(1,16):
print("%s*%X=%X"%(a,i,b*i)) |
73d55a37f22bea206ed607cdc3ecc6e896634860 | roden011/sample-code-portfolio | /imgProc.py | 4,835 | 3.65625 | 4 | from ezgraphics import *
from imgProcTools import *
'''
This program requires that the image files be formatted as bitmap (or raster) images. Each pixel has a distinct location in a 2 dimensional matrix (x,y plot or grid) as well as a r(red), g(green),b(blue) color value of 0-255.
https://en.wikipedia.org/wiki/Raster_graphics
'''
def main():
print('-'*75)
print("Welcome to the CSC 131 Image Processing Tools Application!!!")
print()
print("You will be asked to enter the name of an image file that you would like to be displayed (must gif or png format).\nNext you will be prompted to select a processing option from the menu below.")
print()
imgFile = input("Please enter the name of the image file you wish to display: ")
print()
# Load the image from the file and display it in a window.
theImg = GraphicsImage(imgFile)
win = GraphicsWindow()
win.setTitle("CSC 131 Image Processing Tool: " + imgFile)
canvas = win.canvas()
canvas.drawImage(theImg)
done = False
# When the graphics window displays "not responding", it is because of a threading issue and will
# not affect our program. Multithreading is an advanced topic that will be addressed in later courses.
while not done :
# Prompt the user for the type of processing.
print("How should the image be processed? ")
print("1 - create image negative")
print("2 - adjust brigthness")
print("3 - flip vertically")
print("4 - rotate to the left")
print("5 - apply sepia filter")
print("6 - black/white")
print("7 - smooth")
print("8 - detect edge")
print("9 - shrink")
print("10 - greyscale")
print("11 - Negative to Color")
print("12 - Histogram Eq")
print("13 - RGB HistoEQ")
print("14 - Rotate")
print("15 - Warp")
print("16 - quit")
response = int(input("Enter your choice: "))
print()
# Process the image
if response == 1 :
option = "Negative"
newImg = createNegative(theImg)
elif response == 2 :
option = "Adjust Brightness"
amount = float(input("Adjustment between -1.0 and 1.0: "))
newImg = adjustBrightness(theImg, amount)
elif response == 3 :
option = "Flip Vertically"
newImg = flipVertically(theImg)
elif response == 4 :
option = "Rotate Left"
newImg = rotateLeft(theImg)
elif response == 5 :
option = "Sepia"
newImg = sepiaFilter(theImg)
elif response == 6:
option = "Black/White"
newImg = blackWhite(theImg)
elif response == 7:
option = "Smooth"
newImg = smooth(theImg)
elif response == 8:
option = "Detect Edge"
newImg = edgeDetection(theImg)
elif response == 9:
option = "Shrink"
newImg = shrink(theImg)
elif response == 10:
option = "Greyscale"
newImg = greyScale(theImg)
elif response == 11:
option = "Neg to Color"
newImg = createNegative(theImg)
elif response == 12:
option = "Histogram EQ"
newImg = histoEqual(theImg)
elif response == 13:
option = "RGB Histogram EQ"
newImg = colorHistoEqual(theImg)
elif response == 14:
theta = int(input('How many degrees to rotate?: '))
option = "Img Rotation"
newImg = rotateImage(theImg, theta)
elif response == 15:
option = "Img Warping"
newImg = warpImage(theImg)
# win.quit() deystroys all graphic window objects and ends the application
if response == 16 :
win.quit()
done = True
# If quit is not selected, display the processed image in a new window.
else :
newWin = GraphicsWindow()
newCanvas = newWin.canvas()
newWin.setTitle("Image Processing Tool: " + imgFile + " (" + option + ")")
newCanvas.drawImage(newImg)
badInput = True
saveFile = input("Would you like to save the new image? [Y/n]: ")
while badInput:
if saveFile == "Y" or saveFile == "n":
badInput = False
else:
saveFile = input("Invalid input: Please enter [Y/n]: ")
if saveFile == "Y":
name = input("What would you like to name you file? ")
newImg.save(name + ".gif")
if __name__ == '__main__':
main()
|
a96a42887616c1883c08bd5436a40824bc99eb4a | athletejuan/notebook | /Python Daily/calc.py | 249 | 3.5625 | 4 | # Calc.py
def add(a,b):
return a+b
def substract(a,b):
return a-b
def multiply(a,b):
return a*b
def divide(a,b):
return a/b
#print (add(4,2))
#print (substract(4,2))
#print (multiply(4,2))
#print (divide(4,2))
|
77a286927296c9821afdf47cd7eda8291a904ad4 | ssthurai/fullerene-predictor | /fullerene_curvature/sphere.py | 1,163 | 3.71875 | 4 | '''@package sphere helper routines related to spheres.
'''
import numpy
import numpy.linalg
def compute_sphere(point_a, point_b, point_c, point_d):
'''
compute_sphere Given four points, this computes the radius on a sphere
containing them.
point_a:
point_b:
point_c:
point_d:
return: radius of the sphere.
'''
a0 = point_a[0]
a1 = point_a[1]
a2 = point_a[2]
b0 = point_b[0]
b1 = point_b[1]
b2 = point_b[2]
c0 = point_c[0]
c1 = point_c[1]
c2 = point_c[2]
d0 = point_d[0]
d1 = point_d[1]
d2 = point_d[2]
left_matrix = [[a0 - b0, a1 - b1, a2 - b2],
[b0 - c0, b1 - c1, b2 - c2],
[c0 - d0, c1 - d1, c2 - d2]]
right_0 = (a0**2 + a1**2 + a2**2 - b0**2 - b1**2 - b2**2)/2.0
right_1 = (b0**2 + b1**2 + b2**2 - c0**2 - c1**2 - c2**2)/2.0
right_2 = (c0**2 + c1**2 + c2**2 - d0**2 - d1**2 - d2**2)/2.0
right_array = [[right_0],[right_1],[right_2]]
left_array = numpy.dot(numpy.linalg.inv(left_matrix), right_array)
left_array = left_array.T[0]
R = numpy.linalg.norm(point_a - left_array)
return R, left_array
|
68fb900a4a94a3a04acb48d1b1146011416339a0 | TestowanieAutomatyczneUG/laboratorium-11-maciej-witkowski | /src/zad3/friendships.py | 1,055 | 3.921875 | 4 | class FriendShips:
def __init__(self):
self.friends = {}
def addFriend(self, person, friend):
if not (isinstance(person, str) and isinstance(friend, str)):
raise TypeError("Inputs must be of string type!")
if not person or not friend or person.isspace() or friend.isspace():
raise ValueError("Strings cannot be empty!")
if person not in self.friends:
self.friends[person] = [friend]
else:
self.friends[person].append(friend)
def makeFriends(self, person1, person2):
self.addFriend(person1, person2)
self.addFriend(person2, person1)
def getFriendsList(self, person):
if person in self.friends:
return self.friends[person]
else:
return False
def areFriends(self, person1, person2):
if (person1 in self.friends and person2 in self.friends) and (person2 in self.friends[person1] and person1 in self.friends[person2]):
return True
else:
return False
|
46fd6508edb30bc2e2d7818c8b73f9e087720d88 | mizanurrahman13/PythonAbc | /FreeCodeCamp.org/TakingInputFromUser.py | 475 | 4.09375 | 4 | name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + " ! Your are " + age + " Years old now.")
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = num1 + num2
print(result)
# We need int casting number num1 and num2
result = int(num1) + int(num2)
print(result)
# Adding two Float number
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)
print(result) |
de24c1bc42c6224300cb190615d304126f75f26a | AJohnston29/Instrumental-Project | /conversion.py | 4,931 | 3.625 | 4 | #!/usr/bin/python
#Script created by Anthony Johnston
import os
import sys
import argparse
from scipy import misc
import numpy as np
from PIL import Image
#RGB to Grayscale Conversion Function
def GrayScale(filename):
#Defines the weighted average formula for luminosity
def LuminosityMethod(pixel):
return 0.21*(pixel[0])+0.72*(pixel[1])+ 0.07*(pixel[2])
#Parse through every pixel in the image and run it through the formula
gray = np.zeros(filename.shape[0:-1])
for row in range(len(filename)):
for col in range(len(filename[row])):
gray[row][col] = LuminosityMethod(filename[row][col])
#Pass grayscaled image back to main
return gray
def Blur(filename, passes):
imgarray = np.asarray(filename)
#Pixel radius of blur
radius = 2
#Sets window length of blur in respect to individual pixels
#In this case, length will be set to 5
wlen = (radius*2)+1
#Defines height and width of image array
height = imgarray.shape[0] #Rows (Y-Variable)
width = imgarray.shape[1] #Columns (X-Variable)
def ApplyBlur(imgarray):
#Creates two temporary arrays for image, based on dimensions
tempA = np.zeros((height, width, 3), np.uint8)
tempB = np.zeros((height, width, 3), np.uint8)
#Blur Horizontally, row by row
for row in range(height):
#RGB color values for a white pixel blur
R = 0
G = 0
B = 0
#Find blurred value for first pixel in the row
for rads in range(-radius, radius+1):
if (rads) >= 0 and (rads) <= width-1:
R += imgarray[row, rads][0]/wlen
G += imgarray[row, rads][1]/wlen
B += imgarray[row, rads][2]/wlen
tempA[row,0] = [R,G,B]
#Find blurred value for the rest of the pixels in every row
#The blur value depends on an unweighted mean and a sliding window
#The sliding window adds incoming pixels and subtracts outgoing pixels
#incoming pixel -> pixel to right
#outgoing pixel -> pixel to left
for col in range(1, width):
if (col-radius-1) >= 0:
R -= imgarray[row, col-radius-1][0]/wlen
G -= imgarray[row, col-radius-1][1]/wlen
B -= imgarray[row, col-radius-1][2]/wlen
if (col+radius <=width-1):
R += imgarray[row, col+radius][0]/wlen
G += imgarray[row, col+radius][1]/wlen
B += imgarray[row, col+radius][2]/wlen
#Puts final mean value into pixel in Temp A
tempA[row, col] = [R,G,B]
#Time to repeat the exact same process
#But Verically, column by column
for col in range(width):
R = 0
G = 0
B = 0
for rads in range(-radius, radius+1):
if (rads) >= 0 and (rads) <= height-1:
R += tempA[rads, col][0]/wlen
G += tempA[rads, col][1]/wlen
B += tempA[rads, col][2]/wlen
tempB[0, col] = [R,G,B]
for row in range(1,height):
if (row-radius-1) >= 0:
R -= tempA[row-radius-1,col][0]/wlen
G -= tempA[row-radius-1,col][1]/wlen
B -= tempA[row-radius-1,col][2]/wlen
if (row+radius)<=height-1:
R += tempA[row+radius, col][0]/wlen
G += tempA[row+radius, col][1]/wlen
B += tempA[row+radius, col][2]/wlen
tempB[row,col] = [R,G,B]
return tempB
#Time to step through the array multiple times
#For each pass across the entire array, the amount of blur will increase
#For this case, it will pass through 3 times
#Another temp array to hold values from each pass
tempC = imgarray
for k in range(passes):
#Limits # of passes to 6, for speed
if k < 6:
tempC = ApplyBlur(tempC)
#Get image from array
blurredimg = Image.fromarray(np.uint8(tempC))
#Pass blurred image back to main
return blurredimg
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--image', type=str, help="Filepath or Name of Image to transform")
parser.add_argument('-g', '--grayscale', action='store_true', help="Converts an image to GrayScale")
parser.add_argument('-b','--blur', type=int, help="Blurs an RGB Image on a scale of 0-5")
parser.add_argument('-o', '--output', type=str, help="Filepath or Name + Extension type of Output file")
if len(sys.argv) < 2:
parser.print_help(sys.stderr)
sys.exit(1)
args = parser.parse_args()
filename = misc.imread(args.image)
output = os.path.basename(args.image).split(".")[0]
#Checks for blur flag and performs blur
if args.blur:
print "Applying Blur to %r" % args.image
if len(filename.shape) < 3:
print "Error: Grayscale image or scalar provided. RGB Image Needed."
sys.exit(1)
else:
filename = Blur(filename, args.blur)
print "Done."
if not args.output:
output = output + "_blur"
#Checks for grayscale flag and performs grayscale
if args.grayscale:
print "Applying Grayscale to %r" % args.image
filename = GrayScale(np.asarray(filename))
print "Done."
if not args.output:
output = output + "_gray"
if args.output:
output = "%s" % args.output
misc.imsave(output, filename)
if not args.output:
misc.imsave(output + ".jpg", filename)
#Main Execution
if __name__ == "__main__":
main()
|
1c6339fadc505d07a9245714a8b94ef8fa043afb | MastersAcademy/Programming-Basics | /homeworks/olena.kucheruk_elena6kucheruk/Homework-1/homework1.py | 392 | 3.875 | 4 | print ("Please write about your favorite books \n")
name = input("What is your name?\n ")
age = int(input("What is your age?\n "))
book = input("What is your favorite book?\n ")
#results
result = ("Your name is %s, You are %i years old, your favorite book is %s. Thank you." % ( name, age, book ))
print (result)
#save
f= open ('results.txt', 'w')
f.write (result)
f.close ()
|
d64585d2d0eed2004db9d55445afcc7ffb64df5b | zuxinlin/leetcode | /leetcode/editor/cn/[98]验证二叉搜索树-validate-binary-search-tree.py | 2,046 | 3.703125 | 4 | #! /usr/bin/env python
# coding: utf-8
# 给定一个二叉树,判断其是否是一个有效的二叉搜索树。
#
# 假设一个二叉搜索树具有如下特征:
#
#
# 节点的左子树只包含小于当前节点的数。
# 节点的右子树只包含大于当前节点的数。
# 所有左子树和右子树自身必须也是二叉搜索树。
#
#
# 示例 1:
#
# 输入:
# 2
# / \
# 1 3
# 输出: true
#
#
# 示例 2:
#
# 输入:
# 5
# / \
# 1 4
# / \
# 3 6
# 输出: false
# 解释: 输入为: [5,1,4,null,null,3,6]。
# 根节点的值为 5 ,但是其右子节点值为 4 。
#
# Related Topics 树 深度优先搜索 递归
# 👍 1025 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# stack = []
# share = float('-inf')
#
# # 中序遍历非递归
# while stack or root:
# while root:
# stack.append(root)
# root = root.left
#
# root = stack.pop()
#
# if root.val <= share:
# return False
#
# share = root.val
# root = root.right
#
# return True
# 递归,搜索二叉树特性:左子树所有值小于根节点,右子树所有值大于根节点
def dfs(root, low=float('-inf'), high=float('inf')):
if not root:
return True
val = root.val
return low < val < high and dfs(root.left, low, val) and dfs(
root.right, val, high)
return dfs(root)
# leetcode submit region end(Prohibit modification and deletion)
|
dd0079a1c05d9e5e33d8bc26f227f2daf7bc87f3 | LudwinGarcia/Examples_Python | /ex36.py | 8,702 | 3.859375 | 4 | # -*- coding: utf-8 -*-
from sys import exit
def matematica():
print"\n"
print "*" * 76
print "\n++++++ HAS LLEGADO A LA ULTIMA PRUEBA!!!!++++++"
print "\nEn una jaula hay conejos y palomas, pueden contarse 35 cabezas y 94 patas."
print "Cuntos animales hay de cada clase? "
print "\t 1) 14 conejos y 21 palomas"
print "\t 2) 12 conejos y 23 palomas"
print "\t 3) 17 conejos y 18 palomas"
while True:
respuesta = raw_input("\t> ")
try:
respuesta = int(respuesta)
break
except ValueError:
pass
if respuesta == 2:
print "\n"
print "#" * 78
print "\n\t\t ERES EL NUMERO UNO!!!! "
print """
_______________+88
_______________+880
_______________++880
_______________++880
________________+880
________________+8880
________________++880
________________++888_____+++88
________________++8888__+++8880++88
________________+++8888+++8880++8888
_________________++888++8888+++888888++8888
_________________++88++8888++8888888++888888
_________________++++++888888888888888888_+88
__________________++++++88888888888888888_++8
__________________++++++++000888888888888+88
___________________+++++++000088888888888_88
____________________+++++++00088888888888
_____________________+++++++088888888888
_____________________+++++++088888888888
______________________+++++++8888888888
______________________+++++++0088888888
______________________++++++0088888888
______________________++++++00888888
"""
print"\n\t\t PASASTE LA PRUEBA CON EXITO"
print "#" * 78
print "\n"
elif respuesta == 1 or respuesta == 3:
print "\n"
print "#" * 74
print "no lograste encontrar la respuesta y moriste encerrado en la habitacion!!!"
print "#" * 74
print "\n"
else:
print ("\n************* ERROR *************")
print ("Solo puedes elegir del 1 al 3...")
print ("*********************************\n")
matematica()
def logica():
print"\n"
print "*" * 76
print "\nEn esta habitacion encuentras una adivinanza en la pared que dice: "
print "\nDe tanto pensar te volveras loco, la suegra de la mujer de tu hermano,"
print "Que parentesco le corresponde? si no contestas correctamente moriras aqui..."
print "\t 1) Tu esposa"
print "\t 2) Tu mama"
print "\t 3) Ninguno"
while True:
respuesta = raw_input("\t> ")
try:
respuesta = int(respuesta)
break
except ValueError:
pass
if respuesta == 2:
print "\n"
print "#" * 78
print "Excelente!, has probado tu inteligencia decifraste correctamente la pregunta!!"
print "#" * 78
print "\n"
matematica()
elif respuesta == 1 or respuesta == 3:
print "\n"
print "#" * 74
print "Escogiste el parentezco incorrecto y moriste encerrado en la habitacion!!!"
print "#" * 74
print "\n"
else:
print ("\n************* ERROR *************")
print ("Solo puedes elegir del 1 al 3...")
print ("*********************************\n")
logica()
def ciclope():
print"\n"
print "*" * 76
print "+++Has escogido la habitacion de la derecha+++"
print "\nEn esta habitacion encuentras un ciclope y enseguida te ataca,"
print "Tu corres para poder escapar de sus ataques y te das cuenta que es torpe,"
print "Te propones atacarlo pero ten encuenta que solo pudes hacerlo una vez,"
print "En que lugar enfocarias el ataque para ven"
print "\t 1) Realizas tu ataque en el cuello..."
print "\t 2) Realizas tu ataque en su ojo..."
print "\t 3) Realizas tu atque en el estomago..."
while True:
respuesta = raw_input("\t> ")
try:
respuesta = int(respuesta)
break
except ValueError:
pass
if respuesta == 1:
print "\n"
print "#" * 61
print "Moriste!, sus reflejos fueron superiorey y te aplasto!!"
print "#" * 61
print "\n"
elif respuesta == 3:
print "\n"
print "#" * 61
print "Moriste!, te mando a volar con la fuerza de su cuerpo!!"
print "#" * 61
print "\n"
elif respuesta == 2:
print "\n"
print "#" * 70
print "Excelente!, has probado tu inteligencia atacaste su punto debil!!"
print "#" * 70
print "\n"
logica()
else:
print ("\n************* ERROR *************")
print ("Solo puedes elegir del 1 al 3...")
print ("*********************************\n")
ciclope()
def acertijo():
print"\n"
print "*" * 76
print "\nTe encuentras en una nueva habitacion, tienes una mesa frente a ti,"
print "Veras que sobre ella hay 6 vasos que se encuentran ordenados de forma"
print "Horizontal 3 vasos tiene agua y los otros 3 estan vacios, los vasos se"
print "encuentran ordenados de la siguiente manera: "
print """
\t Pocicion 1 = vaso vacio
\t Pocicion 2 = vaso lleno
\t Pocicion 3 = vaso lleno
\t Pocicion 4 = vaso lleno
\t Pocicion 5 = vaso vacio
\t Pocicion 6 = vaso vacio
"""
print "\nLo que tienes que hacer buscar la menera de que queden intercaldos"
print "Es decir, mantener una linea y que junto a cada vaso lleno este uno vacio."
print "\nTodo esto debe realizarce moviendo un solo vaso, elege que vaso utlizarias"
print "Para poder cumplir con el obejtivo: 1, 2, 3, 4, 5, 6"
while True:
respuesta = raw_input("\t> ")
try:
respuesta = int(respuesta)
break
except ValueError:
pass
if respuesta == 3:
print "\n"
print "#" * 73
print "Excelente!, has probado tu inteligencia escogiste el vaso correctamente!!"
print "#" * 73
print "\n"
matematica()
elif respuesta == 1 or respuesta == 2 or respuesta == 4 or respuesta == 5 or respuesta == 6:
print "\n"
print "#" * 71
print "Escogiste el vaso incorrecto y te quedaste encerrado hasta la muerte!!!"
print "#" * 71
print "\n"
else:
print ("\n************* ERROR *************")
print ("Solo puedes elegir del 1 al 6...")
print ("*********************************\n")
acertijo()
def copas():
print"\n"
print "*" * 76
print "+++Has escogido la habitacion de la izquierda+++"
print "\nEn esta habitacion encuentras un mayordomo y te dice:"
print '\nFrente a mi como puedes observar tengo una mesa, en esta mesa'
print 'Tengo dos copas de vino una con veneno y otra sin veneno, Que eliges?'
print "\t 1) Eliges la copa de la izquierda y bebes de ella..."
print "\t 2) Eliges la copa de la derecha y bebes de ella..."
print "\t 3) No bebes de ninguna copa..."
while True:
respuesta = raw_input("\t> ")
try:
respuesta = int(respuesta)
break
except ValueError:
pass
if respuesta == 1:
print "\n"
print "#" * 61
print "Moriste!, La copa de la izquierda se encontraba envenenada!!"
print "#" * 61
print "\n"
elif respuesta == 2:
print "\n"
print "#" * 61
print "Moriste!, La copa de la derecha se encontraba envenenada!!"
print "#" * 61
print "\n"
elif respuesta == 3:
print "\n"
print "#" * 70
print "Excelente!, has probado tu inteligencia las dos copas tenian veneno!!"
print "#" * 70
print "\n"
acertijo()
else:
print ("\n************* ERROR *************")
print ("Solo puedes elegir del 1 al 3...")
print ("*********************************\n")
copas()
def puertas():
print"\n"
print "*" * 76
print "\nTomaste una sabia decicion, ahora te encuentras en una habitacion,"
print "frente a ti hay dos puertas cual escojeras"
print "\t 1) Izquierda"
print "\t 2) Derecha"
while True:
respuesta = raw_input("\t> ")
try:
respuesta = int(respuesta)
break
except ValueError:
pass
if respuesta == 1:
copas()
elif respuesta == 2:
ciclope()
else:
print ("\n********** ERROR **********")
print ("Solo puedes elegir 1 o 2...")
print ("***************************\n")
puertas()
def start():
print "*" * 76
print "\nTE ENCUENTRAS EN UNA PRUEBA, Y TE DEJAN EN LA CIMA DE UNA TORRE"
print "\nLo que tienes que realizar en la prueba es buscar la manera"
print "De llegar hasta abajo, la torre es cilindrica, esta hecha de"
print "Cuadros de priedra en todo su exterior y esta totalmente sellada."
print "\nTen encuenta que puedes encontrarte con trampas, por ello, "
print "tienes que analizar tus acciones para no morir en el intento"
print "\nYa que comprendes la situacion que opcion elegirias:"
print "\t1) Tratar de bajar la torre por el costado utilizando las piedras..."
print "\t2) Buscarias un entrada a la torre en el piso..."
while True:
respuesta = raw_input("\t> ")
try:
respuesta = int(respuesta)
break
except ValueError:
pass
if respuesta == 2:
puertas()
elif respuesta == 1:
print "\n"
print "#" * 61
print "Moriste!, No Tomaste en cuenta que las piedras se contraen..."
print "#" * 61
print "\n"
else:
print ("\n********** ERROR **********")
print ("Solo puedes elegir 1 o 2...")
print ("***************************\n")
start()
start()
|
4d736eabf7068a532e2aa40472818c1225f605bf | bamonson/brm677 | /02_problem4.py | 1,034 | 4.75 | 5 | #Code to determine if the Year is a leap year or not.
Year=2020
#Year is the variable. The value is 2020.
if Year%4==0:
#This determines if the Year value is divisible by 4. If it is, it goes to the next line's prompt. If it is not, it goes down to the "else" inline with it below that will print it isn't a leap year.
if Year%100==0:
#This determines if the year is divisible by 100 after it has been cleared by the above command that is it divisable by 4. If it is, it goes to the next line's prompt. If it is not, it goes down the the else inline with it below that will print it is a leap year.
if Year%400==0:
#If the value has cleared the above 2 prompts, it will go to this line to see if it is divisible by 400. It if is, it will print that it is a leap year. If it is not, it goes down to the "else" inline with it below that will print it isn't a leap year.
print('Year is a leap year')
else:
print('Year is not a leap year')
else:
print('Year is a leap year')
else:
print('Year is not a leap year') |
bd6775968ee8454fc9b0b0a86bb86acbe92e98b8 | DanyZy/Python-Labs | /Practice04/VigenereCipher.py | 3,413 | 3.5625 | 4 | import unittest
def add_spaces(text_w_space, text_wo_space, alphabet='abcdefghijklmnopqrstuvwxyz'):
for i, el in enumerate(text_w_space):
if not alphabet.__contains__(el):
text_wo_space.insert(i, el)
return text_wo_space
def del_surplus_symbols_in_text(text, alphabet='abcdefghijklmnopqrstuvwxyz'):
text = list(text)
clear_text = []
for el in text:
if alphabet.__contains__(el):
clear_text.append(el)
return clear_text
def del_surplus_symbols_in_password(password, len_pas):
for i in range(len_pas):
del password[-1]
return password
def encrypt(open_text, password, alphabet='abcdefghijklmnopqrstuvwxyz'):
alphabet = list(alphabet)
text = open_text
open_text = del_surplus_symbols_in_text(open_text, alphabet)
password = del_surplus_symbols_in_password(list(password) + open_text, len(password))
i = 0
for el in open_text:
open_text[i] = alphabet[(alphabet.index(el) + alphabet.index(password[i])) % len(alphabet)]
i += 1
open_text = add_spaces(text, open_text, alphabet)
return ''.join(open_text)
def decrypt(ciphered_text, password, alphabet='abcdefghijklmnopqrstuvwxyz'):
alphabet = list(alphabet)
text = ciphered_text
ciphered_text = del_surplus_symbols_in_text(ciphered_text, alphabet)
len_pass = len(password)
if len(ciphered_text) > len(password):
password = list(password)
j = 0
for el in ciphered_text:
if j < len(ciphered_text) - len_pass:
if alphabet.__contains__(el):
password.append(alphabet[(alphabet.index(el) - alphabet.index(password[j])) % len(alphabet)])
j += 1
i = 0
for el in ciphered_text:
if alphabet.__contains__(el):
ciphered_text[i] = alphabet[(alphabet.index(el) - alphabet.index(password[i])) % len(alphabet)]
i += 1
ciphered_text = add_spaces(text, ciphered_text, alphabet)
return ''.join(ciphered_text)
class TestVigener(unittest.TestCase):
def test_empty(self):
text = ''
pwd = ''
cipher = ''
self.assertEqual(decrypt(cipher, pwd), text)
self.assertEqual(encrypt(text, pwd), cipher)
def test_one(self):
text = 'codewars'
pwd = 'password'
cipher = 'rovwsoiv'
self.assertEqual(decrypt(cipher, pwd), text)
self.assertEqual(encrypt(text, pwd), cipher)
def test_two(self):
text = 'waffles'
pwd = 'password'
cipher = 'laxxhsj'
self.assertEqual(decrypt(cipher, pwd), text)
self.assertEqual(encrypt(text, pwd), cipher)
def test_third(self):
text = 'amazingly few discotheques provide jukeboxes'
pwd = 'password'
cipher = 'pmsrebxoy rev lvynmylatcwu dkvzyxi bjbswwaib'
self.assertEqual(decrypt(cipher, pwd), text)
self.assertEqual(encrypt(text, pwd), cipher)
def test_fourth(self):
text = 'amazingly few\n discotheques\n provide\n jukeboxes'
pwd = 'password'
cipher = 'pmsrebxoy rev\n lvynmylatcwu\n dkvzyxi\n bjbswwaib'
self.assertEqual(decrypt(cipher, pwd), text)
self.assertEqual(encrypt(text, pwd), cipher)
if __name__ == '__main__':
unittest.main()
|
2a4becc098cd2d6a072cc3e0b12f6eab0c597973 | dlgweeduh/movie_trailer_website | /media.py | 719 | 3.546875 | 4 | # allows use of Web Browser functionality
import webbrowser
class Movie():
"""" This class provides a way to store movie-related info. """
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
"""
Initializes Movie object with Title, Storyline, Poster Image, and YouTube Trailer data
"""
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
"""
Opens movie trailer in browser
"""
webbrowser.open(self.trailer_youtube_url)
|
f00dbf3879e0a237bed44271ad460489294938d3 | varnitsaini/python-dynamic-programming | /KnapsackProblem.py | 1,388 | 3.84375 | 4 | """
Implementing 0-1 knapsack problem
Two ways of representation has been depicted here
"""
"""
Naive recursive approach
Time complexity : 2^n
This approach has exponential time complexity as each subproblem
has to be evaluated twice. Although time complexity can be reduced
if we use memoisation for evaluate each recursive call
"""
def recursiveKnapsackWithNoMemoisation(w, wt, val, n):
if n == 0 or w == 0:
return 0
if wt[n-1] > w:
return recursiveKnapsackWithNoMemoisation(w, wt, val, n-1)
else:
return max(val[n-1] + recursiveKnapsackWithNoMemoisation(w - wt[n-1], wt, val, n-1), recursiveKnapsackWithNoMemoisation(w, wt, val, n-1))
"""
Iterative Approach
Time Complexity : O(nw)
"""
def iterativeKnapsack(w, wt, val, n):
tempArr = [[0 for x in range(w+1)] for x in range(n+1)]
for i in range(n+1):
for weight in range(w+1):
if i == 0 or weight == 0:
tempArr[i][weight] = 0
elif wt[i-1] <= weight:
tempArr[i][weight] = max(val[i-1] + tempArr[i-1][weight - wt[i-1]], tempArr[i-1][weight])
else:
tempArr[i][weight] = tempArr[i-1][weight]
return tempArr[n][w]
val = [1, 4, 5, 7]
wt = [1, 3, 4, 5]
maxWt = 7
n = len(wt)
print recursiveKnapsackWithNoMemoisation(maxWt, wt, val, n)
print "===="
print iterativeKnapsack(maxWt, wt, val, n)
|
fc16cc20845cfa49345594c077dc1886bbc2d04b | YusefQuinlan/PythonTutorial | /Basics/1.12.1_Basics_Sets.py | 1,831 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 7 15:40:46 2019
@author: Yusef Quinlan
"""
Set1 = {1,7,"Hello"}
#Set creation i.e. put items in '{}' those squiggly brackets
print(Set1)
Set1.add(8)
#Adding items to the set, notice if you use the command several times the number
# 8 will still only appear in the set once as Sets do not allow duplicate values
list1 = [9,8,23]
Set1.add(list1)
#Lists for some STRANGE Reason, cannot be added to sets
tup1 = (3,4,5)
Set1.add(tup1)
#Tuples however can be added to sets
Set1.pop()
#Gets rid of the first item in a set
Set1.remove(1)
#remove the item with value 1 in the set, if used when the item is not present in the set
# an error will occur, the remove function is as follow set.remove(argument)
# if the value that is used as an argument is not in the set an error will occur
Set1.discard(7)
#remove the item with value 1 in the set, if used when the item is not present in the set
# nothing will be removed, the discard function is as follow set.discard(argument)
# if the value that is used as an argument is not in the set an error will occur
Set2 = {9, 62, 33, "Happy_Days"}
print(Set2)
Set2.clear()
#Using the clear function to clear a set of all items
Set3 = set(list1)
#Makes a set out of a list by converting an existing list into a set
print(Set3)
Set4 = {4,4,4,99,99,9,9}
#Making a set with several values that are the same and assigning it to a variable
# is completely valid, but when you print the set or inspect it after assigning it,
# it will not contain duplicate values even though it appeared to have been assigned them.
print(Set4)
Set5 = Set4.copy()
#Copying of a set
Boolval1 = True #And therefore has a value of 1
Boolval2 = False #And therefore has a value of 0
Set6 = {False,True,1}
#Showing that True has a value of 1
print(Set6)
|
edf16a7a8783d8b1175f4d48b43625ba8ae1096a | lishuchen/Algorithms | /leecode/337_House_Robber_III.py | 689 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return self.robber(root)[1]
def robber(self, root):
if not root:
# [not robbed, robbed]
return [0, 0]
lf = self.robber(root.left)
rg = self.robber(root.right)
# need to compare these two, even root is robbed
return [lf[1] + rg[1], max(lf[1] + rg[1], root.val + lf[0] + rg[0])] |
5ec4ef9ba1c4077e26e41eb6765f2ebe26eec7ee | uzzal5954/Weather_Application | /weather_api.py | 1,201 | 3.5625 | 4 |
# Weather API
import requests
def format_response(weather_data):
try:
city_name = weather_data['name']
country_name= weather_data['sys']['country'] # ***
condition = weather_data['weather'][0]['description']
temperature = weather_data["main"]["temp"]
icon_name = weather_data["weather"][0]["icon"]
weather_report = "City: %s \nCountry: %s \nCondition: %s \nTemperature(°F): %s" % (city_name, country_name, condition, temperature) # **
except:
weather_report = "server error 500"
icon_name = ""
return (weather_report, icon_name)
def weather_information(city_name):
# get weather Information by calling openweather api
weather_key = "e1b9e0b7aee9851b9984a26f3675878e"
url = "http://api.openweathermap.org/data/2.5/weather"
params = {"APPID": weather_key, "q" : city_name, "units" : "imperial"}
response = requests.get(url, params)
weather_data = response.json()
# print(weather_data)
weather_report = format_response(weather_data)
return weather_report
print("Wellcome To My Weather Application. This Application Designe and Developed By Uzzal Chandra Boissha.") |
c4decdb01fe6a5e1fffa5f53056a5fdf9355a2ae | jmt-transloc/python_learning | /magic_methods/person_example.py | 302 | 3.78125 | 4 | class Person:
def __init__(self, title, forename, surname):
self.title = title
self.forename = forename
self.surname = surname
def __str__(self):
return ' '.join([self.title, self.forename, self.surname])
person = Person('Mr', 'John', 'Smith')
print(person)
|
83f48889c76b8ce2dbb6de080aafc066b9f6826e | datadiskpfv/basics1 | /functions1.py | 869 | 4.03125 | 4 | def python_food():
width = 80
text = "spam and eggs"
left_margin = (width - len(text)) // 2
print(" " * left_margin, text)
def center_text(width, text):
text = str(text) # make sure parameter is a str
left_margin = (width - len(text)) // 2
print(" " * left_margin, text)
# there are better ways to handle multiple arguments
def multi_arg(*args, end=', '): # end has a default of ', '
for i in args:
print(str(i), end=end)
# return data
def return_data(text):
return "Returned Data: " + text
# call function
python_food()
center_text(80, "spam and eggs")
center_text(80, 12)
# multi-argument
multi_arg("first", "second", 3, 4, "five")
print()
multi_arg("first", "second", 3, 4, "five", end=': ')
# returning data
print("\n" + return_data("Hello World!"))
r1 = return_data("Some returned text")
print(r1)
|
0333a1c91c7846bbb94dd626cbeee17fad839e86 | aldrinpscastro/PythonExercicios | /EstruturaDeRepeticao/ex021.py | 263 | 4 | 4 | numero = int(input('Digite um número: '))
eprimo = True
for i in range(numero - 1, 1, -1):
if numero % i == 0:
eprimo = False
break
if eprimo:
print('O digitado é primo.')
else:
print('O número digitado não é primo.')
|
ad874c9fcdfa6e474950def668961bb93677534f | IuriiD/PythonBasics | /practicepython.org/old/23.py | 1,402 | 3.640625 | 4 | # let's create a dictionary {'Name': count}
'''namescount = {}
with open('nameslist.txt','r') as open_file:
line = open_file.readline()
while line:
line = line.strip()
# check if this key is in dictionary
if line in namescount:
# if it is, corresp. value+=1
namescount[line]+=1
# if it doesn't exist, add such a key to dictionary and value = 1
else:
namescount[line]=1
line = open_file.readline()
print(namescount)'''
### another varian
'''primenumberslist = []
happynumberslist = []
with open('primenumbers.txt','r') as primes:
line = primes.readline()
while line:
line = line.strip()
primenumberslist.append(line)
line = primes.readline()
with open('happynumbers.txt','r') as happies:
line = happies.readline()
while line:
line = line.strip()
happynumberslist.append(line)
line = happies.readline()
overlapping = []
overlapping = [i for i in primenumberslist if i in happynumberslist]
print(overlapping)'''
###### again with functions
def filetolist(filename):
output = []
with open(filename,'r') as open_file:
line = open_file.readline()
while line:
line = line.strip()
output.append(line)
line = open_file.readline()
return output
primenumberslist = filetolist('primenumbers.txt')
happynumberslist = filetolist('happynumbers.txt')
overlapping = []
overlapping = [i for i in primenumberslist if i in happynumberslist]
print(overlapping) |
c0ea96b2eb61f8d9121562e9e7c6ecdff73aff42 | CheffOfGames/Diemen-Academy | /blankScreen.py | 1,689 | 3.546875 | 4 | from tkinter import *
top_bar_color = "Red"
logo_background = "White"
button_background = "Blue"
class Screen:
def __init__(self, root:Tk, frame:Frame, screens:dict, database):
self.root = root
self.frame = frame
self.screens = screens
self.frame_objects = []
self.current_user = ""
self.root.title("Blank Screen")
self.root.update()
self.height = self.root.winfo_height()
self.width = self.root.winfo_width()
self.canvas = Canvas(frame, width=self.width, height=self.height)
self.canvas.create_rectangle(0, 0, self.width, (self.height/10), fill=top_bar_color)
self.canvas.create_rectangle((self.width/50), (self.height/50), (self.width/5), (self.height/10 - self.height/50), fill=logo_background) # Logo
if type(self).__name__ != "LoginScreen" :
logout_button = Button(self.frame, width=int(((self.width/50)-(self.width/500))*1.5), height=int((self.height/100)-(self.height/160)), text="Log out", command=lambda: self.logout()).place(x=int(self.width - self.width/5), y=int(self.height/50))
self.canvas.pack()
def changeScreen(self, screen, user=0):
if not self.screens.get(screen) :
raise KeyError("This screen does not exist.")
self.canvas.delete("all")
self.canvas.destroy()
for i in self.frame_objects :
print(i)
i.destroy()
pass
self = self.screens[screen](self.root, self.frame, self.screens, user)
def logout(self) :
self.current_user = ""
self.changeScreen("Login")
|
df9a44571d3f08a39d51d87afce49a2f50ce4598 | yi-guo/coding-interview | /leetcode/python/015-threeSum.py | 1,382 | 3.59375 | 4 | #!/usr/bin/python
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets
# in the array which gives the sum of zero.
# Note:
# 1. Elements in a triplet (a, b, c) must be in non-descending order, i.e., a <= b <= c.
# 2. The solution set must not contain duplicate triplets.
# For example, given array S = {-1, 0, 1, 2, -1, -4}, a solution set is {(-1, 0, 1), (-1, -1, 2)}
# For every number that has not been visited, do twoSum, thus O(n) * O(n) = O(n^2).
def threeSum(num):
num.sort()
threesum = set()
for i, n in enumerate(num):
twosum = twoSum(num, i, 0 - n)
if twosum:
for res in twosum:
threesum.add(tuple(sorted((res[0], res[1], n))))
return [list(triplet) for triplet in threesum]
def twoSum(num, curr, target):
res = list()
i, j = 0, len(num) - 1
while i < j:
if i == curr:
i = i + 1
continue
elif j == curr:
j = j - 1
continue
twosum = num[i] + num[j]
if twosum < target:
i = i + 1
elif twosum > target:
j = j - 1
else:
res.append([num[i], num[j]])
i = i + 1
j = j - 1
return res
def main():
print threeSum([-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6])
main()
|
6314bf28225deb4912d84a760b1967daa07831dd | Gangamagadum98/Python-Programs | /PythonClass/reverseStr.py | 1,431 | 4.0625 | 4 | #reverse string
s1="hi hello"
def reverse(s):
s2 = "" # empty string since string is immutable
for i in s:
print(i) # we are iterating over characters in a string
s2=i+s2
return s2
# palindrome string
# if("NAN" == reverse("NAN")):
# print("Is a palindrome")
result = reverse(s1)
print(result)
# perfect square
def perfect(a):
sum1 = 0
for i in range(1,a):
if(a%i==0):
sum1=sum1+i
if(a==sum1):
print("It is perfect square")
else:
print("not perfect square")
perfect(6)
# Leap year
def leap(year):
if(year%4 == 0 and year%100!=0 or year%400==0):
print("It is leap year")
else:
print("It's not leap year")
leap(2023)
# bitwise
def clearRightBit(n):
return n & n-1
print(clearRightBit(6))
# reverse no
def reversenum(n):
while(n>0):
rem = n % 10
num = n//10
res1 = (rem *10)+num
return res1
res = reversenum(65)
print(res)
# factorial no
def fact(n):
fact = 1
for i in range(1,n+1):
fact = fact*i
return fact
result = fact(4)
print(result)
# smallest divisor of any no
def divisor(n):
for i in range(2,n):
if(n%i==0):
print(i)
break;
divisor(6)
# or
def smallestDivisor(n):
a=[]
for i in range(2,n):
if(n%i==0):
a.append(i)
return a
print(smallestDivisor(21).pop(0)) |
ef2e1caf2a26aeb4f3bb9f455e5f22447fd5eca9 | kburts/python-HearthStoneUtils | /HSCardnames.py | 509 | 3.828125 | 4 | import csv
import json
'''
Program to search through a .csv file and retrieve all of the contents of
one row, and save them to a json file.
can be modified to get other information about the cards.
File format: ["1","2","3"..."mystuff"].
'''
cardnames = []
with open('Hearthstone_cards.csv', 'r') as csvcards:
cards = csv.reader(csvcards)
for row in cards:
cardnames.append(row[1])
with open('cardnames.json', 'w') as cardnames:
cardnames.write(str(cardnames))
print "DONE!"
|
9ea6102dd25de4c840d338cd886a3cce2e3e34de | howobe/scan-scraping | /utils.py | 185 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 22:48:21 2020
@author: bj
"""
def xor(lst):
if not lst:
return
return lst[0] != xor(lst[1:])
|
694ac2f1609017d8443a5d0e78031820712101b3 | N1kken/PythonProjects | /PythonPodstawy/delta.py | 603 | 3.71875 | 4 | import time
import math
print("LICZ DELTE")
time.sleep(1)
print("Witaj, podaj wspolczynniki rownania kwadratowego: ax^2+bx+c=0!")
print("Podaj a:")
a=int(input())
print("Podaj b:")
b=int(input())
print("Podaj c:")
c=int(input())
delta=math.pow(b,2)-4*a*c
if delta == 0:
m1 = -b/(2*a)
print("Funkcja ma jedno miejsce zerowe w punkcie {}".format(m1))
elif delta>0:
m1 = (-b - math.sqrt(delta)) / (2 * a)
m2 = (-b + math.sqrt(delta)) / (2 * a)
print("Funkcja ma dwa miejsca zerowe w punktach {} , {}".format(m1,m2))
else: print("Funkcja nie ma miejsc zerowych") |
f0228b236d6bd3d15959552ca64bf9b0e603cd81 | makhsudov/csv-reader-python | /Csv.py | 603 | 3.984375 | 4 | import csv
array = []
path = ''
i = 0
with open(path, encoding='utf-8') as r_file:
# Separator character ","
csvReader = csv.DictReader(r_file, delimiter = ",")
# Reading data from a CSV file
for row in csvReader:
if i == 0:
# Displays the first line that contains the headings for the columns
print(f'Columns: {", ".join(row)}')
# Writing to an array of elements from a row called Row Name
elements = (f'{row["Row Name"]}')
array.append (elements)
i += 1
print(f'There are {i} lines in the file.') |
20be62521318fc7b29236872cecbc49fc87ee0a0 | hellion86/pythontutor-lessons | /8. Функции и рекурсия/Числа Фибоначчи.py | 682 | 4.0625 | 4 | '''
Условие
Напишите функцию fib(n), которая по данному целому неотрицательному n возвращает n-e число Фибоначчи. В этой задаче нельзя использовать циклы — используйте рекурсию.
'''
# Мое решение
n = int(input())
def fibo(n):
if n == 0:
return 0
if n == 1:
return 1
if n > 1:
return fibo(n-1) + fibo(n-2)
print(fibo(n))
# Правильное решение
def fib(n):
if n == 1 or n == 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
print(fib(int(input()))) |
ec0a6abb1351fa144f079218821e14ed60f72a50 | christiandleonr/Machine-Learning-A-Z-Course | /Part 2 - Regression/Section 4 - Simple Linear Regression/simple_linear_regression.py | 1,904 | 4.40625 | 4 | # Simple Linear Regression
# Importing the libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# Importing the data-set
data = pd.read_csv('Salary_Data.csv')
"""We take all columns except the last one, this is because we need to take the three independent variables"""
X = data.iloc[:, :-1].values
"""We take the dependent variable"""
y = data.iloc[:, 1].values
# Splitting the data-set into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=0)
# Fitting Simple Linear Regression to the Training set
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predicting the Test set Results
y_pred = regressor.predict(X_test) # Vector o predictions - method Predict return a array of predicted values
# Visualising the Training set results
"""With this we plot the information contains in our X_train and y_train, those are the values with that we train
the simple linear regression model"""
plt.scatter(X_train, y_train, color='red')
"""We use the X_train in y axis and the predictions to the X_train for the x axis
This is the line that describe the relation of the independent variable and the dependent variable"""
plt.plot(X_train, regressor.predict(X_train), color='blue')
# Giving information to our plot
plt.title('Salary vs Experience (Training set)')
plt.xlabel('Years of experience')
plt.ylabel('Salary')
plt.show()
# Visualising the Test set results
"""Now we plot the information contained in our test section to visualize the relation of the line with this
information"""
plt.scatter(X_test, y_test, color='green')
plt.plot(X_train, regressor.predict(X_train), color='blue')
plt.title('Salary vs Experience (Training set)')
plt.xlabel('Years of experience')
plt.ylabel('Salary')
plt.show()
|
c81edc2c96c521858f2335cc471ef642c5b17cf1 | kaztoyoshi/algorithm | /divisor/divisor.py | 795 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
N = 36 # 整数 N
print("1.")
out = "{"
for i in range(1, N+1):
if N % i == 0:
out += (str(i)) + ","
out += "}"
print(out)
print("2.")
arr = []
max = math.ceil(math.sqrt(N+1)) + 1
for i in range(1, max):
if N % i == 0:
arr.append(i)
if i**2 != N:
arr.append(N // i)
arr.sort()
out = "{"
for v in arr:
out += (str(v)) + ","
out += "}"
print(out)
print("2'.")
asc = [] # 昇順
desc = [] # 降順
max = math.ceil(math.sqrt(N+1)) + 1
for i in range(1, max):
if N % i == 0:
asc.append(i)
if i**2 != N:
desc.insert(0, N // i)
out = "{"
for v in asc:
out += (str(v)) + ","
for v in desc:
out += (str(v)) + ","
out += "}"
print(out)
|
b9f502ee35630d30fe2a9287c2ee45f3ee4d7330 | JackelyneTriana/AprendaPython | /Tablas.py | 508 | 3.78125 | 4 | #Tablas.py
#Autor: Mirna Jackelyne Triana Sanchez
#Fecha: 18/09/2019
for j in range(1,11):
#para cada elemento del rango 1 al 11 imprimir lo siguiente:
encabezado = "Tabla del {}"
print(encabezado.format(j))
for i in range(1,11):
#para cada elemento del rango 1 al 11 imprimir lo siguiente:
salida = "{} x {} = {}"
print(salida.format(i, j, i*j))
#ya que este ciclo for se encuentra dentro del ciclo anterior
#permite utilizar los valores de este
else:
print()
|
6383f374b80644b18be38bd9578800a344b90f5e | acharyasant7/Bioinformatics-Algorithms-Coding-Solutions | /Chapter -2/2A_MotifEnumeration.py | 1,473 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 09:02:17 2020
@author: sandesh
"""
def Neighbors(Pattern, d):
assert(d <= len(Pattern))
if d == 0:
return [Pattern]
SuffixNeigh = Neighbors(Pattern[1:], d-1)
Neighborhood = []
Neighborhood.append(Pattern)
for text in SuffixNeigh:
for c in chars:
if c!= Pattern[0]:
Neighborhood.append(c + text)
if (d < len(Pattern)):
SuffixNeigh = Neighbors(Pattern[1:], d)
for text in SuffixNeigh:
Neighborhood.append(Pattern[0] + text)
return Neighborhood
chars = 'ATGC'
def MotifEnumeration(Dna,k,d):
Patterns = []
motif = []
for string in Dna:
for i in range(0, len(string)-k+1):
Patterns.append(string[i:i+k])
for text in Patterns:
Neighbours = Neighbors(text, d)
for patt in Neighbours:
count = 0
patt2 = Neighbors(patt, d)
for m in Dna:
for elem in patt2:
if (m.find(elem) != -1):
count = count +1
break
if count == len(Dna):
motif.append(patt)
motif = list(set(motif))
return motif
Dna =[]
n = int(input("How many DNA Sequences?"))
for i in range(0,n):
Dna.append(input())
k = 5
d = 1
print(MotifEnumeration(Dna, k, d))
|
95d86665b106facfc38e4e57c7e4f04159d0392d | falabretti/uri-online-judge | /python3/beginner/1164.py | 324 | 3.625 | 4 | testes = int(input())
for caso in range(testes):
entrada = int(input())
soma = 0
for index in range(1, entrada):
if(entrada % index == 0):
soma += index
if(soma == entrada):
print("{} eh perfeito".format(entrada))
else:
print("{} nao eh perfeito".format(entrada))
|
f42a0060b4a2635a0fa89f94493aa3cbc30b1f8d | ErickMwazonga/sifu | /oop/playlist.py | 1,397 | 3.703125 | 4 | class Song:
def __init__(self, title, artist, album, track_number):
self.title = title
self.artist = artist
self.album = album
self.track_number = track_number
artist.add_song(self)
class Album:
def __init__(self, title, artist, year):
self.title = title
self.artist = artist
self.year = year
self.tracks = []
def __post_init__(self):
self.artist.add_album(self)
def add_track(self, title, artist=None):
if artist is None:
artist = self.artist
track_number = len(self.tracks)
song = Song(title, artist, self, track_number)
self.tracks.append(song)
class Artist:
def __init__(self, name):
self.name = name
self.albums = []
self.songs = []
def add_album(self, album):
self.albums.append(album)
def add_song(self, song):
self.songs.append(song)
class Playlist:
def __init__(self, name):
self.name = name
self.songs = []
def add_song(self, song):
self.songs.append(song)
band = Artist("Bob's Awesome Band")
album = Album("Bob's First Single", band, 2013)
album.add_track("A Ballad about Cheese")
album.add_track("A Ballad about Cheese (dance remix)")
album.add_track("A Third Song to Use Up the Rest of the Space")
playlist = Playlist("My Favourite Songs")
|
229b171160322badbe876e007dfad43cc25e252c | Ressull250/code_practice | /part4/110.py | 1,133 | 3.75 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root: return True
if abs(self.maxDepth(root.left) - self.maxDepth(root.right)) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def find(root, path):
if not root: return path
return max(find(root.left, path+1), find(root.right, path+1))
return find(root, 0)
class Solution1(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def height(root1):
if not root1: return 0
lh = height(root1.left)
rh = height(root1.right)
if lh == -1 or rh == -1 or abs(lh-rh) > 1: return -1
return max(lh,rh)+1
return height(root) != -1 |
dcae6505d8b0af3069e022944bc804756de10b90 | Puneetdots/Python | /snake_water_gun.py | 548 | 3.765625 | 4 | import random
obj = ["Snake","Water","Gun"]
input1 = print(input("Please choose the charater S for Snake,W for Water,G for Gun\n"))
ch = random.choice(obj)
#print(ch)
if ch=="Snake" and input1 =="W":
print("Snake Win")
elif ch=="Snake" and input1 =="G":
print("Gun Win")
elif ch=="Water" and input1 =="S":
print("Snake Win")
elif ch=="Water" and input1 =="G":
print("Gun Win")
elif ch=="Gun" and input1 =="S":
print("Gun Win")
elif ch=="Gun" and input1 =="W":
print("Water Win")
else:
print("Same Pattern!Try again")
|
631a93b8edc4edd2b65b8d5b5e02f5436c745127 | lilaboc/leetcode | /5.py | 438 | 3.5625 | 4 | # https://leetcode.com/problems/longest-palindromic-substring/
class Solution:
def longestPalindrome(self, s: str) -> str:
window = len(s)
while True:
for i in range(len(s) - window + 1):
st = s[i : i + window]
if st[:] == st[::-1]:
return st
window -= 1
print(Solution().longestPalindrome("babad"))
print(Solution().longestPalindrome("bb")) |
9aee8cee3ad47a9da7e76f83551a2d5430088ee4 | Uncastellum/Hashcode | /2022/main2.py | 818 | 3.515625 | 4 | def main():
print(f"Reading from {input}")
print(f"Writing to {output_file}")
# Sort projects
radixSort(projects, lambda x: x.best_before)
print([x.best_before for x in projects])
indiceWhile = 0
activeProjects = []
output = []
while(len(projects) != 0):
for project in activeProjects:
if project.days <= 0:
for persona in project.personas:
contributors.append(persona)
output.append(project)
else:
project.days -= 1
(activeProjects,projects) = selector.elegirProyecto(projects, contributors)
for i in range(len(projects), 0):
if projects[i].best_before < indiceWhile - projects[i].days:
projects.pop(i)
indiceWhile += 1
|
e36aa5959ad66a03ad6d910e09ae49fa00c196c2 | Xillow/CL-Stanley-Parable | /insane.py | 7,069 | 3.90625 | 4 | import door
import time
def insane():
print("(You enter a room with a car parked. A door shuts behind you.)")
print("But Stanley just couldn't do it.")
time.sleep(1)
print("He considered the possibility of facing his boss, admitting he had left his post during work hours, he might be fired for that. And in such a competitive economy, why had he taken that risk?")
time.sleep(8)
print("(You enter a room with a series of clocks and filing droors.)")
print("All because he believed everyone had vanished? His boss would think he was crazy.")
time.sleep(2)
print("And then something occurred to Stanley: Maybe, he thought to himself, maybe I am crazy. All of my coworkers blinking mysteriously out of existence in a single moment for no reason at all?")
time.sleep(8)
print("(You enter a dull room with a vending machine.)")
print("None of it made any logical sense. And as Stanley pondered this he began to make other strange observations.")
time.sleep(3)
print("(You enter a room with a car parked.)")
print("For example, why couldn't he see his feet when he looked down? Why did doors close automatically behind him wherever he went?")
time.sleep(5)
print("(You enter a room with a series of clocks and filing droors.)")
print("And for that matter, these rooms were starting to look pretty familiar, were they simply repeating?")
time.sleep(4)
print("No, Stanley said to himself, this is all too strange, this can't be real, and at last he came to the conclusion that had been on the tip of his tongue, he just hadn't found the words for it.")
time.sleep(7)
print("(You no longer seem to care about the rooms.)")
print("I'm dreaming! he yelled, This is all a dream!")
time.sleep(1)
print("What a relief Stanley felt to have finally found an answer, an explanation. His coworkers weren't actually gone, he wasn't going to lose his job, he wasn't crazy after all!")
time.sleep(6)
print("And he thought to himself, I suppose I'll wake up soon, I'll have to go back to my boring real life job pushing buttons, I may as well enjoy this while i'm still lucid.")
time.sleep(6)
print("So he imagined himself flying, and began to gently float above the ground.")
time.sleep(4)
print("Then he imagined himself soaring through space on a magical star field, and it too appeared!")
time.sleep(4)
print("It was so much fun, and Stanley marveled that he had still not woken up. How was he remaining so lucid?")
time.sleep(5)
print("And then perhaps the strangest question of them all entered Stanley's head, one he was amazed he hadn't asked himself sooner:")
time.sleep(5)
print("Why is there a voice in my head, dictating everything that i'm doing and thinking?")
time.sleep(3)
print("Now the voice was describing itself being considered by Stanley, who found it particularly strange. I'm dreaming about a voice describing me thinking about how it's describing my thoughts, he thought!")
time.sleep(7)
print("And while he thought it all very odd and wondered if this voice spoke to all people in their dreams, the truth was that of course this was not a dream. How could it be?")
time.sleep(6)
print("Was Stanley simply deceiving himself? Believing that if he's asleep he doesn't have to take responsibility for himself?")
time.sleep(5)
print("Stanley is as awake right now as he's ever been in his life.")
time.sleep(3)
print("Now hearing the voice speak these words was quite a shock to Stanley. After all, he knew for certain beyond a doubt that this was, in fact, a dream!")
time.sleep(5)
print("Did the voice not see him float and make the magical stars just a moment ago? How else would the voice explain all that?")
time.sleep(5)
print("This voice was a part of himself too, surely, surely if he could just....")
time.sleep(3)
print("He would prove it. He would prove that he was in control, that this was a dream.")
time.sleep(3)
print("So he closed his eyes gently, and he invited himself to wake up.")
time.sleep(2)
print("(You close your eyes.)")
time.sleep(2)
print("He felt the cool weight of the blanket on his skin, the press of the mattress on his back,")
time.sleep(3)
print("the fresh air of a world outside this one. Let me wake up, he thought to himself.")
time.sleep(3)
print("I'm through with this dream, I wish it to be over. Let me go back to my job, let me continue pushing the buttons, please, it's all I want.")
time.sleep(6)
print("I want my apartment, and my wife, and my job. All I want is my life exactly the way it's always been.")
time.sleep(4)
print("My life is normal, I am normal. Everything will be fine.")
time.sleep(3)
print("I am okay.")
time.sleep(5)
print("(You open your eyes, and see a parked car.)")
print("Stanley began screaming.")
time.sleep(1)
print("Please someone wake me up!")
time.sleep(0.5)
print("My name is Stanley!")
time.sleep(0.5)
print("I have a boss!")
time.sleep(0.5)
print("I have an office! I am real!")
time.sleep(0.5)
print("(The world grows red around you.)")
print("Please just someone tell me i'm real!")
time.sleep(1)
print("I must be real! I must be!")
time.sleep(0.5)
print("Can anyone hear my voice?!")
time.sleep(0.5)
print("Who am I?!")
time.sleep(0.5)
print("WHO AM I?!")
time.sleep(1)
print("And everything went black.")
print()
time.sleep(5)
print("This is the story of a woman named Mariella.")
time.sleep(3)
print("Mariella woke up on a day like any other. She arose, got dressed, gathered her belongings, and walked to her place of work.")
time.sleep(5)
print("But on this particular day, her walk was interrupted by the body of a man who had stumbled through town talking and screaming to himself and then collapsed dead on the sidewalk.")
time.sleep(7)
print("And although she would soon turn to go call for an ambulance, for just a few, brief moments, she considered the strange man.")
time.sleep(5)
print("He was obviously crazy; this much she knew. Everyone knows what crazy people look like.")
time.sleep(3)
print("And in that moment, she thought to herself how lucky she was to be normal.")
time.sleep(3)
print("I am sane. I am in control of my mind. I know what is real, and what isn't.")
time.sleep(3)
print("It was comforting to think this, and in a certain way, seeing this man made her feel better. But then she remembered the meeting she had scheduled for that day,")
time.sleep(5)
print("the very important people whose impressions of her would affect her career, and, by extension, the rest of her life.")
time.sleep(4)
print("She had no time for this, so it was only a moment that she stood there, staring down at the body.")
time.sleep(3)
print("And then she turned and ran.")
time.sleep(5)
door.door()
|
06936194f459028b65d4dee13db6c3787a9ff989 | DaVinci42/LeetCode | /110.BalancedBinaryTree.py | 1,085 | 3.75 | 4 | from typing import Dict
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
cache = {}
self.getHeight(root, cache)
l = [root]
while l:
nextL = []
for n in l:
leftH, rightH = cache.get(n.left, 0), cache.get(n.right, 0)
if abs(leftH - rightH) > 1:
return False
if n.left:
nextL.append(n.left)
if n.right:
nextL.append(n.right)
l = nextL
return True
def getHeight(self, root: TreeNode, cache: Dict[TreeNode, int]) -> int:
if not root:
return 0
height = 1 + max(
self.getHeight(root.left, cache), self.getHeight(root.right, cache)
)
cache[root] = height
return height
|
df70575c0a6beeed16c299b9301ce2bd17550ba1 | H-Shen/Collection_of_my_coding_practice | /Hackerrank/Mathematics/Eulers_Criterion.py3 | 305 | 3.65625 | 4 | import fractions
for i in range(int(input())):
A, M = list(map(int,input().split()))
if A ** 0.5 % 1 == 0:
print('YES')
elif (M > 2 and fractions.gcd(A, M) == 1 and pow(A, (M - 1) // 2, M)== 1):
print('YES')
elif M == 2:
print('YES')
else:
print('NO')
|
b875f497344c9f951b5c862aa92b01f0dfaffef1 | KimbaWLion/RedditBotPractice | /RedditBotWait.py | 425 | 3.75 | 4 | #!/usr/bin/python
import time
import sys
def wait_2_seconds():
wait_seconds(2)
def wait_2_seconds_no_display():
wait_seconds(2,False)
def wait_seconds(waittime, display=True):
if display:
print 'Wait {0} seconds because you cannot make a call more than once every 2 seconds'.format(waittime)
time.sleep(waittime)
if display:
print 'Now actually start the program'
sys.stdout.flush() |
88708a7801b8c4b771ea2711463d43e8632da154 | Reynouts/AoC19 | /AoC19/day20.py | 5,548 | 3.78125 | 4 | import copy
import os
import aocutils as util
from collections import defaultdict
WIDTH = 0
HEIGHT = 0
def draw(tiles):
result = ""
for j in range(HEIGHT):
for i in range(WIDTH):
if (i, j) in tiles:
result += tiles[i, j]
else:
result += " "
result += "\n"
print(result)
def in_outer(pos):
if pos[0] <= 3 or pos[0] >= WIDTH-3:
return True
if pos[1] <= 3 or pos[1] >= HEIGHT-3:
return True
return False
def get_teleport_exit(pos, teleports):
if pos in teleports[0]:
return teleports[1][teleports[0].index(pos)]
elif pos in teleports[1]:
return teleports[0][teleports[1].index(pos)]
else:
raise ValueError
def surrounding(tiles, pos, teleports=None):
x, y = pos
directions = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
neighbours = {}
for d in directions:
if d in tiles:
neighbours[d] = tiles[d]
if pos in tiles and tiles[pos] == "*" and teleports:
get_teleport_exit(pos, teleports)
return neighbours
def get_teleport_location(tiles, positions):
for p in positions:
s = surrounding(tiles, p)
for t in s:
if s[t] == ".":
return t
def make_pairs(tiles, letters):
couples = []
for l1 in letters:
for l2 in letters:
if l1 is not l2:
if abs(l1[1][0] - l2[1][0]) + abs(l1[1][1] - l2[1][1]) == 1:
# get teleport position
telloc = get_teleport_location(tiles, [l1[1], l2[1]])
# woops..
if l1[1][0] + l1[1][1] < l2[1][0] + l2[1][1]:
first = l1[0]
second = l2[0]
else:
first = l2[0]
second = l1[0]
couples.append(((first, second), telloc))
break
start = (0, 0)
end = (0, 0)
couples = list(dict.fromkeys(couples))
temptel = defaultdict(set)
for c in couples:
if c[0] == ("A", "A"):
start = c[1]
elif c[0] == ("Z", "Z"):
end = c[1]
else:
temptel[c[0]].add(c[1])
teleports = [[], [], []]
for t in temptel:
tup = tuple(temptel[t])
print (tup)
teleports[0].append(tup[0])
teleports[1].append(tup[1])
teleports[2].append(t)
return start, end, teleports
def part1(tiles, start, end, teleports,depth=0):
visited = set()
visited.add(start)
while depth == 0 or len(neighbours) > 0:
neighbours = set()
for v in visited:
x, y = v
directions = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
for d in directions:
if d in tiles:
if d not in visited:
neighbours.add(d)
if tiles[v] == "*":
telexit = get_teleport_exit(v, teleports)
if telexit not in visited:
neighbours.add(telexit)
for n in neighbours:
if n == end:
return depth + 1
visited.add(n)
depth += 1
return -1
def part2(tiles, start, end, teleports, z=0, depth=0):
# just BFS copy of 1 with level/z, slow as hell again :D
if start == end and z==0:
return depth
visited = set()
visited.add((start, z))
while depth == 0 or len(neighbours) > 0:
neighbours = set()
for v in visited:
x, y = v[0]
directions = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
for d in directions:
if d in tiles:
test = (d, v[1])
if test not in visited:
neighbours.add(test)
if tiles[v[0]] == "*":
valid = False
outer = in_outer(v[0])
if not outer or v[1] is not 0:
valid = True
if valid:
if outer:
level = v[1]-1
else:
level = v[1]+1
telexit = get_teleport_exit(v[0], teleports)
if (telexit, level) not in visited:
neighbours.add((telexit, level))
print("Levelling {}, depth {}, size visited {}".format(level, depth, len(visited)))
for n in neighbours:
if n == (end, 0):
return depth + 1
# speedup? level 30 is deep enough
# if n[1] < 30:
# visited.add(n)
visited.add(n)
depth += 1
return -1
def main():
global WIDTH
global HEIGHT
with open("day20.txt", "r") as f:
data = f.read().split("\n")
tiles = {}
HEIGHT = len(data)
WIDTH = len(data[HEIGHT // 2]) + 2
letters = []
for j, row in enumerate(data):
for i, item in enumerate(row):
if item not in " #" and not item.isalpha():
tiles[(i, j)] = item
if item.isalpha():
letters.append((item, (i, j)))
start, end, teleports = make_pairs(tiles, letters)
tiles[start] = "["
tiles[end] = "]"
for l in teleports:
for index in l:
tiles[index] = "*"
print(part1(tiles, start, end, teleports))
print(part2(tiles, start, end, teleports))
if __name__ == "__main__":
main()
|
bbd0344172d7543573c568b9c832bbc6f8b4e8c7 | kimsungho97/Algorithms | /baekjoon/두 동전.py | 3,479 | 3.6875 | 4 | import copy
row, col= list(map(int,input().split()))
origin_board=[]
for i in range(row):
line=list(input())
origin_board.append(line)
token={'coin': 'o', 'empty':'.', 'wall':'#'}
moving=['up','down','left','right']
count=11
def coin_move(before,direction):
global row, col, token
drop_count=0
board=before[:]
if direction=='up':
for r in range(row):
for c in range(col):
if board[r][c]==token['coin']:
if r==0:
board[r][c]=token['empty']
drop_count+=1
elif board[r-1][c]==token['empty']:
board[r][c]=token['empty']
board[r-1][c]=token['coin']
elif board[r-1][c]==token['coin']:
return (-1,board)
if direction=='down':
for r in range(row-1,-1,-1):
for c in range(col):
if board[r][c]==token['coin']:
if r==row-1:
board[r][c]=token['empty']
drop_count+=1
elif board[r+1][c]==token['empty']:
board[r][c]=token['empty']
board[r+1][c]=token['coin']
elif board[r+1][c]==token['coin']:
return (-1,board)
if direction=='left':
for r in range(row):
for c in range(col):
if board[r][c]==token['coin']:
if c==0:
board[r][c]=token['empty']
drop_count+=1
elif board[r][c-1]==token['empty']:
board[r][c]=token['empty']
board[r][c-1]=token['coin']
elif board[r][c-1]==token['coin']:
return (-1,board)
if direction=='right':
for r in range(row):
for c in range(col-1,-1,-1):
if board[r][c]==token['coin']:
if c==col-1:
board[r][c]=token['empty']
drop_count+=1
elif board[r][c+1]==token['empty']:
board[r][c]=token['empty']
board[r][c+1]=token['coin']
elif board[r][c+1]==token['coin']:
return (-1,board)
return (drop_count,board)
def is_eqaul(before,after):
global row, col
coin_count=0
for r in range(row):
for c in range(col):
temp=before[r][c]
if(temp==token['wall']):
continue
if temp!=after[r][c]:
return False
if temp==token['coin']:
coin_count+=1
if coin_count==2:
return True
return True
def move(original,before, cur_count):
global row, col, token, count, moving
for m in moving:
drop_count, after=coin_move(copy.deepcopy(before),m)
#print(cur_count)
if cur_count>=11:
break
if drop_count==1 and cur_count<count:
count=cur_count
break
if drop_count==-1 or drop_count==2:
continue
if is_eqaul(before,after):
continue
move(original, after, cur_count+1)
move(origin_board,copy.deepcopy(origin_board),1)
if count>=11:
print(-1)
else:
print(count)
|
bb62834bfa72d4f6daa038655c47b04f97b4da52 | vronikp/PrestamosIngSw | /prestamo.py | 1,010 | 3.625 | 4 | class Prestamo():
def valor_total(self,prestamo,tiempo):
if( prestamo <5000 && tiempo <=3):
comision=(prestamo *2)/100
capital_total=float(prestamo+comision)
interes=float(((capital_total*1)/100)*tiempo)
return float(capital_total+interes)
if(prestamo <9999.99 && tiempo <=6):
comision=(prestamo*3)/100
capital_total=float(prestamo+comision)
interes=float(((capital_total*1.25)/100)*tiempo)
return float(capital_total+interes)
if(prestamo <20000 && tiempo <=12):
comision=(prestamo*4)/100
capital_total=float(prestamo+comision)
interes=float(((capital_total*1.5)/100)*tiempo)
return float(capital_total+interes)
if(prestamo <5000 && tiempo <=3):
print("El banco no puede otorgar dicho prestamo ya que excede al monto definido")
return None
|
4d08b61f6b54ad55a723599450e7f0beab8cf466 | evalDev/ud-fullstack | /programing-fondations/02-use-functions/secret-message.py | 563 | 4.03125 | 4 | import os
def rename_files():
files_dir = "/home/mute/repos/udacity/programing-fondations//02-use-functions/prank"
saved_path = os.getcwd()
os.chdir(files_dir)
#1. Get the name of each file in folder
file_list = os.listdir(files_dir)
for file_name in file_list:
#2. remove numbers from each file name
file_name_no_numbers = file_name.translate(None, "0123456789")
print "Changing:", file_name, "to:", file_name_no_numbers
os.rename(file_name, file_name_no_numbers)
os.chdir(saved_path)
rename_files()
|
3c7b172b44d143a43e7da5915fb0880adad5db59 | mateuskienzle/training-python | /ex-078-maior-e-menor-valores-na-lista.py | 544 | 3.78125 | 4 | valores = []
for c in range (0, 5):
valores.append(int(input(f'Digite um valor para a Posição {c}: ')))
valor_max = max(valores)
valor_min = min(valores)
print('=-' *30)
print(f'Você digitou os valores {valores}')
print(f'O maior valor digitado foi {valor_max} nas posições ', end='')
for i, v in enumerate(valores):
if v == valor_max:
print(f'{i}...', end='')
print(f'\nO menor valor digitado foi {valor_min} nas posições ', end='')
for i, v in enumerate(valores):
if v == valor_min:
print(f'{i}...', end='') |
80595a0b47554fe2c8cdab1ccd9d280033b43c80 | Evelyn9276/Practice | /main.py | 455 | 3.890625 | 4 | import turtle as trtl
# set turtle pencolor to teal
trtl.pencolor("teal")
trtl.speed(10)
# draw six hexagons
for i in range(6):
trtl.circle(50, 360, 6)
trtl.penup()
trtl.forward(10)
trtl.pendown()
# move turtle to (0, -100)
trtl.penup()
trtl.goto(0, -100)
trtl.pendown()
# make turtle pencolor green
trtl.pencolor("green")
# draw five triangles
for i in range (5):
trtl.circle(50, 360, 3)
trtl.penup()
trtl.forward(20)
trtl.pendown() |
ba46c6c939aeb6e5d5e5c660bbd0735a59d9c634 | wahyuagungs/NotFreeCell | /core/foundation.py | 2,195 | 3.953125 | 4 | from core.stack import Stack
from core.color import Color
class Foundation(Stack):
"""
This class is sometimes called as winner deck, because it will hold stack of cards that will be moved from either
Tableau or Cells. All cards must be placed according to its suit and number sequentially.
The number of foundation object will depend on the number of suits that will be created in the beginning, with the
exception of if the number of suits is less than 4, the number of foundation will only still be 4.
"""
def __init__(self, location):
self._location = location
self._type = None
super().__init__()
# only give the top card if exists, assuming that all cards will be in order
def __str__(self):
return str(super().peek()) if not self.is_empty() else Color.GREEN.value + '-:-' + Color.GREEN.value
# this method override base class to add validation
def add_card(self, card):
if super().is_empty():
if card.get_number() == 1: # first card must be an ace of any suit
card.set_location(self._location) # set every card in the same object location of foundation
super().add_card(card)
self._type = card.get_cardsuit() # it will set the object
else:
raise Exception("The first card must be an ACE of any suit")
else:
# comparing the type and the number which will be equivalent of new card number = top list - 1
if card.get_cardsuit() is self._type \
and card.get_number() == super().peek().get_number() + 1:
card.set_location(self._location)
super().add_card(card)
else:
raise Exception("Cannot add card for different type or unmatched number")
# returns location of foundation
def get_location(self):
return self._location
# set location of foundation
def set_location(self, location):
self._location = location
# this method is to prevent base class being invoked
def add_cards(self, cards):
raise NotImplementedError("Cannot take card from foundation")
|
9a6ab5479ba578aea057ea4b357234f410522e14 | kalmuzaki/Card-Classes | /Card.py | 1,090 | 3.78125 | 4 | from enum import Enum
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def __str__(self):
return "{0} of {1}".format(self.value.name,self.suit.name)
def __gt__(self, other):
if self.suit.value >= other.suit.value:
if self.value.value > other.value.value:
return True
return False
def __lt__(self, other):
if self.suit.value <= other.suit.value:
if self.value.value < other.value.value:
return True
return False
def __eq__(self, other):
if self.suit.value == other.suit.value:
if self.value.value == other.value.value:
return True
return False
class Suit(Enum):
CLUBS = 0
DIAMONDS = 1
HEARTS = 2
SPADES = 3
class Value(Enum):
ACE = 0
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
SIX = 6
SEVEN = 7
EIGHT = 8
NINE = 9
TEN = 10
JACK = 11
QUEEN = 12
KING = 13
|
e099799375308a2b43a1d482b75759fd7a9f79fa | anoru/Intro-to-machine-learning | /naive_bayes/nb_author_id.py | 2,096 | 3.828125 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 1 (Naive Bayes) mini-project.
Use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
#########################################################
def NBAccuracy(features_train, labels_train, features_test, labels_test):
""" compute the accuracy of your Naive Bayes classifier """
### import the sklearn module for GaussianNB
from sklearn.naive_bayes import GaussianNB
### create classifier
clf = GaussianNB()
### Calculate the Time spent to train our algorithm
t0 = time()
### fit the classifier on the training features and labels
clf.fit(features_train, labels_train)
print "Training time:", round(time()-t0, 3), "s"
### Calculate the Time spent in the prediction
t0 = time()
### use the trained classifier to predict labels for the test features
pred = clf.predict(features_test)
print "Prediction time:", round(time()-t0, 3), "s"
### calculate and return the accuracy on the test data
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(pred, labels_test)
### Another way
### accuracy = clf.score(features_test, labels_test)
return accuracy
print NBAccuracy(features_train, labels_train, features_test, labels_test)
#########################################################
### Your exact results for time may vary,
### but we found that predicting with this particular
### setup takes about 30x less time than training.
#no. of Chris training emails: 7936
#no. of Sara training emails: 7884
#Training time: 1.299 s
#Prediction time: 0.199 s
#0.973265073948
|
48cef7ec37fa45ed3a1c5d7bafe63d43f7baa0f6 | Roykssop/pytraining | /11-Ejercicios/ejercicio1.py | 832 | 4.03125 | 4 | # Fn recorre lista
def recorreListaSimple( nombre, lista ):
print(f"============= {nombre} ===========")
for item in lista:
print(item)
print("===============================\n")
def devuelveElemento( indice, lista ):
if( indice < len(lista) ):
print(lista.index(indice))
else:
print("No existe el elemento")
# Crear lista con 8 números
numlist = list(range(8,0,-1))
# Recorrerla y mostrarla
recorreListaSimple("Lista desordenada",numlist)
# Ordenarla y mostrarla
numlist.sort()
recorreListaSimple("Lista ordenada",numlist)
# Mostrar su longitud
print(f"Longitud de la lista {len(numlist)}")
# Buscar un elemento en base a lo que nos pida el usuario por teclado
try:
value = int(input("Ingrese el indice de la lista que quiere ver... :"))
devuelveElemento(value, numlist)
except:
print("Error") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.