blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
542da4b047a76fd24855bdacfd14749bb9a2b56a | pktippa/hr-python | /strings/whats_your_name.py | 261 | 3.90625 | 4 | def print_full_name(a, b):
print("Hello " + a + " " + b + "! You just delved into python.") # Using + operator for concatinating strings.
if __name__ == '__main__':
first_name = input()
last_name = input()
print_full_name(first_name, last_name) |
0ff7d34d4052847acf9a11bf0e2017578ea13e57 | pktippa/hr-python | /sets/check_subset.py | 267 | 3.71875 | 4 | for i in range(int(input())):
a = int(input()); A = set(input().split())
b = int(input()); B = set(input().split())
# Or we can also use A.issubset(B) function directly
if A.intersection(B) == A:
print("True")
else:
print("False") |
67d7f68e4f22f559371da94cf0ea0be9e8051132 | pktippa/hr-python | /basic-data-types/lists.py | 1,208 | 4.03125 | 4 | list_to_handle=[]
input_list=[]
def do_insert(given_list):
global list_to_handle
list_to_handle.insert(int(given_list[1]), int(given_list[2]))
def print_list(given_list):
global list_to_handle
print(list_to_handle)
def remove_element(given_list):
global list_to_handle
list_to_handle.remove(int(given_list[1]))
def append_element(given_list):
global list_to_handle
list_to_handle.append(int(given_list[1]))
def sort_the_list(given_list):
global list_to_handle
list_to_handle.sort()
def pop_element(given_list):
global list_to_handle
list_to_handle.pop()
def reverse_the_list(given_list):
global list_to_handle
list_to_handle.reverse()
input_dictionary = {
'insert': do_insert,
'print': print_list,
'remove': remove_element,
'append': append_element,
'sort': sort_the_list,
'pop': pop_element,
'reverse': reverse_the_list
}
if __name__ == '__main__':
N = int(input())
for i in range(0,N,1):
given_input = input()
input_str_to_list = given_input.split(" ")
input_list.append(input_str_to_list)
for i in range(0,N,1):
input_dictionary[input_list[i][0]](input_list[i])
|
fc8492aca1595ba8df424f489c563b8c932edbde | pktippa/hr-python | /itertools/iterables_and_iterators.py | 932 | 3.875 | 4 | # Importing combinations from itertools
from itertools import combinations
# trash input not used in the code anywhere
trash_int = input()
# Taking input string split and get the list
input_list = input().split()
# Indices count
indices = int(input())
# first way
# Get the combinations, convert to list
combination_list = list(combinations(input_list, indices))
# initialize counter to 0
count = 0
# Loop through the combination_list
for el in combination_list:
# check if tuple contains 'a'
if 'a' in el:
count+=1
probability = count/len(combination_list)
# Another way as in editorial may be the best way
#combination_list_total = 0
# we can loop through combinations output since it is a iterable
#for el in combinations(input_list, indices):
# combination_list_total += 1
# count += 'a' in el # increment counter directly with condition
#probability = count/combination_list_total
print(probability) |
e03cc807d94143ba7377b192d5784cbdb07b1abd | pktippa/hr-python | /math/find_angle_mbc.py | 376 | 4.34375 | 4 | # importing math
import math
# Reading AB
a = int(input())
# Reading BC
b = int(input())
# angle MBC is equal to angle BCA
# so tan(o) = opp side / adjacent side
t = a/b
# calculating inverse gives the value in radians.
t = math.atan(t)
# converting radians into degrees
t = math.degrees(t)
# Rounding to 0 decimals and adding degree symbol.
print(str(int(round(t,0))) + '°') |
bed0fc094ed0b826db808aa4449cbf31686cbd2a | aryakk04/python-training | /functions/dict.py | 549 | 4.53125 | 5 | def char_dict (string):
""" Prints the dictionary which has the count of
each character occurrence in the passed string
argument
Args:
String: It sould be a string from which character
occurrence will be counted.
Returns:
Returns dictionary having count of each character
in the given string.
"""
char_dic = {}
for char in string:
if char not in char_dic:
char_dic[char] = string.count(char)
return char_dic
string = input("Enter a string : ")
char_dic = char_dict (string)
print (char_dic)
|
73ca8208af36edbc825de7e4579c8eb15ef1fcd6 | habahut/GrocerySpy | /Source/ingredientParserBAK.py | 12,462 | 3.75 | 4 | #! /usr/bin/env python
from ingredient import Ingredient
## these follow this form:
# <num> |unit| {name} (, modifer)
# so we split by " ". Then we check each thing for a comma.
# if there is a comma, we now know where the modifier is.
## for now we are going to assume everything is of the form above
## i.e. the modifier will come last, and all terms after the , will
## be part of the modifier.
## as we build this up with recipes from allrecipes.com, we will
# create a database of common words that can be associated with each category
# then we can use that database to help seperate the strings.
"""
Number words currently break this program...
i.e. "one can beef broth or 2 cups water with dissolved beef bouillon**"
who the fuck enters shit by typing out the number? what a bitch...
"""
class IngredientParser(object):
def __init__(self, parserDataFields):#, nameList, modifierList, amountList, unitStringList):
"""self.nameList = nameList
self.modifierList = modifierList
self.amountList = amountList
self.unitStringList = unitStringList"""
self.message = ""
self.inputStringList = []
self.currentString = 0
self.finalIngredientList = []
print parserDataFields
self.preModifierList = parserDataFields["PreModifiers"]
print self.preModifierList
def getFinishedIngredientList(self):
if self.message == "done":
return self.finalIngredientList
else:
return "notDone"
def passString(self, iS):
iS = iS.replace("\r\n", "\n")
self.inputStringList = iS.split("\n")
## this handles calls for the ingredientParser to 'parse'
# its given block of text
def parse(self):
result = ""
for i in range(self.currentString, len(self.inputStringList)):
result = self.doParse(self.inputStringList[i])
if isinstance(result, Ingredient):
## no errors, append this to the finalIngredientList
self.finalIngredientList.append(result.toString())
elif isinstance(result, str):
## returned a string, meaning there is confusion parsing the
# string,
"""
not implemented yet!!!
will ask the user for clarification regarding this specific
ingredient
"""
self.message = result
return result
## if it has gotten here than no confusion has occured, simply return
# "done" to let program know final list is ready
self.message = "done"
return "done"
def doParse(self, thisString):
print
print
print "working on: ", thisString
stringList = thisString.split()
print "num terms: ", len(stringList)
print
print
if (len(stringList) == 0):
## sometimes a blank line will come through
# so just return and wait for the next one
return None
amount = 0
unitString = ""
name = ""
modifiers = ""
done = False
# the format <#> <# ounce can of ____> currently breaks the program
# so we need to have a custom thing to detect that
if not (thisString.lower().find(" can ") == -1):
amount = self.parseAmount(stringList[0])
for i in range(1, len(stringList)):
name += stringList[i] + " "
unitString = name
return Ingredient(name, amount, unitString, modifiers)
## we first check some things about the stringList to try and
# guess the format it is in
if (not (thisString.find(",") == -1)):
tempList = thisString.split(",")
beforeCommaList = tempList[0].split()
afterCommaList = tempList[1].split()
## i.e.: "2 jalapenos, seeded and minced"
if (len(beforeCommaList) == 2):
amount = beforeCommaList[0]
name = beforeCommaList[1]
unitString = name
for s in afterCommaList:
modifiers += s + " "
return Ingredient(name, amount, unitString, modifiers)
if (len(stringList) == 2):
# the length is only two, so it must be something like
# "2 eggs," in which case the unit is the name and modifiers is blank
# it could be reverse ordered thought "eggs 2" or something...
if (stringList[0][0] == "." or stringList[0][0].isdigit()):
## the first part is a number so it is probably of the "2 eggs" variety
amount = self.handleHyphenatedAmount(stringList[0])
name = stringList[1]
# units will be teh same as name here
unitString = name
else:
## the order is probably reversed, so "eggs: 2"
# or something like that
## should ask alec for a regex that removes non-alphabetic characters
name = stringList[0]
unitString = name
amount = self.handleHyphenatedAmount(stringList[1])
done = True
elif (stringList[0][0] == "." or stringList[0][0].isdigit()):
## the first digit is a number
# stringList[0] is a number, which means it is an amount
# so we want to start on the second index of stringList
counter = 1
# in this case we will guess that it is of the form
# <num> |unit| {name} (, modifer)
# i.e.: 3 teaspoons sugar, granulated
amount += self.parseAmount(stringList[0])
## 3 possible options from here, a # - # meaning a range seperated by spaces
if (stringList[1] == "-"):
if (stringList[2][0] == "." or stringList[2][0].isdigit()):
temp = self.parseAmount(stringList[2])
amount = (amount + temp)/2.00
counter = 3
else:
raise IngredientInputError("Ingredient String Makes No Sense!")
elif (stringList[1][0] == "." or stringList[1][0].isdigit()):
amount += self.parseAmount(stringList[1])
counter += 1
## here we should cross check with the database to confirm if our assumption
# is correct. Checking the potential unitString against the database
# of previous unitStrings and "connectors:" i.e. "of, ':'" etc...
# will help determine if this ingredient string is of the type we guessed
#!!! here we need to also check if this word is something to do with the name
# of the ingredient. For example "green peppers" or "large onions." in either
# case green or large would fall into the "unit string" field.
unitString, modifiers, counter = self.considerUnitString(stringList, counter)
## since we have now assumed we have grabbed the above values correctly
# everything from here to the end of the string, or from here to a comma
# is part of the name of the ingredient
hasModifier = False
for i in range(counter, (len(stringList))):
if (not (stringList[i].find("(") == -1)):
hasModifier = True
break
name += stringList[i]
print "name is: ", name, " i @ ", i, " len: ", len(stringList)
if (not (name.find(",") == -1)):
# the string we just added contains a comma, meaning
# this ingredient has a modifier
name = name.strip(",")
i += 1
hasModifier = True
break
else:
name += " "
name = name.rstrip()
print
print
print "length of stringList = ", len(stringList)
print
print
if (hasModifier):
for i2 in range(i, len(stringList)):
modifiers += stringList[i2].strip(",").strip("(").strip(")")+ " "
print "modifiers: ", modifiers
if unitString == "":
unitString = name
print "name: ", name
print "modifiers: ", modifiers
print "amount: ", amount
print "unitString: ", unitString
# we want this to be in string form in the dictionary:
# i.e.: name?(,modifiers): amount unitString
# but we need to make it an ingredient for now so we can differentiate
# between finished products and error messages
return Ingredient(name, amount, unitString, modifiers)
def parseAmount(self, stringList):
amountList = stringList.split("-")
blankElements = []
for i in range(len(amountList)):
if amountList[i] == "":
blankElements.append(i)
else:
amountList[i] = self.handleFractionalAmount(amountList[i])
for i in blankElements:
amountList.pop(i)
if (len(amountList) == 1):
return amountList[0]
else:
return (amountList[0] + amountList[1])/2.00
def handleFractionalAmount(self, string):
s = string.split("/")
if (len(s) == 1):
## i.e. no fraction
print "s[0] is : ", s[0]
return float(s[0])
else:
return float(s[0])/float(s[1])
def considerUnitString(self, stringList, startIndex):
modS = ""
unitString = ""
done = False
while not done:
done = True
if (not (stringList[startIndex].find("(") == -1)):
if (not (stringList[startIndex].find(")") == -1)):
modS += stringList[startIndex].strip("(").strip(")") + " "
startIndex += 1
else:
modS += stringList[startIndex].strip("(") + " "
startIndex += 1
while (not (stringList[startIndex].find(")") == -1)):
modS += stringList[startIndex].strip(")") + " "
startIndex += 1
for word in self.preModifierList:
if stringList[startIndex].strip(",").lower() == word.lower():
modS += stringList[startIndex].strip(",") + " "
startIndex += 1
done = False
break
if modS == "":
unitString = stringList[startIndex].strip(",")
startIndex += 1
print "after consideration: unitString:", unitString, " modS: ", modS, " startIndex: ", startIndex
return unitString,modS,startIndex
class IngredientInputError(Exception):
def __init__(self, v):
self.val = v
def __str__str(self):
return repr(self.val)
if __name__ == "__main__":
parser = IngredientParser({"PreModifiers": ["delicious","sweet","green", "red", "orange", "blue", "spicy", "large", "chopped", "big", "medium", "sized"]})
#parser = IngredientParser(["large","green"])
datString = raw_input("try me: ")
parser.passString(datString)
print "returned", parser.parse()
print "==========="
#print parser.considerUnitString(datString.split(), 1)
print
print
print "final ingredient List: " , parser.getFinishedIngredientList()
"""
4 medium sized potatoes (peeled/chunked)
3 carrots (sliced)
1 sweet (bell) green pepper (chunked)
1 medium sized yellow onion (chopped)
1/4 head of green cabbage (shredded)
1-2 stalks of celery (sliced 1/4-1/2")
1 red delicious apple (peeled/chunked)
1 small turnip (chunked)
1- 14 oz can whole kernel corn (drained)
1- 14oz can green peas (drained)
64 oz V8 (or other brand) 100% vegetable juice
1.5 lb. beef chuck roast
one can beef broth or 2 cups water with dissolved beef bouillon**
1 tsp dried basil
1 tsp. oregano
"""
|
8f4737c5028b5237c809d24ee24fd3280d466d46 | SamuelSebastianMartin/folder_tree_ac_eng | /make_google_folders.py | 3,087 | 3.8125 | 4 | #! /usr/bin/env python3
"""
This may be a one-off program, depending on changes made to registers.
It reads a SOAS Google Docs register (2019-20) into a pandas dataframe
and creates folders necessary for all academic English student work.
Student work/
|
|___ SURNAME Firstname/
| |
| |__Term 1/
| |
| |__Term 2/
| |
| |__Term 3/
|
|____NEXT Student/
| |
| |__Term 1/
| |
| |__Term 2/
| |
| |__Term 3/
"""
import pandas as pd
import re
import os
def filepicker():
"""
Opens a graphical file selection window, and returns
the path of the selected file.
"""
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
return file_path
def read_register():
"""
Opens a csv file (given the filepath, and returns a pandas
dataframe.
"""
print("Please select a downloaded register file")
filename = filepicker()
if ".csv" not in filename:
print("You must select a .csv file, exported from Google forms")
register = pd.read_csv(filename)
return register
def extract_names(register):
"""
Extracts the names from the relevant columns of the dataframe.
This is not a robust function, and will break if the registers
change the order of the columns.
"""
names = []
for i in range(len(register) - 1): # len() -> no of columns
first_name = str(register.iloc[i][2]).capitalize()
last_name = str(register.iloc[i][1]).upper()
name = last_name + ' ' + first_name
names.append(name)
names = list(set(names))
return names
def clean_names_list(names):
"""
Takes out NaN entries and 'Surname' & 'firstname' headings.
This is not a robust function, and will break if the registers
change their column headings.
"""
pure_names = []
nan = re.compile('nan', re.IGNORECASE)
title = re.compile('surname', re.IGNORECASE)
for name in names:
if nan.search(name):
continue
elif title.search(name):
continue
else:
pure_names.append(name)
return pure_names
def make_directories(names):
"""
Given a list of names, this function creates a
new directory for each name.
Within each new directory, sub-directories are
created: 'Term 1', 'Term 2', 'Term 3'
"""
os.mkdir('Student_Folders')
os.chdir('Student_Folders')
for name in names:
os.mkdir(name)
os.chdir(name)
sub_dirs = ['Term 1', 'Term 2', 'Term 3']
for drcty in sub_dirs:
os.mkdir(drcty)
os.chdir('..')
def main():
"""
Asks user to select list of names (register).
and makes a directory for each name.
"""
register = read_register()
names = extract_names(register)
names = clean_names_list(names)
make_directories(names)
print(names)
if __name__ == '__main__':
main()
|
149b7cdf5c74d2bc96c2249ad192000659303926 | edmartins-br/PythonTraining | /general.py | 4,281 | 4.0625 | 4 | #! /usr/bin/python3
#Fiibonacci
a,b = 0, 1
for i in range(0, 10):
print(a)
a, b = b, a + b
# ----------------------------------------------------------------
# FIBONACCI GENERATOR
def fib(num):
a,b = 0, 1
for i in range(0, num):
yield "{}: {}".format(i+1, a)
a, b = b, a + b
for item in fib(10):
print (item)
# ----------------------------------------------------------------
# LISTAS SÃO IMUTAVEIS E TUPLAS SÃO MUTÁVEIS
my_list = [1,2,3,4,5,6,7,8,9,10]
squares = [num*num for num in my_list]
print (squares)
# ---------------------- OOP ------------------------------------------
class Person(object):
def _init_(self, name):
self.name = name
def reveal_identity(self):
print("My name is {}".format(self.name))
class SuperHero(Person):
def _init_(self, name, hero_name):
super(SuperHero, self)._init_(name)
self.hero_name = hero_name
def reveal_identity(self):
super(SuperHero, self).reveal_identity()
print("...And I am {}".format(self.hero_name))
# corey = Person('Corey')
# corey.reveal_identity()
wade = SuperHero('Wade Wilson', 'Deadpool')
wade.reveal_identity()
# ----------------------------------------------------------------
class employee:
def _init_(self, firstName, lastName, salary):
self.firstName = firstName
self.lastName = lastName
self.salary = salary
self.email = self.firstName + "." + self.lastName + "@outlook.com"
def giveRaise(self, salary):
self.salary = salary
class developer(employee):
def _init_(self, firstName, lastName, salary, programming_languages):
super()._init_(firstName, lastName, salary)
self.prog_langs = programming_languages
def addLanguage(self, lang):
self.prog_langs += [lang]
employee1 = employee("Jon", "Montana", 100000)
print(employee1.salary)
employee1.giveRaise(100000)
print(employee1.salary)
dev1 = developer("Joe", "Montana", 100000, ["Python", "C"])
print(dev1.salary)
dev1.giveRaise(125000)
print(dev1.salary)
dev1.addLanguage("Java")
print(dev1.prog_langs)
# ----------------------------------------------------------------
# STRING FORMATING
name = "Eduardo"
age = 33
string = "Hi, my name is %s and I am %i years old" % (name, age) # similar to printf in C language
print(string)
string2 = "Hi, my name is {} and I am {} years old" .format(name, age)
print(string2)
string3 = f"Hello, {name}"
print(string3)
string4 = f"1 + 1 is {1 + 1}"
print(string4)
# ----------------------------------------------------------------
# DATA STRUCTURE
# STaCK
stack = []
stack.append(1)
stack.append(2)
pop_elem = stack.pop()
print(stack, pop_elem)
queue = []
queue.append(1)
queue.append(2)
pop_elem = queue.pop(0)
print(queue, pop_elem)
# SET
set1 = set([1,2,3,4,5,6])
set2 = set([2,4,3,1,8,7,9,2])
print(set1 & set2)
# DICTIONARY
ages = dict()
ages["bob"] = 22
ages["emily"] = 20
for key, value in ages.items():
# print(ages)
print(key, value)
# LIST COMPREHENSION
lst = [1,2,3,4,5,6,7]
even_lst = [x for x in lst if x % 2 == 0]
print(even_lst)
square_lst = [x ** 2 for x in lst]
print(square_lst)
# PYTHON STANDARD LIBRARIES
from collections import defaultdict
exam_grades = [("Bob", 43), ("Joe", 98), ("Eduardo", 89), ("Mark", 90), ("Tiff", 44), ("Jan", 56)]
student_grades = defaultdict(list)
for name, grade in exam_grades:
student_grades[name].append(grade)
print(student_grades)
print(student_grades["Eduardo"])
from collections import Counter
numbers = [1,2,3,4,5,6,7,8,3,5,7,8,3,2, 8, 8, 8, 8, 8]
counts = Counter(numbers)
print(counts)
top2 = counts.most_common(2)
print(top2)
# ex: [(8, 7), (3, 3)] - Numero 8 ocorreu 7 vezes e o número 3 ocorreu 3 vezes
class Carro:
def _init_(self, marca, preco, cor):
self.marca = marca
self.preco = preco
self.cor = cor
def mostraMarca(self):
print('A marca do carro é {}'.format(self.marca))
def mostraPreco(self):
print('O preço do carro é R${}'.format(self.preco))
def mostraCor(self):
print('A cor do carro é {}'.format(self.cor))
meuCarro = Carro('Volks', 45000, 'Prata')
meuCarro.mostraMarca()
meuCarro.mostraPreco()
meuCarro.mostraCor() |
2d87b86197a7790b8596ee19e8099661d2a89536 | ZinoKader/X-Pilot-AI | /pathfinding/navigator.py | 2,045 | 3.6875 | 4 | import math
import helpfunctions
class Navigator:
def __init__(self, ai, maphandler):
self.ai = ai
self.pathlist = []
self.maphandler = maphandler
def navigation_finished(self, coordinates):
targetX = int(coordinates[0])
targetY = int(coordinates[1])
selfX = self.ai.selfX()
selfY = self.ai.selfY()
self_block = self.maphandler.coords_to_block(selfX, selfY)
target_block = self.maphandler.coords_to_block(targetX, targetY)
if self_block == target_block:
print("navigation completed")
return True
return False
def navigate(self, coordinates):
targetX = int(coordinates[0])
targetY = int(coordinates[1])
selfX = self.ai.selfX()
selfY = self.ai.selfY()
self_block = self.maphandler.coords_to_block(selfX, selfY)
target_block = self.maphandler.coords_to_block(targetX, targetY)
if self_block == target_block:
self.ai.talk("teacherbot: move-to-pass {}, {} completed".format(targetX, targetY))
print("navigation completed")
# om vi hamnar på vilospår, hämta ny pathlist
if not self.pathlist or self_block not in self.pathlist:
self.pathlist = self.maphandler.get_path(self_block, target_block)
while self_block in self.pathlist: # förhindra att vi åker tillbaka (bugg)
self.pathlist.remove(self_block)
if self.pathlist:
next_move_block = (self.pathlist[0][0], self.pathlist[0][1])
next_move_coords = self.maphandler.block_to_coords(next_move_block)
targetDirection = math.atan2(next_move_coords[1] - selfY, next_move_coords[0] - selfX)
self.ai.turnToRad(targetDirection)
self.ai.setPower(8)
# thrusta endast när vi har nästa block i sikte så vi inte thrustar in i väggar
if helpfunctions.angleDiff(self.ai.selfHeadingRad(), targetDirection) < 0.1:
self.ai.thrust()
|
2bc03bbfed056ccd044b253e6e1430c59215d59a | ZinoKader/X-Pilot-AI | /excercises/exc3.py | 5,294 | 3.5625 | 4 | #
# This file can be used as a starting point for the bot in exercise 1
#
import sys
import traceback
import math
import os
import libpyAI as ai
from optparse import OptionParser
#
# Create global variables that persist between ticks.
#
tickCount = 0
mode = "wait"
targetId = -1
def tick():
#
# The API won't print out exceptions, so we have to catch and print them ourselves.
#
try:
#
# Declare global variables so we're allowed to use them in the function
#
global tickCount
global mode
global targetId
#
# Reset the state machine if we die.
#
if not ai.selfAlive():
tickCount = 0
mode = "aim"
return
tickCount += 1
#
# Read some "sensors" into local variables to avoid excessive calls to the API
# and improve readability.
#
selfX = ai.selfX()
selfY = ai.selfY()
selfHeading = ai.selfHeadingRad()
# 0-2pi, 0 in x direction, positive toward y
targetCount = ai.targetCountServer()
#print statements for debugging, either here or further down in the code.
# Useful functions: round(), math.degrees(), math.radians(), etc.
# os.system('clear') clears the terminal screen, which can be useful.()
targetCountAlive = 0
for i in range(targetCount):
if ai.targetAlive(i):
targetCountAlive += 1
# Use print statements for debugging, either here or further down in the code.
# Useful functions: round(), math.degrees(), math.radians(), etc.
# os.system('clear') clears the terminal screen, which can be useful.
targetlist = {}
for i in range(targetCount):
if ai.targetAlive(i):
targetdistance = ( ( (ai.targetX(i) - selfX) ** 2) + ( (ai.targetY(i) - selfY) ** 2) ) ** (1 / 2)
targetlist[targetdistance] = i
targetId = targetlist.get(min(targetlist))
print("current targetId: " + str(targetId))
targetX = ai.targetX(targetId) - selfX
targetY = ai.targetY(targetId) - selfY
print(targetX)
print(targetY)
print(targetlist)
targetdistance = ( ( targetX ** 2) + ( targetY ** 2) ) ** (1 / 2)
targetDirection = math.atan2(targetY, targetX)
print(targetDirection)
velocity = ((ai.selfVelX() ** 2) + (ai.selfVelY() ** 2)) ** (1 / 2)
velocityvector = math.atan2(ai.selfVelY(), ai.selfVelX())
print("tick count:", tickCount, "mode:", mode, "heading:",round(math.degrees(selfHeading)), "targets alive:", targetCountAlive)
if mode == "wait":
if targetCountAlive > 0:
mode = "aim"
elif mode == "aim":
if targetCountAlive == 0:
mode = "wait"
return
if velocity < 15 and tickCount % 3 == 0:
ai.turnToRad(targetDirection)
ai.setPower(40)
ai.thrust()
elif velocity > 15:
ai.turnToRad(velocityvector + math.pi)
ai.setPower(55)
ai.thrust()
angledifference = angleDiff(selfHeading, targetDirection)
if angledifference <= 0.05 and targetdistance < 600:
mode = "shoot"
else:
mode = "aim"
elif mode == "shoot":
if not ai.targetAlive(targetId):
mode = "aim"
else:
if velocity > 10 and targetdistance > 500:
ai.turnToRad(velocityvector + math.pi)
ai.setPower(55)
ai.thrust()
elif targetdistance < 250: #spin-circus compensation. Will eventually fully stop if the ship keeps spinning around a target.
if velocity > 5:
ai.turnToRad(velocityvector + math.pi)
ai.setPower(55)
ai.thrust()
else:
ai.turnToRad(targetDirection)
ai.fireShot()
elif targetdistance < 600:
ai.turnToRad(targetDirection)
ai.setPower(55)
ai.thrust()
ai.fireShot()
elif targetdistance > 800:
mode = "aim"
except:
#
# If tick crashes, print debugging information
#
print(traceback.print_exc())
def angleDiff(one, two):
"""Calculates the smallest angle between two angles"""
a1 = (one - two) % (2*math.pi)
a2 = (two - one) % (2*math.pi)
return min(a1, a2)
#
# Parse the command line arguments
#
parser = OptionParser()
parser.add_option ("-p", "--port", action="store", type="int",
dest="port", default=15345,
help="The port to use. Used to avoid port collisions when"
" connecting to the server.")
(options, args) = parser.parse_args()
name = "Exc. 1 skeleton" #Feel free to change this
#
# Start the main loop. Callback are done to tick.
#
ai.start(tick, ["-name", name,
"-join",
"-turnSpeed", "64",
"-turnResistance", "0",
"-port", str(options.port)])
|
8e18bf9cc041596acb023cd5d68c0933f432f6cd | hitsumabushi845/Cure_Hack | /addSongInfoToDB.py | 1,167 | 3.65625 | 4 | import sqlite3
from createSpotifyConnection import create_spotify_connection
def add_songinfo_to_db():
db_filename = 'Spotify_PreCure.db'
conn = sqlite3.connect(db_filename)
c = conn.cursor()
spotify = create_spotify_connection()
albumIDs = c.execute('select album_key, name from albums;')
sql = 'insert into songs ' \
'(song_key, artist_key, album_key, title, href_url, duration_ms, disk_number, track_number) ' \
'values (?,?,?,?,?,?,?,?)'
for album in albumIDs.fetchall():
print('Processing {}...'.format(album[1]))
songs = spotify.album_tracks(album_id=album[0], limit=50)
for song in songs['items']:
songdata = (song['id'],
song['artists'][0]['id'],
album[0], song['name'],
song['external_urls']['spotify'],
song['duration_ms'],
song['disc_number'],
song['track_number'])
print(songdata)
c.execute(sql, songdata)
conn.commit()
print("end")
if __name__ == '__main__':
add_songinfo_to_db()
|
9d035da888745f18febd025b110dab7cb6f1f2d7 | KarChun0227/PythonQuizz | /Expertrating/Word_sort.py | 201 | 3.984375 | 4 | input_str = input()
result = ""
word = input_str.split(",")
sortedword = sorted(word)
for x in sortedword:
result = result + "," + x
result = result[1:]
print(result)
# order,hello,would,test |
a5bb0c599c2cb8e70b3d60a85932b9fd28b65780 | KarChun0227/PythonQuizz | /Exercise/Ex8.py | 747 | 3.953125 | 4 | def winner(P1, P2):
if P1 == P2:
return 0
elif P1 == "S":
if P2 == "R":
return 2
else:
return 1
elif P1 == "R":
if P2 == "S":
return 1
else:
return 2
elif P1 == "P":
if P2 == "S":
return 2
else:
return 1
while True:
p1 = input("Player one:")
p2 = input("Player two:")
result = winner(p1,p2)
if result == 0:
print ("No Winner!!")
elif result == 1:
print ("Winner is Payer 1")
if input("Wish to continue?") == "no":
break
elif result == 2:
print ("Winner is Payer 2")
if input("Wish to continue?") == "no":
break
|
7d27fc42523b5ae8e1cb509c38d5538c85d959d5 | KarChun0227/PythonQuizz | /Expertrating/exam.py | 199 | 3.890625 | 4 | import string
input_str = raw_input()
for i in range(1,6):
password = input_str[i]
if (password)<5:
return False
if " " in password:
return False
if "*" or "#" or "+" or "@" in
|
f4f03e85c8c0d572714451962e539fd4736c18c8 | lulzzz/counter-1 | /Counter/serv/report_python/reportmg.py | 711 | 3.78125 | 4 | import sqlite3
import re
conn = sqlite3.connect('/Users/itlabs/db1.db')
cur = conn.cursor()
cur.execute('''
DROP TABLE IF EXISTS mega''')
cur.execute('''
CREATE TABLE mega (dates TEXT, people TEXT)''')
fname = '/tfs/report-MEGA.txt'
fh = open(fname)
count = 0
for line in fh:
if not count % 2:
people = line
count = count + 1
continue
else:
dates = line.split()[2]
alla = people, dates
count = count + 1
# Insert a row of data
cur.execute("INSERT INTO mega VALUES (?,?)", alla)
# Save (commit) the changes
conn.commit()
sqlstr = 'SELECT dates, people FROM mega'
for row in cur.execute(sqlstr) :
print str(row[0]), row[1]
cur.close()
|
bf61860cd0381b0b6eb5563ff529da0b4a07c9bf | PavelErsh/Python-for-pro | /shop.py | 896 | 3.6875 | 4 | from datetime import datetime
class Greeter:
def __init__(self, name, store):
self.name = name
self.store = store
def _day(self):#tace date
return datetime.now().strftime('%A')
def _part_of_day(self):
current_hour = datetime.now().hour
if current_hour < 12:
part_of_day = 'утра'
elif 12 <= current_hour < 17:
part_of_day = 'дня'
else:
part_of_day = 'вечера'
return part_of_day
def greet(self):
print(f'Здравствуйте, меня зовут {self.name}, и добро пожаловать в {self.store}!')
print(f'Желаем вам приятного {self._part_of_day()} {self._day()}?')
print('Дарим вам купон на скидку 20 %!')
welcome = Greeter("bishop", "test")
welcome.greet() |
766b98ad78790d5cb7436b20afc07ddc1b8fdd0e | Asakura-Hikari/assignment-2-travel-tracker-Asakura-Hikari | /a1_classes.py | 4,745 | 3.65625 | 4 | """
Replace the contents of this module docstring with your own details
Name: Chaoyu Sun
Date started: 31/july/2020
GitHub URL: https://github.com/JCUS-CP1404/assignment-1-travel-tracker-Asakura-Hikari
"""
# main() function is to open and save the file.
def main():
print("Travel Tracker 1.0 - by Chaoyu Sun")
print("3 places loaded from places.csv")
file = open("places.csv", "r+")
content = file.readlines() # read the whole file
place_list = [] # create a list to add every place
for i in content: # split one place to one list
place = i.strip('\n').split(',')
place_list.append(place)
file.seek(0) # reset file index to the beginning
place_list = menu(place_list)
for place in place_list: # write list into file
file.write("{},{},{},{}\n".format(place[0], place[1], place[2], place[3]))
file.close()
print("{} places saved to places.csv".format(len(place_list)))
print("Have a nice day :)")
# menu() function is to loop the main menu.
def menu(place_list):
var = True # set quit value
while var:
place_list = sorted(place_list, key=lambda x: (x[3], int(x[2]))) # sort list
print("Menu:")
print("L - List places
")
print("A - Add new place")
print("
M - Mark a place as visit
")
print("Q - Quit")
select = input(">>> ").upper() # get upper input value
if select == 'L':
list_places(place_list)
elif select == 'A':
place_list = add_new_place(place_list)
elif select == 'M':
place_list = mark_place(place_list)
elif select == 'Q':
return place_list
else:
print("Invalid menu choice")
# list_places is to list the places in menu.
def list_places(place_list):
i = 0 # to count unvisited place number
for place in place_list:
i += 1
if place[3] == 'n': # printing depend visit and unvisited
print("*{}. {:<15} in {:<15} priority {:<15}".format(i, place[0], place[1], place[2]))
else:
print(" {}. {:<15} in {:<15} priority {:<15}".format(i, place[0], place[1], place[2]))
# add_new_place is to add new places in list.
def add_new_place(place_list):
new_place = []
name = input("Name: ")
while name == '': # retry if name is blank
print("Input can not be blank
")
name = input("Name: ")
new_place.append(name)
country = input("Country: ")
while country == '': # retry if country is blank
print("Input can not be blank
")
country = input("Country: ")
new_place.append(country)
var = True # create a support variable to help loop
while var:
try: # retry if priority not a number
priority = int(input("Priority: "))
except ValueError:
print("Invalid input, enter a valid number
")
continue
if priority < 0: # retry if priority is a negative number
print("Number must be > 0")
else:
new_place.append(priority)
new_place.append("n")
print("{} in {} (priority {}) added to Travel Tracker
".format(name, country, priority))
place_list.append(new_place) # add new place in list
return place_list
# mark_place is to change place from unvisited to visit.
def mark_place(place_list):
unvisited = 0
for place in place_list:
if place[3] == 'n': # to check how many places are unvisited.
unvisited += 1
if unvisited == 0: # if all places are unvisited, return the function.
print("No unvisited places")
return
list_places(place_list)
print("{} places. You still want to visit {} places.".format(len(place_list), unvisited))
var = True
while var:
try: # check if enter value not a number.
print("Enter the number of a place to mark as unvisited
")
mark = int(input(">>> "))
except ValueError:
print("Invalid input; enter a valid number")
continue
if mark < 0: # check the number must large than 0.
print("Number must be > 0")
elif mark > len(place_list): # check the number is valid number in place.
print("Invalid place number")
elif place_list[mark - 1][3] == 'v': # check if this place are unvisited.
print("That place is already unvisited")
else: # change place to unvisited successfully.
place_list[mark - 1][3] = 'v'
print("{} in {} unvisited!".format(place_list[mark - 1][0], place_list[mark - 1][1]))
return place_list
if __name__ == '__main__':
main()
|
2e0deae0231338db84a2f11cd64994bf82900b33 | seanakanbi/SQAT | /SampleTests/Sample/classes/Calculator.py | 1,677 | 4.375 | 4 | import math
from decimal import *
class Calculator():
"""
A special number is any number that is
- is between 0 and 100 inclusive and
- divisible by two and
- divisible by five.
@param number
@return message (that displays if the number is a special number)
"""
def is_special_number(self, num_in):
# Verify the number is within the valid range.
if num_in < 0 or num_in > 100:
message = " is not a valid number."
else:
# Determine if the number is a special number.
if num_in % 2 != 0:
message = " is not an even number."
elif num_in % 5 != 0:
message = " is not divisible by five."
else:
message = " is a special number"
#Remember this will return your number plus the message!
return str(num_in) + message
"""
This method does a strange/alternative calculation
* @param operand
* @return calculated value as a Decimal
"""
def alternative_calculate(self, operand):
calculated_value = operand * 100 / math.pi
return Decimal(calculated_value)
if __name__ == '__main__':
print("****** ******* ")
print("****** Running calculator ******* ")
calc = Calculator()
num1 = int(input("Please enter a number to check if it is special: " ))
print("-> ", calc.is_special_number(num1))
num2 = int(input("Please enter a number to run an alternative calculation on it: " ))
print("-> ", round(calc.alternative_calculate(num2),4))
|
af698f93e23c3d8a429b72ecc03bdb272de5d3b5 | patrickgaskill/project-euler | /patrick.py | 642 | 3.671875 | 4 | from functools import reduce
from operator import mul
from math import sqrt
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
w = 6 - w
return True
def prod(a):
return reduce(mul, a)
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(sqrt(n)) + 1) if n % i == 0)))
def tup2int(t):
return int(''.join(t))
|
d9de3d0d4860d0ace81217ddf8fa23bd15c47c16 | patrickgaskill/project-euler | /7.py | 177 | 3.625 | 4 | from patrick import is_prime
N = 10001
primes = [2, 3]
i = primes[-1] + 2
while len(primes) < N:
if (is_prime(i)):
primes.append(i)
i += 2
print(primes[-1])
|
87d068764544cb2670704d56028940a1847bd061 | TheUlr1ch/3- | /main3.py | 655 | 3.984375 | 4 | # 1-е задание
myList = [1, 2, 3]
myNewList = [i * 2 для i в myList]
print(myNewList)
# 2-е задание
myList = [1, 2, 3]
myNewList = [i * * 2 для i в myList]
print(myNewList)
# 3-е задание
list = 'Hello world'
для i в диапазоне(len(list)):
if list[i] == " ":
список = список.заменить("w", "W")
печать(список)
# 4-е задание
из datetime импорт datetime
год1 = дата-время .сейчас().год
год2 = 1900
ren = год1 - год2
для i в диапазоне(ren+1):
печать(год2 + i)
|
0df98d530f508a752e42a67ad7c6fe0a2608f823 | JaiAmoli/Project-97 | /project97.py | 266 | 4.21875 | 4 | print("Number Guessing Game")
print("guess a number between 1-9")
number = int(input("enter your guess: "))
if(number<2):
print("your guess was too low")
elif(number>2):
print("your guess was too high")
else:
print("CONGRATULATIONS YOU WON!!!") |
a71aa0afdb02234d87afe81f5b3b912748e66027 | marcusshepp/hackerrank | /python/anagram.py | 1,963 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding: ascii -*-
""" Your task is to help him find the minimum number of characters of the first string he needs to
change to enable him to make it an anagram of the second string.
Note: A word x is an anagram of another word y if we can produce y by rearranging the letters of x.
Input Format The first line will contain an integer, T, representing the number of test cases.
Each test case will contain a string having length len(S1)+len(S2),
which will be concatenation of both the strings described above in the problem.
The given string will contain only characters from a to z.
Output Format An integer corresponding to each test case is printed in a different line,
"""
def min_del(s):
c_ = 0
_u = len(s)
q_ = list(s)
if _u % 2 == 0:
l_side = q_[_u/2:]
r_side = q_[:_u/2]
pok = {}
for i in l_side:
if i in pok:
pok[i] += 1
else:
pok[i] = 1
for j in r_side:
if j in pok:
if pok[j] > 0:
pok[j] -= 1
else:
c_ += 1
for x in pok:
if pok[x] > 0:
c_ += 1
else:
c_ = -1
return c_
# for i in range(int(raw_input())):
# print min_del(str(raw_input()))
print "10 -- ", min_del("hhpddlnnsjfoyxpciioigvjqzfbpllssuj")
print "13 -- ", min_del("xulkowreuowzxgnhmiqekxhzistdocbnyozmnqthhpievvlj")
print "5 -- ", min_del("dnqaurlplofnrtmh")
print "26 -- ", min_del("aujteqimwfkjoqodgqaxbrkrwykpmuimqtgulojjwtukjiqrasqejbvfbixnchzsahpnyayutsgecwvcqngzoehrmeeqlgknnb")
print "15 -- ", min_del("lbafwuoawkxydlfcbjjtxpzpchzrvbtievqbpedlqbktorypcjkzzkodrpvosqzxmpad")
print "-1 -- ", min_del("drngbjuuhmwqwxrinxccsqxkpwygwcdbtriwaesjsobrntzaqbe")
print "3 -- ", min_del("ubulzt")
print "13 -- ", min_del("vxxzsqjqsnibgydzlyynqcrayvwjurfsqfrivayopgrxewwruvemzy")
print "13 -- ", min_del("xtnipeqhxvafqaggqoanvwkmthtfirwhmjrbphlmeluvoa")
print "-1 -- ", min_del("gqdvlchavotcykafyjzbbgmnlajiqlnwctrnvznspiwquxxsiwuldizqkkaawpyyisnftdzklwagv")
"""
10
13
5
26
15
-1
3
13
13
-1
""" |
88794e943e08e346af71e6e3e8b398a22c6c4432 | marcusshepp/hackerrank | /python/openkattis/ahh.py | 177 | 3.78125 | 4 | jon = raw_input()
doc = raw_input()
def noh(s):
return [a for a in s if a != "h"]
jon = noh(jon)
doc = noh(doc)
if len(jon) >= len(doc):
print "go"
else:
print "no" |
956019e0287fed6689e94f291add98e827fc9744 | marcusshepp/hackerrank | /python/warmup/chocolate_feast.py | 610 | 3.640625 | 4 | """
Problem Statement:
Little Bob loves chocolate, and he goes to a store with $N in his pocket.
The price of each chocolate is $C. The store offers a discount:
for every M wrappers he gives to the store, he gets one chocolate for free.
How many chocolates does Bob get to eat?
Input Format:
The first line contains the number of test cases, T.
T lines follow, each of which contains three integers, N, C, and M.
Output Format:
Print the total number of chocolates Bob eats.
"""
def chocolate(money, cost, wrappers):
c = 0
for i in range(1, money):
if i % money == 0:
c += 1
if c % wrappers == 0
|
7b9c3c2cd1a9f753a9f3df2adeb84e846c9eb1b4 | mschaldias/programmimg-exercises | /list_merge.py | 1,395 | 4.34375 | 4 | '''
Write an immutable function that merges the following inputs into a single list. (Feel free to use the space below or submit a link to your work.)
Inputs
- Original list of strings
- List of strings to be added
- List of strings to be removed
Return
- List shall only contain unique values
- List shall be ordered as follows
--- Most character count to least character count
--- In the event of a tie, reverse alphabetical
Other Notes
- You can use any programming language you like
- The function you submit shall be runnable
For example:
Original List = ['one', 'two', 'three',]
Add List = ['one', 'two', 'five', 'six]
Delete List = ['two', 'five']
Result List = ['three', 'six', 'one']*
'''
def merge_lists(start_list,add_list,del_list):
set_start = set(start_list)
set_add = set(add_list)
set_del = set(del_list)
set_final = (set_start | set_add) - set_del
final_list = list(set_final)
final_list.sort(key=len, reverse=True)
return final_list
def main():
start_list = ['one', 'two', 'three',]
add_list = ['one', 'two', 'five', 'six']
del_list = ['two', 'five']
#final_list = ['three', 'six', 'one']
final_list = merge_lists(start_list,add_list,del_list)
print(final_list)
main() |
c65d5f051adcb61c0b2b98e304551f4538779177 | tethig/oyster_catchers | /oyster_catchers/gaussian_walk.py | 1,001 | 3.65625 | 4 | '''
Generalized behavior for random walking, one grid cell at a time.
'''
# Import modules
import random
from mesa import Agent
# Agent class
class RandomWalker(Agent):
'''
Parent class for moving agent.
'''
grid = None
x = None
y = None
sigma = 2
def __init__(self, pos, model, sigma=2):
'''
grid: The MultiGrid object in which the agent lives.
x: The agent's current x coordinate
y: The agent's current y coordinate
sigma: deviation from home square
'''
super().__init__(pos, model)
self.pos = pos
self.sigma = 2
def gaussian_move(self):
'''
Gaussian step in any allowable direction.
'''
x, y = self.pos
coord = (x, y)
while coord == self.pos:
dx, dy = int(random.gauss(0, self.sigma)), int(random.gauss(0, self.sigma))
coord = (x + dx, y + dy)
# Now move:
self.model.grid.move_agent(self, coord)
|
3df2910d100c84048bee5a5a965580cdea802811 | susie9393/spaces | /spaces.py | 1,413 | 3.796875 | 4 | # spaces
import numpy as np
import random as rn
def Spaces(no_rolls):
# initialise an array to record number of times each space is landed on
freq = np.zeros(14)
# s denotes space landed on, 1 <= s <= 14
s = 0
# a counter has been set up to perform a check on total number of squares landed on
count = 0
for n in range(no_rolls):
dice1 = rn.randint(1,6)
dice2 = rn.randint(1,6)
moves = dice1 + dice2
s+=moves
if s > 14:
s-=14
if s == 4:
freq[s-1]+=1
count+=1
s = 10
if s == 7 and (dice1 == 6 or dice2 == 6):
freq[s-1]+=1
count+=1
s = 1
if s == 10 and moves%2==0:
freq[s-1]+=1
count+=1
s = 5
freq[s-1]+=1
if np.sum(freq)==200+count:
return freq
else:
print "Error"
def Average(iterations):
total = []
for i in range(iterations):
freq = Spaces(200)
total.append(freq)
freq = np.mean(np.array(total), axis = 0)
print np.around(freq)
Average(10)
|
6aaf293f5c0eb3ecbeac2a8844eae47189ed22b5 | Romannweiler/hu_bp_python_course | /02_introduction/guess_a_number_rm.py | 853 | 3.984375 | 4 | # This is a guess the number game.
import random
guessesTaken = 0
print('Welcome to my Game')
print('I am thinking of a number between 0 and 100!')
number = random.randint(0, 100)
while guessesTaken < 4:
numTries = 3 - guessesTaken
numTriesStr = str(numTries)
print('you have '+ numTriesStr +' tries')
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
|
da4f38b16f878727966067fa8da540115169ad66 | Nori1117/Recursion-lv.2 | /MyLogic.py | 1,075 | 3.890625 | 4 | #Given a number n, write a program to find the sum of the largest prime factors of each of nine consecutive numbers starting from n.
#g(n) = f(n) + f(n+1) + f(n+2) + f(n+3) + f(n+4) + f(n+5) + f(n+6) + f(n+7) + f(n+8)
#where, g(n) is the sum and f(n) is the largest prime factor of n
def find_factors(num):
factors = []
for i in range(2,(num+1)):
if(num%i==0):
factors.append(i)
return factors
def is_prime(num, i):
if(i==1):
return True
elif(num%i==0):
return False;
else:
return(is_prime(num,i-1))
def find_largest_prime_factor(list_of_factors):
large=[]
for i in list_of_factors:
if is_prime(i,i//2)==True:
large.append(i)
return max(large)
def find_f(num):
f=find_factors(num)
l=find_largest_prime_factor(f)
return l
def find_g(num):
sum=0
consicutive=[i for i in range(num,num+9)]
for i in consicutive:
largest_prime_factor=find_f(i)
sum=sum+largest_prime_factor
return sum
print(find_g(10))
|
7473ceb49464bcf2268a790243b1dae6c671ec03 | zhouxiongaaa/myproject | /my_game/congratulation.py | 266 | 3.71875 | 4 | name = input('你想给谁发祝福:')
def cong(name1):
a = list(map(lambda x: 'happy birthday to' + (' you' if x % 2 == 0 else ' '+name1+''), range(4)))
return a
if __name__ == '__main__':
print(cong(name))
b = input('如要退出请输入exit:')
|
bac10c57ecb9bccb3a13cda38a104937d8bcd1b2 | Goro-Majima/OpenFoodFacts | /pureBeurre.py | 4,468 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""Starting program that calls insert and display functions from other file """
from displaydb import *
from databaseinit import *
from connexion import *
from displayfavorite import *
#query used to check if filling is needed
CHECKIFEMPTY = '''SELECT * FROM Category'''
CURSOR.execute(CHECKIFEMPTY)
ALLTABLES = CURSOR.fetchall()
if ALLTABLES == []:
NEWDATABASE = DatabaseP()
#Already filled
NEWDATABASE.fill_table_category()
NEWDATABASE.fill_table_product()
MENUSCREEN = 1
while MENUSCREEN:
USER = Userintro()
USER.introduction()
USER.choices()
CHOICE = 0
while CHOICE not in (1, 2):
try:
CHOICE = int(input("Veuillez choisir entre requête 1 ou 2:\n"))
except ValueError:
print("Mauvaise commande, choisir 1 ou 2")
if CHOICE == 1:
# User wants to see the category list
DISPLAY = Displaydb()
DISPLAY.showcategory()
print("")
CATEG = -1
while CATEG < 0 or CATEG > 20:
# User choose which category
try:
CATEG = int(input("Sélectionnez la catégorie entre 1 et 20: \n"))
except ValueError:
print("Mauvaise commande, choisir entre 1 et 20\n\n")
DISPLAY.showproducts(CATEG)
# Put an error message if input different than product list
# loop with verification from database
WHICHPRODUCT = 0
while WHICHPRODUCT < (CATEG * 50) - 49 or WHICHPRODUCT > CATEG * 50:
try:
WHICHPRODUCT = int(
input("\nSélectionnez l'aliment à remplacer dans sa catégorie: \n")
)
print("")
except ValueError:
print("Mauvaise commande, choisir aliment\n\n")
print("-----------------------------------------------------------")
print("Votre sélection: \n")
DISPLAY.showproductdetails(WHICHPRODUCT)
print("\n-----------------------------------------------------------")
print("Produit alternatif: \n")
DISPLAY.showalternative(CATEG)
FAVORITE = input("\nSouhaitez-vous ajouter cet aliment à vos favoris ? O pour OUI, N si pas de substitut \n")
while FAVORITE not in ("N", "O"):
print("Mauvaise commande, tnapez O pour OUI, N pour NON\n")
FAVORITE = input(
"Souhaitez-vous ajouter cet aliment à vos favoris ? O/N \n"
)
if FAVORITE == "N":
BACKTOMENU = input("\nRevenir à l'accueil ?\n")
while BACKTOMENU not in ("N", "O"):
print("Mauvaise commande, tnapez O pour OUI, N pour NON\n")
BACKTOMENU = input("Revenir à l'accueil ? O ou N\n")
if BACKTOMENU == "N":
print("\nMerci d'avoir utilisé la plateforme ! A la prochaine !")
MENUSCREEN = 0
else:
print("-------------------------------------------------------------\n")
elif FAVORITE == "O":
DISPLAY.addalternative()
elif CHOICE == 2:
REQSUB = """SELECT * FROM Substitute"""
CURSOR.execute(REQSUB)
REQSUB = CURSOR.fetchall()
if REQSUB == []:
print("\nIl n'y a aucun produit alternatif. \n")
print("-----------------------------------------------")
BACKTOMENU2 = input("Revenir à l'accueil ?\n")
while BACKTOMENU2 not in ("O", "N"):
print("Mauvaise commande, tnapez O pour OUI, N pour NON\n")
BACKTOMENU2 = input("Revenir à l'accueil ? O ou N\n")
if BACKTOMENU2 == "N":
print("")
print("Merci d'avoir utilisé la plateforme ! A la prochaine !")
MENUSCREEN = 0
else:
print("-------------------------------------------------------------\n")
else:
DISPLAYSUB = Displaysub()
DISPLAYSUB.substitutelist()
BACKTOMENU2 = input("Revenir à l'accueil ?\n")
while BACKTOMENU2 not in ("O", "N"):
print("Mauvaise commande, tnapez O pour OUI, N pour NON\n")
BACKTOMENU2 = input("Revenir à l'accueil ? O ou N\n")
if BACKTOMENU2 == "N":
print("")
print("Merci d'avoir utilisé la plateforme ! A la prochaine !")
MENUSCREEN = 0
CONN.commit()
CONN.close()
|
5c2bfd87eae9ecbf66be718816136f425a11fd24 | NandanIITM/Pizzeria_Zearth_Sol | /Nandani_Garg/graph.py | 4,709 | 3.671875 | 4 | from collections import defaultdict
import numpy as np
# Class to represent a graph
class Graph:
def __init__(self, vertices):
'''
Args:
vertices : No of vertices of graph
'''
self.V = vertices # No. of vertices
self.graph = [] # default list to store graph
#Vertex adjacency list required for DFS traversal
self.adjList = defaultdict(list)
self.weights = {}
def addEdge(self, src, des, wt):
'''
function to add an edge to graph
Args:
src: source vertex
des: destination vertex
wt: weight of edge
'''
self.graph.append([src, des, wt])
def makeadjList(self, src, des, wt):
'''
function to make adjList of a graph
Args:
src: source vertex
des: destination vertex
wt: weight of edge
'''
self.adjList[src].append(des)
self.weights[(src, des)] = wt
def find(self, parent, i):
'''
function to find set of an element i
Args:
parent: parent of i
i: vertex i
'''
if parent[i] == i:
return i
return self.find(parent, parent[i])
def union(self, parent, rank, x, y):
'''
A function that does union of two sets of x and y
(uses union by rank)
'''
xparent = self.find(parent, x)
yparent = self.find(parent, y)
# Attach smaller rank tree under root of
# high rank tree (Union by Rank)
if rank[xparent] < rank[yparent]:
parent[xparent] = yparent
elif rank[xparent] > rank[yparent]:
parent[yparent] = xparent
# If ranks are same, then make one as root
# and increment its rank by one
else:
parent[yparent] = xparent
rank[xparent] += 1
def getKruskalMST(self):
'''
The main function to construct MST using Kruskal's algorithm
Returns: list of resultant MST
'''
result = [] # This will store the resultant MST
# An index variable, used for sorted edges
i = 0
# An index variable, used for result[]
e = 0
# Step 1: Sort all the edges in
# non-decreasing order of their
# weight. If we are not allowed to change the
# given graph, we can create a copy of graph
self.graph = sorted(self.graph,
key=lambda item: item[2])
parent = []
rank = []
# Create V subsets with single elements
for node in range(self.V):
parent.append(node)
rank.append(0)
# Number of edges to be taken is equal to V-1
while e < self.V - 1:
# Step 2: Pick the smallest edge and increment
# the index for next iteration
u, v, w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent, v)
# If including this edge does't
# cause cycle, include it in result
# and increment the indexof result
# for next edge
if x != y:
e = e + 1
result.append([u, v, w])
self.union(parent, rank, x, y)
# Else discard the edge
return result
def DFS(self, src, des, route_cost, wt, visited):
'''
Function to find cost of the path from src to des from a given MST
Args:
src : Source vertex
des: Destination vertex
route_cost: empty list representing cost of the path from src to des
wt: edge wt
visited: list containing visit status of each vertex in MST
Returns:
route_cost: list containing cost of the path from src to des
'''
visited[src] = 1
route_cost.append(wt)
# If current vertex is same as destination, then return route_cost
if src==des:
return route_cost
else:
# If current vertex is not destination
# Recur for all the vertices adjacent to this vertex
for i in self.adjList[src]:
if visited[i]==0:
r_cost = self.DFS(i, des, route_cost, self.weights[(src,i)], visited)
if r_cost:
return r_cost
# Remove current cost from route_cost and mark it as unvisited
route_cost.pop()
visited[src] = 0 |
2385bc762c835072e42a2e7bfdbbd66579f3ee84 | amssdias/python-school | /classes.py | 2,537 | 3.78125 | 4 | class Student:
id = 1
def __init__(self, name, course):
self.name = name
self.course = course
self.grades = []
self.id = Student.id
self.teachers = []
Student.id += 1
def __repr__(self):
return f"<Student({self.name}, {self.course})>"
def __str__(self):
return f"Id: {self.id} - {self.name}"
@property
def details(self):
return f"""Student \n
id: {self.id}
Name: {self.name}
Course: {self.course}
Grades: {self.grades}
Teachers: {[teacher.__str__() for teacher in self.teachers]}
"""
def add_grade(self, grade):
if not isinstance(grade, int) and not isinstance(grade, float):
raise ValueError('Grade must be a number!')
self.grades.append(grade)
def add_teacher(self, teacher):
if not isinstance(teacher, Teacher):
raise TypeError('Tried to add a `{teacher.__class__.__name__}` to student, but you can only add `Teacher` object. ')
if teacher in self.teachers:
return print('<<<<< Teacher already exists >>>>>')
self.teachers.append(teacher)
teacher.students.append(self)
print(f'Teacher added! to {self.name}.')
class Working_student(Student):
def __init__(self, name, course, job, pay):
super().__init__(name, course)
self.job = job
self.pay = pay
def __repr__(self):
return f"<Working_student({self.name}, {self.course}, {self.job}, {self.pay})>"
def __str__(self):
return f"Id: {self.id} - {self.name} (Working)"
@property
def details(self):
return f"""Working student \n
id: {self.id}
Name: {self.name}
Course: {self.course}
Grades: {self.grades}
Teachers: {[teacher.__str__() for teacher in self.teachers]}
Job: {self.job}
Pay(Yearly): {self.pay}
"""
class Teacher:
id = 1
def __init__(self, name, subject):
self.name = name
self.subject = subject
self.students = []
self.id = Teacher.id
Teacher.id += 1
def __repr__(self):
return f'<Teacher: {self.name} {self.subject}>'
def __str__(self):
return f"Id: {self.id} - {self.name}"
@property
def details(self):
return f"""Teacher \n
id: {self.id}
Name: {self.name}
Subject: {self.subject}
Students: {[student.__str__() for student in self.students]}
"""
|
00dfb0b8881dcccdd6f8ef059e0149956b6ed29b | ashleybaldock/tilecutter | /old/Script1.py | 1,693 | 3.796875 | 4 | import os
class pathObject:
"""Contains a path as an array of parts with some methods for analysing them"""
def __init__(self, pathstring):
"""Take a raw pathstring, normalise it and split it up into an array of parts"""
path = pathstring
norm_path = os.path.abspath(pathstring)
p = path
self.path_array = []
# Iterate through the user supplied path, splitting it into sections to store in the array
while os.path.split(p)[1] != "":
n = os.path.split(p)
self.path_array.append(path2(n[1],os.path.exists(p),len(p) - len(n[1])))
p = os.path.split(p)[0]
def __getitem__(self, key):
return self.path_array[key]
def blah(self):
return 1
def __str__(self):
a = ""
for k in range(len(self.path_array)):
a = a + "<[" + str(k) + "]\"" + self.path_array[k].text + "\"," + str(self.path_array[k].offset) + "," + str(self.path_array[k].length) + "," + str(self.path_array[k].exists) + ">, "
return a
class path2:
def __init__(self,text,exists,offset):
self.text = text # Textual content of this section of the path
self.length = len(text) # Length of this section of the path
self.offset = offset # Offset from start of string
self.exists = exists # Does this path section exist in the filesystem
def __len__(self):
return self.length
def __str__(self):
return self.text
def exists(self):
return self.exists
a = pathObject("old\\output/blah/output.dat")
print len(a[1])
print a
|
b30bc8c68c43339e91c03673aa98bd186fdee092 | wheatgrinder/donkey | /donkeycar/parts/pitft.py | 3,020 | 3.8125 | 4 | #!/usr/bin/env python3
'''
donkey part to work with adafruitt PiTFT 3.5" LCD display.
https://learn.adafruit.com/adafruit-pitft-3-dot-5-touch-screen-for-raspberry-pi/displaying-images
classes
display text on display
So far I have only been able to find a methond to write to the display using the frame buffer.
(without installing x anyway which is really not necessary)
display image
We will use opencv to create an image and display it on the screen
or we will display existing images on the screen
or we will show a short video on the screen. (animaated gifts etc)
image size 480x330
'''
import os
import sys
import cv2
import numpy as np
import re
import time
class display_text():
def __init__(self, port='/dev/fb1', text='text to show here'):
self.port = port
self.text = text
self.prev_text = ''
self.on = True
def update(self):
while self.on:
#self.text = str(text)
if not self.text == self.prev_text: # only update display if text is chnaged
# = os.popen('vcgencmd measure_temp').readline()
#print('display: '+ self.text)
my_img = create_blank_image()
my_img = add_text(my_img,self.text)
my_img = display_image(my_img)
self.prev_text = self.text
time.sleep(2)
def run_threaded(self,text):
self.text = str(text)
return self.prev_text
def create_blank_image():
blank_image = np.zeros((330,480,3), np.uint8)
#display_image_direct(blank_image)
return blank_image
def display_image_direct(img_in):
fbfd = open('/dev/fb1','w')
fbfd.write(img_in)
def add_text(img_arr,text='text here',size=1,color=(255,255,255),width=1):
img_arr = cv2.putText(img_arr, str(text), (20,100), cv2.FONT_HERSHEY_SIMPLEX,size, color,width, cv2.LINE_AA)
return img_arr
def open_image(img):
image = cv2.imread(img,0)
return image
def display_image(img_in):
#write the imgage then display...
image_file = cv2.imwrite(os.getcwd()+'/999.jpg', img_in)
img_handel = os.popen('sudo fbi -T 2 -d /dev/fb1 -noverbose -a ' + os.getcwd()+'/999.jpg > /dev/null 2>&1')
return img_handel
def main():
dir_path=os.getcwd()
# my code here
#result=os.popen('sudo fbi -T 2 -d /dev/fb1 -noverbose -a ' + dir_path + '/debug.jpg')
#display_image(dir_path + '/debug.gif')
my_img = create_blank_image()
#my_img = open_image(os.getcwd()+'/dog.jpg')
my_ip=os.popen('ip -4 addr show wlan0 | grep -oP \'(?<=inet\s)\d+(\.\d+){3}\'').readline()
my_ip = re.sub('\?', '',my_ip)
text = 'View on Web at: ' + my_ip
#text=os.popen('ip -4 addr show wlan0' ).readline()
my_img = add_text(my_img,text)
my_img = display_image(my_img)
return
if __name__ == "__main__":
main()
|
3df6b8f9818261092de3b9df2143871c121fc360 | leosartaj/thinkstats | /ch1.py | 1,463 | 3.5 | 4 | """
Chapter 1
"""
import sys
import survey
import thinkstats as ts
def live_births(table):
cou = 0
for rec in table.records:
if rec.outcome == 1:
cou += 1
return cou
def partition_births(table):
first = survey.Pregnancies()
other = survey.Pregnancies()
for rec in table.records:
if rec.outcome != 1:
continue
if rec.birthord == 1:
first.AddRecord(rec)
else:
other.AddRecord(rec)
return first, other
def average(table):
return (sum(rec.prglength for rec in table.records) /
float(len(table.records)))
def MeanVar(table):
return ts.MeanVar([rec.prglength for rec in table.records])
def summarize(table):
"""Prints summary statistics for first babies and others.
Returns:
tuple of Tables
"""
first, other = partition_births(table)
print 'Number of first babies', len(first.records)
print 'Number of others', len(other.records)
(mu1, st1), (mu2, st2) = MeanVar(first), MeanVar(other)
print 'Mean gestation in weeks:'
print 'First babies', mu1
print 'Others', mu2
print 'Difference in days', (mu1 - mu2) * 7.0
print 'STD of gestation in weeks:'
print 'First babies', st1
print 'Others', st2
print 'Difference in days', (st1 - st2) * 7.0
if __name__ == '__main__':
table = survey.Pregnancies()
table.ReadRecords(sys.argv[1])
summarize(table)
|
d47912664ed0a3d113d4d868ff9ecb16ae22e800 | akhilharihar/optimus | /optimus/optimus.py | 1,548 | 4 | 4 | class Optimus:
""" Arguments -
prime - Prime number lower than 2147483647
inverse - The inverse of prime such that (prime * inverse) & 2**31-1 == 1
xor - A large random integer lower than 2147483647"""
def __init__(self,prime, inverse, xor):
self.prime = int(prime)
self.inverse = int(inverse)
self.xor = int(xor)
self.max = int((2**31) - 1)
self.__validate(prime = self.prime,inverse = self.inverse,random = self.xor)
def encode(self,value):
"""
Accepts a integer value and returns obfuscated integer
"""
self.__check_arg(value)
return (int(value*self.prime) & self.max) ^ self.xor
def decode(self,value):
"""
Accepts obfuscated integer generated via encode method and returns the original integer
"""
self.__check_arg(value)
return ((value ^ self.xor)*self.inverse) & self.max
def __check_arg(self,value):
if not isinstance(value, int):
raise Exception('Argument should be an integer')
def __validate(self,**kwargs):
if kwargs['prime'] >= 2147483647:
raise Exception('The prime number should be less than 2147483647')
if ((kwargs['prime'] * kwargs['inverse']) & (2**31 -1)) != 1:
raise Exception('The inverse does not satisfy the condition "(prime * inverse) & 2**31-1 == 1"')
if kwargs['random'] >= 2147483647:
raise Exception('The random integer should be less than 2147483647') |
03e2d051ac1d3c734e5d4d2127a53ddf4187d7f9 | Asritha-Reddy/2TASK | /positivenumbers.py | 354 | 3.78125 | 4 | #positive numbers
list1=[12,-7,5,64,-14]
print('List1: ',list1)
print("Positive numbers in list1:")
for i in list1:
if i>=0:
print(i, end=", ")
print('\n')
list2=[12,14,-95,3]
print('List2: ',list2)
print("Positive numbers in list2:")
for j in list2:
if j<=0:
list2.remove(j)
print(list2)
|
da9b9a622dbe2abc55064bb484c030c88f2587c8 | Chearfly/- | /xiang_mu.py | 1,010 | 3.609375 | 4 | from tkinter import *
from tkinter import ttk
# from PIL import Image
#建立模块对像
root = Tk()
#设置窗口标题
root.title("人工智能项目")
#设置显示窗口的大小
root.geometry("700x500")
#设置窗口的宽度是不可变化的,但是他的长度是可变的
root.resizable(width = "true",height = "True")
# l = ttk.Label(root, text="欢迎来到人工智能的项目", bg = "blue", font= ("Arial",15), width=30,\
# height=5)
# l.grid(side = TOP)#设置项目的名称
# label=Label(root,text='Hello,GUI') #生成标签
# label.pack() #将标签添加到主窗口
# button1=Button(root,text='聊天',width=8,height = 2) #生成button1
# button1.pack(side=LEFT) #将button1添加到root主窗口
button2=ttk.Button(root,text='天气').grid(column=3, row=1, sticky=W)#列,行,
# button2.pack(side=LEFT)
# def my_out():
# root.quit
# button2=ttk.Button(root,text='退出',command = root.quit ,width = 8,height =2)
# button2.grid(side=BOTTOM)
root.mainloop()
|
9f9ca4275f16934ecb0dc4b331dd3ed3cfa150be | alex123012/Bioinf_HW | /fourth_HW/hw_5.py | 512 | 3.515625 | 4 | k = int(input('Enter k number: '))
# wget https://raw.githubusercontent.com/s-a-nersisyan/HSE_bioinformatics_2021/master/seminar4/homework/SARS-CoV-2.fasta
with open('SARS-CoV-2.fasta') as f:
f.readline().strip()
fasta = f.readline().strip()
hash_table = {}
for i in range(len(fasta) - k):
j = i + k
hash_table[fasta[i:j]] = hash_table.get(
fasta[i:j], []) + [(i, j)]
for i in hash_table:
print(i, end=': ')
for j in hash_table[i]:
print(j, end=', ')
print('\n')
|
511aac38c0edf5a12b6819d91b2bb20246581308 | alex123012/Bioinf_HW | /first_HW/first_hw_1.py | 1,231 | 3.71875 | 4 | def quadratic_equation(a, b, c, rnd=4):
"""Solving quadratic equations"""
if a == 0:
if b == 0:
if c == 0:
return 'any numbers'
else:
return 'No solutions'
else:
return -c / b
elif b == 0:
if c <= 0:
return c**0.5
else:
x1 = (-c)**0.5
x1 = complex(f'{round(x1.imag, rnd)}j') + round(x1.real, rnd)
return x1
dD = b**2 - 4 * a * c
if dD >= 0:
x1 = (-b + dD**0.5) / (2 * a)
if dD == 0:
return x1
x2 = (-b - dD**0.5) / (2 * a)
return x1, x2
else:
sqrtD = dD**0.5
x1 = (-b + sqrtD**0.5) / (2 * a)
x2 = (-b - sqrtD**0.5) / (2 * a)
x1 = complex(f'{round(x1.imag, rnd)}j') + round(x1.real, rnd)
x2 = complex(f'{round(x2.imag, rnd)}j') + round(x2.real, rnd)
# print(f'x1 = {x1}, x2 = {x2}')
return x1, x2
def main():
a = float(input('Enter coefficient A: '))
b = float(input('Enter coefficient B: '))
c = float(input('Enter coefficient C: '))
print('Quadratic roots are', quadratic_equation(a, b, c))
if __name__ == '__main__':
main()
|
27bdec3ef8bcff49ef41716fb4b2dd5fe0e39168 | isabella0428/Leetcode | /python/695.py | 1,383 | 3.5 | 4 | class Solution:
def maxAreaOfIsland(self, grid: 'List[List[int]]') -> 'int':
def search(row, col, grid, num):
grid[row][col] = 0
up = 0 if row == 0 else grid[row - 1][col]
if up:
num += search(row - 1, col, grid, 1)
down = 0 if row == m - 1 else grid[row + 1][col]
if down:
num += search(row + 1, col, grid, 1)
left = 0 if col == 0 else grid[row][col - 1]
if left:
num += search(row, col - 1, grid, 1)
right = 0 if col == n - 1 else grid[row][col + 1]
if right:
num += search(row, col + 1, grid, 1)
return num
m, n = len(grid), len(grid[0])
index = [[i,j] for i in range(m) for j in range(n) if grid[i][j] == 1]
max_term = 0
for loc in index:
row, col = loc[0], loc[1]
grid[row][col] = 0
max_term = max(max_term, search(row, col, grid[:], 1))
grid[row][col] = 1
return max_term
if __name__ == "__main__":
a = Solution()
print(a.maxAreaOfIsland(
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]))
|
1fa0995dcf2c1f58e42c542e5cdc31c02bad6be1 | isabella0428/Leetcode | /python/141.py | 1,132 | 3.953125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution1:
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
dict = {} # for address
while head:
if id(head) in dict: #address of head
return True # circle
dict[id(head)] = 1
head = head.next
return False
class Solution2:
#fast runner and slow runner
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return False
fast_runner = head
slow_runner = head.next
while slow_runner != fast_runner:
if not fast_runner:
return False
slow_runner = slow_runner.next
fast_runner = fast_runner.next
return True
|
cc17363e0989be93f817691c1b64e6968091eb8b | isabella0428/Leetcode | /python/81.py | 2,919 | 3.609375 | 4 | class MySolution:
pivot = 0
ans = False
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
def findPivot(start, end, nums):
if start == end:
return
mid = (start + end) >> 1
if nums[mid] < nums[mid - 1]:
self.pivot = mid
return
if nums[mid] > nums[mid + 1]:
self.pivot = mid + 1
return
if nums[mid] > nums[start]:
return findPivot(mid + 1, end, nums)
else:
return findPivot(start, mid - 1, nums)
def binarySearch(start, end, nums, target):
if start > end:
return
mid = start + end >> 1
if nums[mid] == target:
self.ans = True
return
if nums[mid] > target:
return binarySearch(0, mid - 1, nums, target)
else:
return binarySearch(mid + 1, end, nums, target)
def removeDuplicate(nums):
prev = nums[0]
if len(nums) == 1:
return
i = 1
while i < len(nums):
item = nums[i]
if item == prev:
nums.pop(i)
else:
prev = item
i += 1
if not nums:
return False
removeDuplicate(nums)
if nums[len(nums) - 1] <= nums[0]:
findPivot(0, len(nums) - 1,nums)
if target == nums[self.pivot]:
self.ans = True
elif nums[0] > target > nums[self.pivot]:
binarySearch(self.pivot + 1, len(nums) - 1, nums, target)
else:
binarySearch(0, self.pivot, nums, target)
else:
if target == nums[self.pivot]:
self.ans = True
elif target > nums[self.pivot]:
binarySearch(self.pivot + 1, len(nums) - 1, nums, target)
else:
binarySearch(0, self.pivot, nums, target)
return self.ans
class Solution:
def search(self, nums, target):
l, r = 0, len(nums) - 1
mid = l + r >> 1
while l <= r:
while l < mid and nums[l] == nums[mid]:
l += 1
if nums[mid] == target:
return True
if nums[l] <= nums[mid]:
if nums[l] <= target < nums[mid]:
r = mid - 1
else:
l = mid + 1
else:
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid - 1
mid = l + r >> 1
return False
if __name__ == "__main__":
a = Solution()
print(a.search([1, 3, 5], 1))
|
734b98d18f175109c48e16afeec4b64cdea4d0ac | isabella0428/Leetcode | /python/413.py | 890 | 3.671875 | 4 | class Solution1:
def numberOfArithmeticSlices(self, A: 'List[int]') -> 'int':
# dynamic programming
memo = [0 for i in range(len(A))]
if len(A) < 3:
return 0
sum = 0
for i in range(2, len(A)):
if A[i] - A[i - 1] == A[i - 1] - A[i - 2]:
memo[i] = memo[i - 1] + 1
sum += memo[i]
return sum
class Solution2:
def numberOfArithmeticSlices(self, A: 'List[int]') -> 'int':
# dp with constant spaces
dp = 0
if len(A) < 3:
return 0
sum = 0
for i in range(2, len(A)):
if A[i] - A[i - 1] == A[i - 1] - A[i - 2]:
dp += 1
sum += dp
else:
dp = 0
return sum
if __name__ == "__main__":
a = Solution2()
print(a.numberOfArithmeticSlices([1, 2, 3, 4]))
|
dac3c5e2a9f05e6ac34168e145ccb5b25f3d854f | isabella0428/Leetcode | /python/217.py | 794 | 3.515625 | 4 | class Solution1:
def containsDuplicate(self, nums) -> bool:
if len(nums) < 2:
return False
min_term = min(nums)
for i in range(len(nums)):
nums[i] += - min_term
max_term = max(nums)
stack = [-1 for i in range(max_term + 1)]
for item in nums:
if stack[item] != -1:
return True
else:
stack[item] = item
return False
class Solution2:
def containsDuplicate(self, nums) -> bool:
nums.sort()
prev = None
for item in nums:
if item == prev:
return True
prev = item
return False
if __name__ == "__main__":
a = Solution2()
print(a.containsDuplicate([-1200000000,-1200000005])) |
bc860577a7a9c6466fb1cf604dae49dcb08f89df | isabella0428/Leetcode | /python/86.py | 904 | 3.609375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def partition(self, head: 'ListNode', x: 'int') -> 'ListNode':
num = []
while head:
num.append(head.val)
head = head.next
loc = 0
for i in range(len(num)):
d = num[i]
if d < x:
num = num[:i] + num[i + 1:]
num.insert(loc, d)
loc += 1
node = prev = ListNode(0)
for item in num:
node.next = ListNode(item)
node = node.next
return prev.next
if __name__ == "__main__":
a = Solution()
node = head = ListNode(1)
val = [4, 3, 2, 5, 2]
for item in val:
node.next = ListNode(item)
node = node.next
node = a.partition(head, 3)
while node:
print(node.val)
node = node.next |
24ab2e2b98b68d9b357a49b1c9816d1ee5cc9ba2 | isabella0428/Leetcode | /python/22.py | 1,845 | 3.640625 | 4 | class Solution1:
def __init__(self):
self.result = []
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
bal = 0 # if bal < 0 and bal !=0 at last returns False
for i in s:
if i == '(':
bal += 1
else:
bal -= 1
if bal < 0:
return False
return bal == 0
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
strs = ""
self.Recursive(strs, 0, 0, n)
return self.result
def Recursive(self, strs, nums, cur, n):
if len(strs) == 2*n:
if self.isValid(strs):
self.result.append(strs)
return self.result
return
else:
for j in range(2):
if j == 0:
if cur - nums == n:
continue
self.Recursive(strs + '(', nums, cur + 1, n)
else:
if cur == 0:
continue
if nums == n:
continue
nums += 1
self.Recursive(strs + ')', nums, cur + 1, n)
class Solution2:
def generateParenthesis(self, n: 'int') -> 'List[str]':
def recursive(tmp, left, right):
nonlocal result
if left == right == 0:
result.append(tmp)
return
if 0 < left < n + 1:
recursive(tmp + '(', left - 1, right)
if right > left:
recursive(tmp + ')', left, right - 1)
result = []
recursive("", n, n)
return result
if __name__ == "__main__":
a = Solution2()
print(a.generateParenthesis(3)) |
f4ce8e0353739753200f9742ff5be3ca3a971651 | isabella0428/Leetcode | /python/5.py | 1,339 | 3.546875 | 4 | class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def expandAroundElement(index, s):
left = index - 1
right = index + 1
ans = str(s[index])
while left >= 0 and right < len(s):
if s[left] == s[right]:
ans = s[left] + ans + s[right]
left -= 1
right += 1
else:
break
return ans
def expandAroundSpace(index, s):
left = index - 1
right = index
ans = ''
while left >= 0 and right < len(s):
if s[left] == s[right]:
ans = s[left] + ans + s[right]
left -= 1
right += 1
else:
break
return ans
ans = ''
for i in range(len(s)):
center = expandAroundElement(i, s)
space = expandAroundSpace(i, s)
if len(center) > len(ans):
ans = center
if len(space) > len(ans):
ans = space
return ans
if __name__ == "__main__":
a = Solution()
print(a.longestPalindrome("babad")) |
eae3eb282eb9ea947d758ea1c59a3c4e0b2d0a85 | isabella0428/Leetcode | /python/17.py | 2,002 | 3.546875 | 4 | class Solution1:
def __init__(self):
self.result = []
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
strs = []
s = []
dict = {2:['a','b','c'], 3:['d','e','f'], 4:['g','h','i'], 5:['j','k','l'],
6:['m','n','o'], 7:['p','q','r','s'], 8:['t','u','v'], 9:['w','x','y','z']}
for i in digits:
s.append(dict[int(i)])
length = len(s)
self.Recursive(s, 0, length)
return self.result
def Recursive(self, s, i, length, ans=""):
if i == length:
self.result.append(ans)
else:
for p in s[i]:
ans += p
self.Recursive(s, i + 1, length, ans)
ans = ans[:-1]
class Solution2:
def __init__(self):
self.result = []
def digitLetter(self, digit):
if digit == '1':
return []
elif digit == '2':
return ['a', 'b', 'c']
elif digit == '3':
return ['d', 'e', 'f']
elif digit == '4':
return ['g', 'h', 'i']
elif digit == '5':
return ['j', 'k', 'l']
elif digit == '6':
return ['m', 'n', 'o']
elif digit == '7':
return ['p', 'q', 'r', 's']
elif digit == '8':
return ['t', 'u', 'v']
else:
return ['w', 'x', 'y', 'z']
def recursive(self, tmp, digits):
if not digits:
self.result.append(tmp)
return
for char in self.digitLetter(digits[0]):
self.recursive(tmp + char, digits[1:])
def letterCombinations(self, digits: 'str') -> 'List[str]':
"""
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
self.recursive("", digits)
return self.result
if __name__ == "__main__":
a = Solution2()
print(a.letterCombinations("23"))
|
bfc6f9541b8b93b9eee437c24594552e1bc9da45 | isabella0428/Leetcode | /python/34.py | 1,804 | 3.6875 | 4 | class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def binarySearch(nums, start, end, ans, target):
if start > end:
return
if nums[start] > target or nums[end] < target:
return
medium = int((start + end) / 2)
if nums[medium] < target:
start = medium + 1
return binarySearch(nums, start, end, ans, target)
elif nums[medium] > target:
end = medium - 1
return binarySearch(nums, start, end, ans, target)
else:
if medium < ans[0]:
ans[0] = medium
if medium > ans[1]:
ans[1] = medium
binarySearch(nums, start, medium - 1, ans,target)
binarySearch(nums, medium + 1, end, ans, target)
if not nums:
return [-1, -1]
ans = [float('inf'), -1]
start, end = 0, len(nums) - 1
medium = int((start + end) / 2)
if nums[medium] < target:
start = medium + 1
binarySearch(nums, start, end, ans, target)
elif nums[medium] > target:
end = medium - 1
binarySearch(nums, start, end, ans, target)
else:
if medium < ans[0]:
ans[0] = medium
if medium > ans[1]:
ans[1] = medium
binarySearch(nums, start, medium - 1, ans, target)
binarySearch(nums, medium + 1, end, ans, target)
if ans == [float('inf'), -1]:
return [-1, -1]
return ans
if __name__ == "__main__":
a = Solution()
print(a.searchRange([1], 1)) |
eb7bdb086ac0f1932e9b66811db53f1d8957818d | isabella0428/Leetcode | /python/847.py | 743 | 3.515625 | 4 | class Solution:
def shortestPathLength(self, graph):
# use bits to represent states
N = len(graph)
dp = [[float('inf') for i in range(N)] for j in range(1 << N)]
q = []
for i in range(N):
dp[1 << i][i] = 0
q.append([1 << i, i])
while q:
state, node = q.pop(0)
step = dp[state][node]
for k in graph[node]:
new_state = state | (1 << k)
if dp[new_state][k] == float('inf'):
dp[new_state][k] = step + 1
q.append([new_state, k])
return min(dp[-1])
if __name__ == "__main__":
a = Solution()
print(a.shortestPathLength([[1, 2, 3],[0], [0], [0]])) |
c59b550736aeef6603de8b7406839051f495e7b6 | isabella0428/Leetcode | /python/35.py | 1,106 | 3.875 | 4 | class Solution1(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for i in range(len(nums)):
if target == nums[i]:
return i
if target < nums[i]:
return i
return i + 1
class Solution2:
def searchInsert(self, nums, target) -> int:
def binarySearch(l, r, nums, target):
mid = l + r >> 1
if nums[mid] == target:
return mid
elif nums[mid] > target:
r = mid - 1
if nums[r] < target:
return r + 1
else:
l = mid + 1
if nums[l] > target:
return l
return binarySearch(l, r, nums, target)
if target > nums[-1]:
return len(nums)
if target < nums[0]:
return 0
return binarySearch(0, len(nums) - 1, nums, target)
if __name__ == "__main__":
a = Solution2()
print(a.searchInsert([1, 3, 5, 6], 7)) |
9ebdf9b2d26b2f720896b0281362f4f08318955f | isabella0428/Leetcode | /python/680.py | 512 | 3.6875 | 4 | class Solution:
#greedy
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
def isPali(s, i, j):
return all(s[k] == s[j - k + i] for k in range(i, j))
for i in range(len(s)):
if s[i] != s[~i]: # ~i = -(i + 1)
j = len(s) - 1 - i
return isPali(s, i + 1, j) or isPali(s, i, j - 1)
return True
if __name__ == "__main__":
a = Solution()
print(a.validPalindrome('abc')) |
667e87890af57db213b90fa41a5027e46a404cfe | OliverOC/countryScratchMap | /functionLib.py | 6,634 | 4 | 4 | import json
import os
import matplotlib.pyplot as plt
import pandas as pd
from collections import defaultdict
def if_no_json_create_new(file_name):
"""
This function checks whether a JSON file exists under the given file name.
If no JSON file exists, a new one is created.
:param file_name: Name of the JSON file to be created.
"""
if os.path.exists(str(file_name)+'.json'):
pass
else:
empty_dict = {}
with open((str(file_name))+'.json', 'w') as f:
json.dump(empty_dict, f)
def add_countries(file_name):
"""
This function adds a country and the year visited into the JSON file through user input.
:param file_name: Name of the JSON file to add a country and year to.
"""
add_more = True
while add_more:
with open((str(file_name))+'.json', 'r') as f:
countries = json.load(f)
accepted_country = False
while not accepted_country:
def check_country(country_to_check):
"""
This function checks whether the inputted country is a real country by comparing to a JSON file
containing all the allowed countries in the world.
:param country_to_check: The name of the country to check
:return: Returns True or False
"""
with open('country_list.json', 'r') as f2:
countries_json = json.load(f2)
if country_to_check.title() in countries_json.keys():
accepted = True
return accepted
else:
accepted = False
print('Error: country not recognised. '
'This might be due to a spelling error.')
see_list = input('Press ''L'' to see a list of all countries, or press ''X'' to continue...')
if see_list.lower() == 'l':
string_countries_list = [str(x) for x in sorted(countries_json.keys())]
print(string_countries_list)
elif see_list.lower() == 'x':
pass
return accepted
input_country = input('What country did you visit?:')
accepted_country = check_country(input_country)
input_year = input('What year did you visit? (if multiple visits include list, e.g. 2010, 2016):')
split_input_years = input_year.split(',')
split_input_years_strip = [int(i.strip()) for i in split_input_years]
if input_country.title() in countries.keys():
for year in range(len(split_input_years_strip)):
countries[input_country.title()].append(split_input_years_strip[year])
else:
countries[input_country.title()] = split_input_years_strip
with open((str(file_name)+'.json'), 'w') as f:
json.dump(countries, f)
add_again = input("Would you like to add another country?(Y or N):")
if add_again.lower() == 'y':
add_more = True
elif add_again.lower() == 'n':
add_more = False
def rearrange_dict_by_country(json_file_name, new_file_name):
"""
This function creates a new JSON file with the year as the key and the countries as the values.
:param json_file_name: The name of the file containing the country: years information
:param new_file_name: The new JSON file to be created in the format of year: countries
"""
with open((str(json_file_name)+'.json'), 'r') as f:
dictionary = json.load(f)
dictionary_values = list(dictionary.values())
dictionary_keys = list(dictionary.keys())
dictionary_keys_new_list = []
dictionary_values_new_list = []
for i in range(len(dictionary_keys)):
if len(dictionary_values[i]) > 1:
for ii in range(len(dictionary_values[i])):
dictionary_keys_new_list.append(dictionary_values[i][ii])
dictionary_values_new_list.append(dictionary_keys[i]+str(ii+1))
else:
dictionary_keys_new_list.append(dictionary_values[i][0])
dictionary_values_new_list.append(dictionary_keys[i])
new_dictionary = dict(zip(dictionary_values_new_list, dictionary_keys_new_list))
new_dictionary_inverted = defaultdict(list)
{new_dictionary_inverted[v].append(k) for k, v in new_dictionary.items()}
with open((str(new_file_name)+'.json'), 'w') as f2:
json.dump(new_dictionary_inverted, f2)
def extract_country_by_year(file_name, year, include_none=False):
"""
This function allows the user to extract all the countries visited in a given year or a range of years.
:param file_name: The name of the JSON file containing the information in the year: countries format
:param year: year or range of years to be extracted
:param include_none: the returned list will append an empty string for all years where no country was visited
:return: A list where each element is a list of countries visited in the years corresponding to the input years
"""
with open(str(file_name)+'.json') as f:
countries_by_year = json.load(f)
if type(year) == int:
if str(year) in list(countries_by_year.keys()):
output = countries_by_year[str(year)]
return output
else:
print('no countries visited in ' + str(year))
elif type(year) == list:
output_countries = []
for i in range(len(year)):
if str(year[i]) in list(countries_by_year.keys()):
output_countries.append(countries_by_year[str(year[i])])
else:
if include_none:
output_countries.append('')
else:
print('no countries visited in ' + str(year[i]))
return output_countries
def plot_by_year(years, countries):
"""
This function plots the number of countries visited per year.
:param years: A list of years of interest
:param countries: A list of the corresponding countries visited each year
"""
country_number = []
for i in range(len(countries)):
if countries[i] == "":
country_number.append(0)
else:
country_number.append(len(countries[i]))
plt.bar(years, country_number, color='green', width=1, align='center')
plt.xlabel('Year', labelpad=20, fontsize=20)
plt.xticks(years, rotation=90)
plt.ylabel('Countries Visited', labelpad=20, fontsize=20)
plt.yticks(range(0, max(country_number) + 2))
plt.show()
|
d089ecb536c7d01e7387f82dbe93da65da98358c | yogabull/TalkPython | /WKUP/loop.py | 925 | 4.25 | 4 | # This file is for working through code snippets.
'''
while True:
print('enter your name:')
name = input()
if name == 'your name':
break
print('thank you')
'''
"""
name = ''
while name != 'your name':
name = input('Enter your name: ')
if name == 'your name':
print('thank you')
"""
import random
print('-----------------')
print(' Number Game')
print('-----------------')
number = random.randint(0, 100)
guess = ''
while guess != number:
guess = int(input('Guess a number between 1 and 100: '))
if guess > number:
print('Too high')
print(number)
if guess < number:
print('Too low')
print(number)
if guess == number:
print('Correct')
print(number)
print('---------------------')
print(' f-strings')
print('---------------------')
name = input('Please enter your name: ')
print(f'Hi {name}, it is nice to meet you.')
|
8837287f4ef533b32c594b35c8b432216cb8c628 | yogabull/TalkPython | /ex3_birthday_program/ex3_program_birthday.py | 1,221 | 4.28125 | 4 | """This is a birthday app exercise."""
import datetime
def main():
print_header()
bday = get_user_birthday()
now = datetime.date.today()
td = compute_user_birthday(bday, now)
print_birthday_info(td)
def print_header():
print('-----------------------------')
print(' Birthday App')
print('-----------------------------')
print()
def get_user_birthday():
print("When is your birthday?")
year = int(input('Year [YYYY]: '))
month = int(input('Month [MM]: '))
day = int(input('Day [DD]: '))
bday = datetime.date(year, month, day)
return bday
def compute_user_birthday(original_date, today):
# this_year = datetime.date(
# year=today.year, month=original_date.month, day=original_date.day)
""" Refactored below."""
this_year = datetime.date(
today.year, original_date.month, original_date.day)
td = this_year - today
return td.days
def print_birthday_info(days):
if days > 0:
print(f"Your birthday is in {days} days.")
elif days < 0:
print(f"Your birtdahy was {-days} days ago.")
else:
print("Happy Birthday!")
print()
print('-----------------------------')
main()
|
ce930feff941e3e78f9629851ce0c8cc08f8106b | yogabull/TalkPython | /WKUP/fStringNotes.py | 694 | 4.3125 | 4 | #fString exercise from link at bottom
table = {'John' : 1234, 'Elle' : 4321, 'Corbin' : 5678}
for name, number in table.items():
print(f'{name:10} --> {number:10d}')
# John --> 1234
# Elle --> 4321
# Corbin --> 5678
'''
NOTE: the '10' in {name:10} means make the name variable occupy at least 10 spaces.
This is useful for making columns align.
'''
'''
f-Strings:
Another method to output varibles within in a string.
Formatted String Literals
This reads easily.
year = 2019
month = 'June'
f'It ends {month} {year}.'
>>> It ends June 2019.
https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings
'''
|
77ddf7f2e6d19a20ca71862d7507a72ed1cde4bd | rohitgang/MATH471 | /rank_matrices.py | 1,677 | 3.75 | 4 | """
(Ranks of random matrices) Generate square (n x n) matrices with random entries (for instance Gaussian or uniform
random entries). For each n belonging to {10,20,30,40,50}, run 100 trials and report the statistics of the rank of
the matrix generated for each trial (mean, median, min, max). What do you notice? Please turn in the code you used to
produce the data.
"""
import numpy as np
def answer(n):
# Dictionary to store the statistics of the matrices
stats = {'rank': list(),
'mean': list(),
'median': list(),
'min': list(),
'max': list()}
for i in range(100):
# random generated square matrix
matrix = np.random.rand(n, n)
# appending the required statistics to the dictionary
stats['rank'].append(np.linalg.matrix_rank(matrix))
stats['mean'].append(np.mean(matrix))
stats['median'].append(np.median(matrix))
stats['min'].append(matrix.min())
stats['max'].append(matrix.max())
# returning a tuple of the mean value of required statistics
return (np.mean(stats['rank']), np.mean(stats['mean']),
np.mean(stats['median']), np.mean(stats['min']),
np.mean(stats['max'])), stats
# different dimensions for the matrices
set_of_ns = [10,20,30,40,50]
# dictionary to append statistics for each n
answer_dict = {n : None for n in set_of_ns}
for n in set_of_ns:
avg_stats, stats = answer(n)
intermediate_dict = {'avg': avg_stats,
'stats': stats}
answer_dict[n] = intermediate_dict
for key, val in answer_dict.items():
avg = val['avg']
print('key :', key, '-- ', avg)
|
8a07ac0097bdfa92665a85be956b5dfc40b217dc | gregor42/python-for-the-stoopid | /diction.py | 733 | 3.640625 | 4 | #!/usr/local/bin/python
#
# diction.py - playing with dictionaries
#
import pri
filename = 'templ8.py'
# Say hello to the Nice People
pri.ntc(filename + " : Start.")
pri.bar()
D = {'a': 1, 'b': 2, 'c': 3}
pri.ntc(D)
pri.bar()
D['e']=42
pri.ntc(D)
pri.bar()
#underfined value will break
#print D['f']
pri.ntc('f' in D)
pri.bar()
if not 'f' in D:
pri.ntc("f is missing")
pri.ntc("no really")
pri.bar()
pri.ntc(D.get('x',-1))
pri.bar()
Ks = list(D.keys())
pri.ntc(Ks)
pri.bar()
Ks.sort()
pri.ntc(Ks)
pri.bar()
for key in sorted(D):
print(key, '=>', D[key])
pri.bar()
for c in 'spam spam spam':
print(c.upper())
pri.bar()
x = 4
while x > 0:
print('spam! ' * x)
x -= 1
pri.bar()
pri.ntc("Done.")
|
3a3bf87bc7aeede084d8df8e78331110b8f3e441 | zumioo/tweet | /remove.py | 1,203 | 3.671875 | 4 | """
使うときはコメントアウト外してね
import tweepy
import calendar
import random
import time
def main():
consumer_key = 'XXXXX'
consumer_secret = 'XXXXX'
access_token_key = 'XXXXX'
access_token_secret = 'XXXXX'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token_key, access_token_secret)
api = tweepy.API(auth)
my_user_id = api.me().id_str #自分のidを取得
follower_list = list(api.followers_ids(my_user_id))#自分のフォロワーを取得
friend_list = list(api.friends_ids(my_user_id))#自分がフォローしている人を取得
remove(api,follower_list,friend_list)
#フォロバしてくれない人のフォローを外す
def remove(api,follower_list,friend_list):
result = list(set(friend_list) - set(follower_list))#差分を計算
if not result == []:
for un_follower in result:
api.destroy_friendship(un_follower)
print(api.get_user(un_follower).screen_name + 'のフォローを外しました。')
else:
print("おじいさんをフォローバックしていないフォロワーはいません。")
main() """
|
f08ec1974b033d5bd56b64b764f23541a811acbc | febin72/LearnPython | /oddoreven.py | 149 | 4.28125 | 4 | '''
Find even or odd
'''
import math
print ('enter the number')
x= int(input())
if (x%2==0):
print ('the number is even')
else:
print('odd')
|
2550c545f6f0f73faef10670b3dde6f2235b21a1 | febin72/LearnPython | /strings.py | 509 | 3.9375 | 4 | '''
play with strings
'''
import string
print ('enter a string')
a = str(input())
print ('ented one more string')
one_more_string = str(input())
print ('entered strings length is ' , len(a) , len(one_more_string))
#print (a[2:6])
#print ('The length of the string entered is' ,len(a+one_more_string))
newstring = a + one_more_string
print ('new string is' , newstring)
split_line=(newstring.split('m'))
print (split_line)
print (split_line[1])
#while split_line != 'n':
#print ('febin')
#break
|
c7fc3ced3296f7e181ba9714534800b59d20dd53 | thevirajshelke/python-programs | /Basics/subtraction.py | 586 | 4.25 | 4 | # without user input
# using three variables
a = 20
b = 10
c = a - b
print "The subtraction of the numbers is", c
# using 2 variables
a = 20
b = 10
print "The subtraction of the numbers is", a - b
# with user input
# using three variables
a = int(input("Enter first number "))
b = int(input("Enter first number "))
c = a - b
print "The subtraction of the numbers is", c
# using 2 variables
# int() - will convert the input into numbers if string is passed!
a = int(input("Enter first number "))
b = int(input("Enter first number "))
print "The subtraction of the numbers is", a - b
|
ef45e2377ab4276345644789a17abdd20da69aca | johnehunt/computationalthinking | /week4/tax_calculator.py | 799 | 4.3125 | 4 | # Program to calculate tax band
print('Start')
# Set up 'constants' to be used
BASIC_RATE_THRESHOLD = 12500
HIGHER_RATE_THRESHOLD = 50000
ADDITIONAL_RATE_THRESHOLD = 150000
# Get user input and a number
income_string = input('Please input your income: ')
if income_string.isnumeric():
annual_income = int(income_string)
# Determine tax band
if annual_income > ADDITIONAL_RATE_THRESHOLD:
print('Calculating tax ...')
print('Your highest tax rate is 45%')
elif annual_income > HIGHER_RATE_THRESHOLD:
print('Your highest tax rate is 40%')
elif annual_income > BASIC_RATE_THRESHOLD:
print('Your highest tax rate is 20%')
else:
print('You are not liable for income tax')
else:
print('Input must be a positive integer')
print('Done')
|
fecc9d49fc1df51d7b793fb052c8defcbc86300e | johnehunt/computationalthinking | /week1/exammarks/main3.py | 633 | 3.9375 | 4 | # Alternative solution using compound conditional statement
component_a_mark = int(input('Please enter your mark for Component A: '))
coursework_mark = int(input('Please enter your mark for Component B: '))
# Calculating mark by adding the marks together and dividing by 2
module_mark = (component_a_mark + coursework_mark) / 2
print('Your mark is', module_mark, 'Calculating your result')
# Uses compound boolean proposition
if coursework_mark < 35 and component_a_mark < 35:
print('You have not passed the module')
elif module_mark < 40:
print('You have failed the module')
else:
print('You have passed the module') |
8d7ca111c403010de98909a1850ae5f7a1d54b2b | johnehunt/computationalthinking | /number_guess_game/number_guess_game_v2.py | 1,262 | 4.34375 | 4 | import random
# Print the Welcome Banner
print('===========================================')
print(' Welcome to the Number Guess Game')
print(' ', '-' * 40)
print("""
The Computer will ask you to guess a number between 1 and 10.
""")
print('===========================================')
# Initialise the number to be guessed
number_to_guess = random.randint(1, 10)
# Set up flag to indicate if one game is over
finished_current_game = False
# Obtain their initial guess and loop to see if they guessed correctly
while not finished_current_game:
guess = None
# Make sure input is a positive integer
input_ok = False
while not input_ok:
input_string = input('Please guess a number between 1 and 10: ')
if input_string.isdigit():
guess = int(input_string)
input_ok = True
else:
print('Input must be a positive integer')
# Check to see if the guess is above, below or the correct number
if guess < number_to_guess:
print('Your guess was lower than the number')
elif guess > number_to_guess:
print('Your guess was higher than the number')
else:
print('Well done you won!')
finished_current_game = True
print('Game Over')
|
0f25b7552ca48fbdc04ee31bd873d899ffae26c6 | johnehunt/computationalthinking | /week4/forsample.py | 813 | 4.34375 | 4 | # Loop over a set of values in a range
print('Print out values in a range')
for i in range(0, 10):
print(i, ' ', end='')
print()
print('Done')
print('-' * 25)
# Now use values in a range but increment by 2
print('Print out values in a range with an increment of 2')
for i in range(0, 10, 2):
print(i, ' ', end='')
print()
print('Done')
print('-' * 25)
# This illustrates the use of a break statement
num = int(input('Enter a number: '))
for i in range(0, 6):
if i == num:
break
print(i, ' ', end='')
print('Done')
print('-' * 25)
# This illustrates the use of a continue statement
for i in range(0, 10):
print(i, ' ', end='')
if i % 2 == 1: # Determine if this is an odd number
continue
print('its an even number')
print('we love even numbers')
print('Done')
|
0e6908ec30831e4ea0218e8af6b0605dae3cef78 | johnehunt/computationalthinking | /week4/ranges.py | 171 | 4.1875 | 4 | for i in range(1, 10):
print(i, end=', ')
print()
for i in range(0, 10, 2):
print(i, ' ', end='')
print()
for i in range(10, 1, -2):
print(i, ' ', end='')
|
3a3069f8e96bf2bdcf973dececffb43dc0ca59c4 | johnehunt/computationalthinking | /week2/numbers.py | 1,867 | 3.734375 | 4 | x = 1
print(x)
print(type(x))
x = 10000000000000000000000000000000000000000000000000000000000000001
print(x)
print(type(x))
home = 10
away = 15
print(home + away)
print(type(home + away))
print(10 * 4)
print(type(10 * 4))
goals_for = 10
goals_against = 7
print(goals_for - goals_against)
print(type(goals_for - goals_against))
print(100 / 20)
print(type(100 / 20))
res1 = 3 / 2
print(res1)
print(type(res1))
print('-' * 10)
res1 = 3 // 2
print(res1)
print(type(res1))
a = 5
b = 3
print(a ** b)
print('Modulus division 4 % 2:', 4 % 2)
print('Modulus division 3 % 2:', 3 % 2)
print('True division 3/2:', 3 / 2)
print('True division -3/2:', -3 / 2)
print('Integer division 3//2:', 3 // 2)
print('Integer division -3//2:', -3 // 2)
int_value = 1
string_value = '1.5'
float_value = float(int_value)
print('int value as a float:', float_value)
print(type(float_value))
float_value = float(string_value)
print('string value as a float:', float_value)
print(type(float_value))
print('*' * 10)
age = int(input('Please enter your age: '))
print(type(age))
print(age)
print('*' * 10)
exchange_rate = float(input("Please enter the exchange rate to use: "))
print(exchange_rate)
print(type(exchange_rate))
print(float(1))
print(int(exchange_rate))
print(2.3 + 1.5)
print(1.5 / 2.3)
print(1.5 * 2.3)
print(2.3 - 1.5)
print(1.5 - 2.3)
print(12.0 // 3.0)
i = 3 * 0.1
print(i)
print('+' * 10)
f = 3.2e4 + 0.00002e-6
formatString = "%16.20g"
print(formatString % f)
print(type(f))
c1 = 1j
c2 = 2j
print('c1:', c1, ', c2:', c2)
print(type(c1))
print(c1.real)
print(c1.imag)
c3 = c1 * c2
print(c3)
print('=' * 10)
all_ok = True
print(all_ok)
all_ok = False
print(all_ok)
print(type(all_ok))
print(int(True))
print(int(False))
print(bool(1))
print(bool(0))
status = bool(input('OK to proceed: '))
print(status)
print(type(status))
x = 0
x += 1
print('x =', x)
|
2acb0005b760b130fc4c553b8f9595c91b828c0e | tainagdcoleman/sharkid | /helpers.py | 2,892 | 4.125 | 4 | from typing import Tuple, List, Dict, TypeVar, Union
import scipy.ndimage
import numpy as np
import math
Num = TypeVar('Num', float, int)
Point = Tuple[Num, Num]
def angle(point: Point,
point0: Point,
point1: Point) -> float:
"""Calculates angles between three points
Args:
point: midpoint
point0: first endpoint
point1: second endpoint
Returns:
angle between three points in radians
"""
a = (point[0] - point0[0], point[1] - point0[1])
b = (point[0] - point1[0], point[1] - point1[1])
adotb = (a[0] * b[0] + a[1] * b[1])
return math.acos(adotb / (magnitude(a) * magnitude(b)))
def find_angles(points: List[Point])-> List[float]:
"""Finds angles between all points in sequence of points
Args:
points: sequential list of points
Returns:
angles in radians
"""
return angle(points[len(points) // 2], points[0], points[-1])
def magnitude(point: Point) -> float:
"""Finds the magnitude of a point, as if it were a vector originating at 0, 0
Args:
point: Point (x, y)
Returns:
magnitude of point
"""
return math.sqrt(point[0]**2 + point[1]**2)
def dist_to_line(start: Point, end: Point, *points: Point, signed=False) -> Union[float, List[float]]:
"""Finds the distance between points and a line given by two points
Args:
start: first point for line
end: second point for line
points: points to find distance of.
Returns:
A single distance if only one point is provided, otherwise a list of distances.
"""
start_x, start_y = start
end_x, end_y = end
dy = end_y - start_y
dx = end_x - start_x
m_dif = end_x*start_y - end_y*start_x
denom = math.sqrt(dy**2 + dx**2)
_dist = lambda point: (dy*point[0] - dx*point[1] + m_dif) / denom
dist = _dist if signed else lambda point: abs(_dist(point))
if len(points) == 1:
return dist(points[0])
else:
return list(map(dist, points))
def gaussian_filter(points:List[Point], sigma=0.3):
return scipy.ndimage.gaussian_filter(np.asarray(points), sigma)
def distance(point1: Point, point2: Point):
x1, y1 = point1
x2, y2 = point2
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def coord_transform(points: List[Tuple[int, int]])-> float:
start_x, start_y = points[0]
end_x, end_y = points[-1]
inner = points[1:-1]
perp_point_x = start_x - (end_y - start_y)
perp_point_y = start_y + (end_x - start_x)
ys = dist_to_line((start_x, start_y), (end_x, end_y), *inner, signed=True)
xs = dist_to_line((start_x, start_y), (perp_point_x, perp_point_y), *inner, signed=True)
return xs, ys
def remove_decreasing(xs, ys):
maxx = xs[0]
for x, y in zip(xs, ys):
if x > maxx:
yield x, y
maxx = x
|
33a375ed2fb0b278b1304dffb4815c4cfdf67982 | rose60730422/writingTest | /writingTest.py | 696 | 3.84375 | 4 |
def reverseString(t):
reverseString = t[::-1]
return reverseString
def reverseWords(s):
s = s.split(" ")
for index, word in enumerate(s) :
s[index] = reverseString(word)
r = ' '.join(s)
return r
def countingFactor(n):
cnt = 0
for i in range(n):
if ((i+1) % 3 == 0) and ((i+1) % 5 == 0):
cnt = cnt + 1
elif ((i+1) % 3 != 0) and ((i+1) % 5 != 0):
cnt = cnt + 1
return cnt
text_A = input('Please enter your string : ')
print(reverseString(text_A))
text_B = input('Please enter your sentence : ')
print(reverseWords(text_B))
number = input('Please enter your number : ')
print(countingFactor(int(number)))
|
0438c1b364eae318c527df99ea6b1959489e0fce | lakshmanboddoju/Automate_the_boring_stuff_with_python | /11/31-hello_txt_read.py | 867 | 3.734375 | 4 | #! python3
import shelve
# Read Operation
helloFile = open('C:\\Users\\lakshman\\Desktop\\hello.txt')
#helloFileContent = helloFile.read()
#print(helloFileContent)
print(helloFile.readlines())
helloFile.close()
# Write Operation
helloFile2 = open('C:\\Users\\lakshman\\Desktop\\hello2.txt', 'w')
helloFile2.write('YOLO!\n')
helloFile2.write('You Rock!\n')
helloFile2.close()
# Append Operation
helloFile3 = open('C:\\Users\\lakshman\\Desktop\\hello3.txt', 'a')
helloFile3.write('YOLO!\n')
helloFile3.write('You Rock!\n')
helloFile3.close()
# Shelve File | Persistent memory for complex stuff to store like lists, etc.
shelfFile = shelve.open('mydata')
shelfFile['cats'] = ['Zophie', 'Pooka', 'Simon', 'Fat-tail', 'Cleo']
shelfFile.close()
shelfFile = shelve.open('mydata')
print(shelfFile['cats'])
shelfFile.close()
|
8079ac6be8a7cbfbda9230c0fffeb89170e04f8d | AshWije/Neural-Networks-In-Python | /WithPyTorch/ImageNet_ResNetX_CNN.py | 9,451 | 3.53125 | 4 | ################################################################################
#
# FILE
#
# ImageNet_ResNetX_CNN.py
#
# DESCRIPTION
#
# Creates a convolutional neural network model in PyTorch designed for
# ImageNet modified to 100 classes and downsampled to 3x56x56 sized images
# via resizing and cropping. The model is based on the RegNetX image
# classifier and modified slightly to fit the modified data.
#
# Two python classes are defined in this file:
# 1. XBlock: The building block used in the model. At stride=1, this block
# is a standard building block. At stride=2, this block is a
# downsampling building block.
# 2. Model: Creates the convolutional neural network model using the
# building block class XBlock.
#
# There are six distinct layers in the model: the stem, encoder level 0,
# encoder level 1, encoder level 2, encoder level 3, and the decoder. The
# layer details are shown below:
# 1. Stem:
# Conv(3x3,s=1)
#
# 2. Encoder level 0:
# XBlock(s=1)
#
# 3. Encoder level 1:
# XBlock(s=2)
#
# 4. Encoder level 2:
# XBlock(s=2)
# XBlock(s=1)
# XBlock(s=1)
# XBlock(s=1)
#
# 5. Encoder level 3:
# XBlock(s=2)
# XBlock(s=1)
# XBlock(s=1)
# XBlock(s=1)
# XBlock(s=1)
# XBlock(s=1)
# XBlock(s=1)
#
# 6. Decoder:
# AvgPool
# Flatten
# Linear
#
# After being trained for 100 epochs with Adam as the optimizer and a
# learning rate schedule of linear warmup followed by cosine decay, the final
# accuracy achieved is 70.93%. (Note: training code is not provided in this
# file).
#
################################################################################
################################################################################
#
# IMPORT
#
################################################################################
# torch
import torch
import torch.nn as nn
################################################################################
#
# PARAMETERS
#
################################################################################
# data
DATA_NUM_CHANNELS = 3
DATA_NUM_CLASSES = 100
# model
MODEL_LEVEL_0_BLOCKS = 1
MODEL_LEVEL_1_BLOCKS = 1
MODEL_LEVEL_2_BLOCKS = 4
MODEL_LEVEL_3_BLOCKS = 7
MODEL_STEM_END_CHANNELS = 24
MODEL_LEVEL_0_IDENTITY_CHANNELS = 24
MODEL_LEVEL_1_IDENTITY_CHANNELS = 56
MODEL_LEVEL_2_IDENTITY_CHANNELS = 152
MODEL_LEVEL_3_IDENTITY_CHANNELS = 368
# training
TRAINING_DISPLAY = False
################################################################################
#
# NETWORK BUILDING BLOCK
#
################################################################################
# X block
class XBlock(nn.Module):
# initialization
def __init__(self, Ni, No, Fr=3, Fc=3, Sr=1, Sc=1, G=8):
# parent initialization
super(XBlock, self).__init__()
# identity
if ((Ni != No) or (Sr > 1) or (Sc > 1)):
self.conv0_present = True
self.conv0 = nn.Conv2d(Ni, No, (1, 1), stride=(Sr, Sc), padding=(0, 0), dilation=(1, 1), groups=1, bias=False, padding_mode='zeros')
else:
self.conv0_present = False
# residual
self.bn1 = nn.BatchNorm2d(Ni, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.relu1 = nn.ReLU()
self.conv1 = nn.Conv2d(Ni, No, (1, 1), stride=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1, bias=False, padding_mode='zeros')
self.bn2 = nn.BatchNorm2d(No, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.relu2 = nn.ReLU()
self.conv2 = nn.Conv2d(No, No, (Fr, Fc), stride=(Sr, Sc), padding=(1, 1), dilation=(1, 1), groups=G, bias=False, padding_mode='zeros')
self.bn3 = nn.BatchNorm2d(No, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
self.relu3 = nn.ReLU()
self.conv3 = nn.Conv2d(No, No, (1, 1), stride=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1, bias=False, padding_mode='zeros')
# forward path
def forward(self, x):
#if TRAINING_DISPLAY: print("\tXBLOCK_INPUT: ", x.shape)
# residual
res = self.bn1(x)
res = self.relu1(res)
res = self.conv1(res)
#if TRAINING_DISPLAY: print("\tXBLOCK_CONV1: ", res.shape)
res = self.bn2(res)
res = self.relu2(res)
res = self.conv2(res)
#if TRAINING_DISPLAY: print("\tXBLOCK_CONV2: ", res.shape)
res = self.bn3(res)
res = self.relu3(res)
res = self.conv3(res)
#if TRAINING_DISPLAY: print("\tXBLOCK_CONV3: ", res.shape)
# identity
if (self.conv0_present == True):
x = self.conv0(x)
#if TRAINING_DISPLAY: print("\tXBLOCK_CONV0: ", x.shape)
# summation
x = x + res
# return
return x
################################################################################
#
# NETWORK
#
################################################################################
# define
class Model(nn.Module):
# initialization
def __init__(self,
data_num_channels,
data_num_classes,
model_level_0_blocks,
model_level_1_blocks,
model_level_2_blocks,
model_level_3_blocks,
model_stem_end_channels,
model_level_0_identity_channels,
model_level_1_identity_channels,
model_level_2_identity_channels,
model_level_3_identity_channels):
# parent initialization
super(Model, self).__init__()
# encoder stem
self.enc_stem = nn.ModuleList()
self.enc_stem.append(nn.Conv2d(data_num_channels, model_stem_end_channels, (3, 3), stride=(1, 1), padding=(1, 1), dilation=(1, 1), groups=1, bias=False, padding_mode='zeros'))
# encoder level 0
self.enc_0 = nn.ModuleList()
self.enc_0.append(XBlock(model_stem_end_channels, model_level_0_identity_channels))
for n in range(model_level_0_blocks - 1):
self.enc_0.append(XBlock(model_level_0_identity_channels, model_level_0_identity_channels))
# encoder level 1
self.enc_1 = nn.ModuleList()
self.enc_1.append(XBlock(model_level_0_identity_channels, model_level_1_identity_channels, Sr=2, Sc=2))
for n in range(model_level_1_blocks - 1):
self.enc_1.append(XBlock(model_level_1_identity_channels, model_level_1_identity_channels))
# encoder level 2
self.enc_2 = nn.ModuleList()
self.enc_2.append(XBlock(model_level_1_identity_channels, model_level_2_identity_channels, Sr=2, Sc=2))
for n in range(model_level_2_blocks - 1):
self.enc_2.append(XBlock(model_level_2_identity_channels, model_level_2_identity_channels))
# encoder level 3
self.enc_3 = nn.ModuleList()
self.enc_3.append(XBlock(model_level_2_identity_channels, model_level_3_identity_channels, Sr=2, Sc=2))
for n in range(model_level_3_blocks - 1):
self.enc_3.append(XBlock(model_level_3_identity_channels, model_level_3_identity_channels))
# encoder level 3 complete the bn - relu pattern
self.enc_3.append(nn.BatchNorm2d(model_level_3_identity_channels, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True))
self.enc_3.append(nn.ReLU())
# decoder
self.dec = nn.ModuleList()
self.dec.append(nn.AdaptiveAvgPool2d((1, 1)))
self.dec.append(nn.Flatten())
self.dec.append(nn.Linear(model_level_3_identity_channels, data_num_classes, bias=True))
# forward path
def forward(self, x):
#if TRAINING_DISPLAY: print("MODEL_INPUT: ", x.shape)
# encoder stem
for layer in self.enc_stem:
#if TRAINING_DISPLAY: print("MODEL_ENC_STEM: ", x.shape)
x = layer(x)
# encoder level 0
for layer in self.enc_0:
#if TRAINING_DISPLAY: print("MODEL_ENC0: ", x.shape)
x = layer(x)
# encoder level 1
for layer in self.enc_1:
#if TRAINING_DISPLAY: print("MODEL_ENC1: ", x.shape)
x = layer(x)
# encoder level 2
for layer in self.enc_2:
#if TRAINING_DISPLAY: print("MODEL_ENC2: ", x.shape)
x = layer(x)
# encoder level 3
for layer in self.enc_3:
#if TRAINING_DISPLAY: print("MODEL_ENC3: ", x.shape)
x = layer(x)
# decoder
for layer in self.dec:
#if TRAINING_DISPLAY: print("MODEL_DEC: ", x.shape)
x = layer(x)
# return
return x
# create
model = Model(DATA_NUM_CHANNELS,
DATA_NUM_CLASSES,
MODEL_LEVEL_0_BLOCKS,
MODEL_LEVEL_1_BLOCKS,
MODEL_LEVEL_2_BLOCKS,
MODEL_LEVEL_3_BLOCKS,
MODEL_STEM_END_CHANNELS,
MODEL_LEVEL_0_IDENTITY_CHANNELS,
MODEL_LEVEL_1_IDENTITY_CHANNELS,
MODEL_LEVEL_2_IDENTITY_CHANNELS,
MODEL_LEVEL_3_IDENTITY_CHANNELS) |
21e93a9e63969f1a8a0ff398cc8b5b1c94668317 | dcronin05/timewaster | /main.py | 212 | 3.859375 | 4 | print("Hello world")
class AClass(object):
def __init__(self, a, b):
self.a = a
self.b = b
def getter(self):
return self.a
newObj = AClass(3, "hello")
print(newObj.getter())
|
c1c530035fcd38d5b23e00dd66f914206de5d313 | iampaavan/Internet_Data_Python | /urllibdata_start.py | 910 | 3.703125 | 4 | # Send data to a server using urllib
# TODO: import the request and parse modules
import urllib.request
import urllib.parse
def main():
# url = 'http://httpbin.org/get'
url = 'http://httpbin.org/post'
# TODO: create some data to pass to the GET request
args = {
'Name': 'Paavan Gopala',
'Is_Author': True
}
# TODO: the data needs to be url-encoded before passing as arguments
data = urllib.parse.urlencode(args)
# TODO: issue the request with a data parameter as part of the URL
#result = urllib.request.urlopen(url + '?' + data)
# TODO: issue the request with a data parameter to use POST
data = data.encode('utf-8')
result = urllib.request.urlopen(url, data=data)
print(f"Result Code: {result.status}")
print(f"Returned Data ----------------------------------------")
print(f"{result.read().decode('utf-8')}")
if __name__ == '__main__':
main()
|
0b8333949d8b4a32573cd24b8c83cedd9585e25e | pancham2016/ScubaAdventure | /bubble.py | 1,042 | 3.921875 | 4 | import pygame
from pygame.sprite import Sprite
class Bubble(Sprite):
"""A class that manages bubbles released from the diver."""
def __init__(self, sa_game):
"""create a bubble object at the diver's current position."""
super().__init__()
self.screen = sa_game.screen
self.settings = sa_game.settings
# import the bubble image
self.image = pygame.image.load("images/bubble.bmp")
self.bubble_rect = self.image.get_rect()
self.bubble_rect.topright = sa_game.diver.rect.topright
# Store the bubble's position as a decimal value
self.y = float(self.bubble_rect.y)
def update(self):
"""Move the bubble up the screen."""
# Update the decimal position of the bubble
self.y -= self.settings.bubble_speed
# Update the rect position.
self.bubble_rect.y = self.y
def blit_bubble(self):
"""Draw the bubble at the diver's current location"""
self.screen.blit(self.image, self.bubble_rect.topright) |
62d9367a9114d703024070eee7b92f1d4c067f2a | xiaojin9712/data_strcture_review | /two_sum.py | 1,005 | 3.671875 | 4 | A = [-2, 1,2,4,7,11]
target = 13
# Time Complexity: O(n^2)
# Space Complexity: O(1)
def two_sum_brute_force(A, target):
for i in range(len(A) - 1):
for j in range(i+1, len(A)):
if A[i] + A[j] == target:
print(A[i], A[j])
return True
return False
two_sum_brute_force(A, target)
# Time Complexity: O(n)
# Space Complexity: O(n)
def two_sum_hash_table(A, target):
ht = dict()
for i in range(len(A)):
if A[i] in ht:
print(ht[A[i]], A[i])
return True
else:
ht[target - A[i]] = A[i]
return False
two_sum_hash_table(A, target)
# IF THE ARRAY IS SORTED
# Time Complexity: O(n)
# Space Complexity: O(1)
def two_sum(A, target):
i = 0
j = len(A) - 1
while i < j:
if (A[i] + A[j]) == target:
print(A[i], A[j])
return True
if (A[i] + A[j]) < target:
i += 1
else:
j -= 1
return False
two_sum(A, target)
|
1f2b1c0f66ca6d9b116a1d86c5097cbaa0bd41e7 | pvsreenivas/BillingSoftware-SalesTax | /TaxCalc/ReceiptGenerate.py | 1,137 | 3.609375 | 4 | # 01a, 07Apr2021, SreenivasK, Initial code
from typing import List, Dict
from .TotalCalc import TotalCalc
class ReceiptGenerate:
def __init__(self):
self.product_list: List[str] = []
def receipt_generate(self):
"""
Returns:
None
"""
print("Ready to bill the cart.")
print("Please enter the products in the format: [QUANTITY] [PRODUCT NAME] at [COST PER PRODUCT]")
print("Example: 1 book at 12.49\n")
self.product_list = []
cont: int = True
print("Enter the sale details: \n")
while cont:
prod: str = input()
if prod:
self.product_list.append(prod.strip(" "))
else:
cont = False
total_calc: TotalCalc = TotalCalc(self.product_list)
taxed_product_list: List = total_calc.get_receipt_product_list()
print("***********Receipt***********")
for taxed_product in taxed_product_list:
print("{}".format(taxed_product))
print("**********Thank You**********")
print("*********Visit Again*********\n")
|
ba76365aa5bf69e54e4ee4cba9ebb4ef7c6daf97 | arehy/Elvenar | /tesztek/radioButton.py | 540 | 3.84375 | 4 | from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = StringVar(root, '1')
R1 = Radiobutton(root, text="Kristály", variable=var, value='kristaly', command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text="Márvány", variable=var, value='marvany', command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text="Drágakő", variable=var, value='dragako', command=sel)
R3.pack( anchor = W)
label = Label(root)
label.pack()
root.mainloop() |
792d0ff1f1bf339810b83c2b3f1c6f9aa637ea86 | sofiyuh/ProgramAssignments | /dictionarypractice.py | 855 | 3.578125 | 4 | groceries = {"chicken": "$1.59", "beef": "$1.99", "cheese": "$1.00", "milk": "$2.50"}
NBA_players = {"Lebron James": 23, "Kevin Durant": 35, "Stephen Curry": 30, "Damian Lillard": 0}
PHONE_numbers = {"Mom": 5102131197, "Dad": 5109088833, "Sophia": 5106939622}
shoes = {"Jordan 13": 1, "Yeezy": 8, "Foamposite": 10, "Air Max": 5, "SB Dunk": 20}
chicken_price = groceries["chicken"]
print(chicken_price)
beef_price = groceries["beef"]
print(beef_price)
cheese_price = groceries["cheese"]
print(cheese_price)
milk_price = groceries["milk"]
print(milk_price)
Lebron_number = NBA_players["Lebron James"]
print(Lebron_number)
Kevin_number = NBA_players["Kevin Durant"]
print(Kevin_number)
NBA_players["Lebron James"] = 6
jersey_number = NBA_players["Lebron James"]
print(jersey_number)
NBA_players["Lebron James"] -= 17
jersey_number = NBA_players["Lebron James"]
print(jersey_number) |
d59bd150cb4fcb379cb959b9310cf1204d06b65a | asolisn/Ejercicios-de-la-S9 | /class Ordenar.py | 440 | 3.59375 | 4 | class Ordenar
def__init__(self,lista):
self.lista=lista
def recorrerElemento(self):
for ele in self.lista:
print(ele)
def recorrerPosicion(self):
for pos,ele in self.lista.items():
print(pos,ele)
lista = [2,3,1,5,8,10]
ord1 = Ordenar(lista)
ord1.recorrerElemento()
ord1.recorrerPosicion() |
d160a250d883ed92ce1b9effd217a4d5177b3bfc | FullStackToro/Python_Orden_por_Inserci-n | /main.py | 633 | 3.90625 | 4 |
#Los datos en el arreglo son ordenados de menor a mayor.
def ordenamientoPorInserccion(num):
#Recorre todas las posiciones del arreglo
for x in range (len(num)):
#No es necesario evaluar con un solo valor
if x==0:
pass
else:
#Comparación e intercambio (en caso de que el numero ubicado en lugar predecesor sea mayor)
for y in range (x,0,-1):
if num[y]<num[y-1]:
num[y-1],num[y]=num[y],num[y-1]
ouput="Arreglo modificado: {}".format(num)
return ouput
if __name__ == '__main__':
print(ordenamientoPorInserccion([6,5,3,1,8,7,2,4]))
|
acdd2bf6a695151004880dffae1d509918fb7b59 | jpcirqueira/Grafos1_Fofocando | /criagrafo.py | 514 | 3.953125 | 4 |
def main():
h = {}
numnos = int(input('digite o numero de pessoas:\n'))
for i in range(0,numnos):
vizinhos = []
nomeno = input('represente a pessoa por um nome ou numero ' + str(i) + ' :')
numvizinhos = int(input('digite o numero de conhecidos do ' + str(nomeno) + ' :' ))
for j in range(0,numvizinhos):
vizinho = input('indique o ' + str(j+1) + ' conhecido:')
vizinhos.append(vizinho)
h[str(nomeno)] = vizinhos
return h
|
d4a3251bdf830118e2c04dd9cdff7c74ab1c1e1c | IanMK-1/Password-locker | /password_locker_test.py | 2,975 | 3.703125 | 4 | import unittest
from User import User
class TestPasswordLocker(unittest.TestCase):
def setUp(self) -> None:
"""Method that define instructions to be ran before each test method"""
self.new_locker_account = User("Ian", "Mwangi", "ianmk", "1234567")
def test_init(self):
"""Test to check if the objects are being instantiated correctly"""
self.assertEqual(self.new_locker_account.first_name, "Ian")
self.assertEqual(self.new_locker_account.last_name, "Mwangi")
self.assertEqual(self.new_locker_account.username, "ianmk")
self.assertEqual(self.new_locker_account.password, "1234567")
def test_save_user_details(self):
"""Test_save_user_details tests if details of a new user are being saved"""
self.new_locker_account.save_user_details()
self.assertEqual(len(User.user_list), 1)
def tearDown(self) -> None:
"""tearDown method define instruction to be run before each test method"""
User.user_list = []
def test_save_multiple_user_details(self):
"""Test_save_multiple_user_details saves details of multiple users"""
self.new_locker_account.save_user_details()
user_test_details = User("joe", "mark", "joe123", "lockedaccount")
user_test_details.save_user_details()
self.assertEqual(len(User.user_list), 2)
def test_get_user_account_by_username_password(self):
"""test_get_user_account_by_username is a test that obtains locker account based on username and password"""
self.new_locker_account.save_user_details()
user_test_details = User("joe", "mark", "joe123", "lockedaccount")
user_test_details.save_user_details()
got_user_account = User.get_user_account("joe123", "lockedaccount")
self.assertEqual(got_user_account.first_name, user_test_details.first_name)
def test_delete_user_account_by_username_password(self):
"""test_delete_user_account_by_username is a test that deletes locker account based on username and password"""
self.new_locker_account.save_user_details()
user_test_details = User("joe", "mark", "joe123", "lockedaccount")
user_test_details.save_user_details()
got_account = User.get_user_account("joe123", "lockedaccount")
got_account.del_user_account()
self.assertEqual(len(User.user_list), 1)
def test_check_if_user_exists(self):
self.new_locker_account.save_user_details()
user_test_details = User("joe", "mark", "joe123", "lockedaccount")
user_test_details.save_user_details()
user_exists = User.user_exist("joe123", "lockedaccount")
self.assertTrue(user_exists)
def test_display_user_details(self):
"""test_display_user_details tests if the available user account is being displayed"""
self.assertEqual(User.display_user_details(), User.user_list)
if __name__ == '__main__':
unittest.main()
|
419e9c5cbb652df0abccd13ca68273bc18327cd9 | jadugnap/python-problem-solving | /Task4-predict-telemarketers.py | 1,300 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
text.csv columns: sending number (string), receiving number (string), message timestamp (string).
call.csv columns: calling number (string), receiving number (string), start timestamp (string), duration in seconds (string)
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
text_senders = set([t[0] for t in texts])
text_receivers = set([t[1] for t in texts])
call_receivers = set([c[1] for c in calls])
whitelist = call_receivers.union(text_senders, text_receivers)
# print("\n".join(sorted(whitelist)))
callers = sorted(set([c[0] for c in calls if c[0] not in whitelist]))
print("These numbers could be telemarketers: ")
print("\n".join(callers))
|
33a9b899adfee643bc01dfb05d9291fbec3d65c0 | JiahuanChen/homework2 | /simulator_v2.py | 10,991 | 3.5 | 4 | #! /usr/bin/python
"""
Try to finished all three extra tasks. I used Gaussian distribution for the
reason that it is the most common distribute in statistics.
"""
import sys
import math
import string
import random
from optparse import OptionParser
#add functions
parser = OptionParser()
parser.add_option("--calc", help="calculate length and distribution")
parser.add_option("--save", help="save the parameter file, must follow --calc \
or --load")
parser.add_option("--load", help="load the parameter file")
parser.add_option("--k", help="report dinucleotide and higher-order \
compositional statistics, must follow the \'--calc\',e.g. --calc .fa --k n")
parser.add_option("--insert", help="insert motifs to the parameter file. \
To use this function, just enter [script] --insert paramterfile, and you'll \
see instructions.")
(options, args) = parser.parse_args()
length = 70
def checkinput(arg):
if len(arg) == 1:
return 1;
elif arg[1] == "--calc":
if len(arg) == 3 or arg[3] == "--save" or arg[3] == "--k":
return 2
else:
return -1
elif arg[1] == "--load":
if len(arg) == 3 or arg[3] == "--save":
return 3
else:
return -1
elif arg[1] == "--insert":
return 4
else:
return -1
#input: list of ditribution(dictionary) and sequence_length(int)
#function: generate random sequences that can be devided by 3
#return: list of unchecked sequences
def generate_sequences(distribution,sequence_length):
sequences = []
count = 0
for single_dis in distribution:
seq = []
for i in range(0,int(round(single_dis["A"]*sequence_length[count]))):
seq.append("A")
for i in range(0,int(round(single_dis["T"]*sequence_length[count]))):
seq.append("T")
for i in range(0,int(round(single_dis["C"]*sequence_length[count]))):
seq.append("C")
for i in range(0,int(round(single_dis["G"]*sequence_length[count]))):
seq.append("G")
count += 1;
random.shuffle(seq)
s = ''.join(seq)
while(len(s) %3 != 0):
s += str(random.choice(["A","T","C","G"]))
sequences.append(s)
return sequences
#input: list of unchecked sequences
#function: check start and stop codon
#return: list of checked sequences
def check(sequences):
new_sequences = []
for seq in sequences:
if(seq[0:3] != "ATG"):
seq = "ATG" + seq[3:]
for i in range(3,len(seq)-3,3):
if (seq[i:i+3] == "TAA"
or seq[i:i+3] == "TAG"
or seq[i:i+3] == "TGA"):
seq = seq[:i] + random.choice(["A","C","G"]) + seq[i+1:]
if (seq[len(seq)-3:len(seq)] != "TAA"
or seq[len(seq)-3:len(seq)] != "TAG"
or seq[len(seq)-3:len(seq)] != "TGA"):
seq = seq[:len(seq)-3] + random.choice(["TAA","TAG","TGA"])
new_sequences.append(seq)
return new_sequences
#input: list of sequences
#function: computedistribution
#return: list of distribution
def compute_distribution(sequences):
distribution = []
for seq in sequences:
dictionary = {"A":float(0),"C":float(0), "T":float(0),"G":float(0)}
for nucleotide in seq:
dictionary[nucleotide] += 1
for i in dictionary:
dictionary[i] /= len(seq)
distribution.append(dictionary)
return distribution
#input: list of distributions, sequences, names, filename
#function: generate parameter file
#file format: line1: name1; line2: length; line3: distribution(0~1),
#line4:user-specified motifs, etc..
def save_parameter(distributions,sequences,names,filename):
f = open(filename,"w")
for i in range(0,len(names)):
f.write(names[i]+"\n")
f.write(str(len(sequences[i]))+"\n")
for dis in distributions[i]:
f.write(dis+ " ")
f.write(str(distributions[i][dis])+ " ")
f.write("\n")
f.write("\n")
f.close()
#input:list of names and sequences
#function: print names and sequences to screen
def print_sequences(sequences,names):
for i in range(0,len(names)):
print("%s %d bp" %(names[i], len(sequences[i])))
for j in range(0, len(sequences[i]), length):
print(sequences[i][j:j+length])
#input: filename(string)
#functions: load names and sequences
#return: list of names and sequences
def openfile(filename):
file = open(filename)
sequence = []
name = []
count = -1
for line in file.readlines():
if line[0] == '>':
line = line.replace('\n','')
name.append(line)
sequence.append('')
count += 1
else:
sequence[count] += line
for i in range(0,count+1):
sequence[i] = sequence[i].replace('\n','')
return name,sequence
#input list of sequences lengths
#function: generate gaussian distribution and then random lengths
#return:list of random sequences lengths
def gaussian(seq_len):
average_len = 0.0
for seq in seq_len:
average_len += seq
average_len /= len(seq_len)
diviation = 0.0
for seq in seq_len:
diviation += (average_len - seq)**2
diviation = math.sqrt(diviation)
new_len = [];
for i in range(0,len(seq_len)):
new_len.append(random.gauss(average_len,diviation))
return new_len
#input: filename
#function: get lists of names,sequence_length,distributions for parameter file
#return:lists of names,sequence_length,distributions,motifs
def loadparams(filename):
file = open(filename)
names = []
sequence_length = []
distributions = []
motifs = []
count = 0
for line in file.readlines():
line = line.replace('\n','')
if count == 0:
names.append(line)
count += 1
elif count == 1:
sequence_length.append(int(line))
count += 1
elif count == 2:
dictionary = {}
s = line.split(" ")
for i in range(0,8,2):
dictionary[s[i]] = float(s[i+1])
distributions.append(dictionary)
count += 1;
elif count == 3:
motifs.append(line)
count = 0
return names,sequence_length,distributions,motifs
#input: k(k-nucleotide), list of sequences
#function: split sequences every k nucleotides and records them in a dictionary
#The distribution is show by how many times the k-nucleotide appears
def k_mers(k, sequences):
distribution = []
for seq in sequences:
dictionary = {}
for i in range(0,len(seq),k):
if dictionary.get(seq[i:i+k]) == None:
dictionary[seq[i:i+k]] = 1
else:
dictionary[seq[i:i+k]] += 1
distribution.append(dictionary)
print(distribution)
#input: list of sequences and motifs
#function: generate a random position except the at begining and the ending,
# then replace the position with the motifs
#return: list of sequences
def insert_motif(sequences,motifs):
for i in range(0,len(sequences)):
position = random.randint(1,(len(sequences[i])-len(motifs[i]))/3)
position *= 3
sequences[i] = sequences[i][:position] + motifs[i]\
+sequences[i][position+len(motifs):]
return sequences
#input: filename
#function: add motif to parameter
def edit_param(filename):
names,sequence_length,distributions,motifs = loadparams(filename)
print("There are "+str(len(names))+" sequences. Which sequence do you\
want to edit? Enter 0 to exit")
f = open(filename,"r")
contant = f.readlines()
f.close()
f = open(filename,"w")
index = input("Enter a sequence index:")
if (index> len(names)):
print("Out of range.")
while(index != 0 and index <= len(names)):
mof = raw_input("Enter the motif:")
mof_validation = True
if len(mof)%3 != 0:
mof_validation = False
for i in range(0,len(mof),3):
for i in range(3,len(mof)-3,3):
if (mof[i:i+3] == "TAA"
or mof[i:i+3] == "TAG"
or mof[i:i+3] == "TGA"):
mof_validation = False
if mof_validation:
mof += "\n"
contant[index*4-1] = mof
else:
print("Motif is not validated! Please check your motif!")
index = input("Enter a sequence index:")
if (index> len(names)):
print("Out of range.")
f.writelines(contant)
f.close()
# entrance
if __name__ == '__main__':
task = checkinput(sys.argv)
if task == 1:
#for no argument, the distribution is set to 0.25 evenly
distribution = [
{"A":float(0.25),"C":float(0.25), "T":float(0.25),"G":float(0.25)}]
sequence_length = [996]
sequences = generate_sequences(distribution,sequence_length)
sequences = check(sequences)
distributions = compute_distribution(sequences)
names = [">sequence1"]
filename = "mypara.txt"
save_parameter(distributions,sequences,names,filename)
print_sequences(sequences,names)
elif task == 2:
names, sequences = openfile(sys.argv[2])
distributions = compute_distribution(sequences)
sequence_length = []
for seq in sequences:
sequence_length.append(len(seq))
print(sequence_length)
sequence_length = gaussian(sequence_length)
sequences = generate_sequences(distributions,sequence_length)
sequences = check(sequences)
print_sequences(sequences,names)
if len(sys.argv) == 5:
if sys.argv[3] == "--save":
save_parameter(distributions,sequences,names,sys.argv[4])
elif sys.argv[3] == "--k":
k_mers(int(sys.argv[4]), sequences)
elif task == 3:
names,sequence_length,distributions,motifs = loadparams(sys.argv[2])
#use gaussian distribution to generate new lengths
#but the diviation will become rediculously large(several hundreds)
#thus the random sequences saperate in a very large range
sequence_length = gaussian(sequence_length)
sequences = generate_sequences(distributions,sequence_length)
sequences = check(sequences)
sequences = insert_motif(sequences,motifs)
print_sequences(sequences,names)
if len(sys.argv) == 5:
save_parameter(distributions,sequences,names,sys.argv[4])
elif task == 4:
edit_param(sys.argv[2])
else:
print("Please check your input!")
|
a4b024fe5edf1f5da39078c8d52034ba303a98cc | schirrecker/Math | /Math with Python.py | 397 | 4.15625 | 4 | from fractions import Fraction
try:
a = Fraction(input("Enter a fraction: "))
b = Fraction(input("Enter another fraction: "))
except ValueError:
print ("You entered an invalid number")
except ZeroDivisionError:
print ("You can't divide by zero")
else:
print (a+b)
def is_factor (a, b):
if b % a == 0:
return True
else:
return False
|
09772c3ab8555b1b1e33b480f7fb02dedc8dfacc | schirrecker/Math | /Censor text.py | 278 | 3.84375 | 4 | def censor(text, word):
list = text.split()
newlist = []
for w in list:
if w == word:
newlist.append(len(w)*"*")
else:
newlist.append(w)
return " ".join(newlist)
print (censor("Hi there Ismene", "Ismene"))
|
5ad4cf6a9e1acb0834dcb0d663d83e0db1417a46 | schirrecker/Math | /mathematical_functions.py | 109 | 3.546875 | 4 | def equation(a,b,c,d):
''' solves equations of the form ax + b = cx + d'''
return (d - b)/(a - c)
|
b105489d556e2941fa532c828bb47f8f19e4ea8d | hahapang/py_tutor | /Ch_11_TEST/names.py | 967 | 3.9375 | 4 | # Данная прога предназначена для проверки правильности работы функции
# get_formatted_name(), расположенной в файле name_function.py (Ex. 1).
# Данная функция строит полное имя и фамилию, разделив их пробелами и
# преобразуя первый символы слов в заглавные буквы.
# Проверка проводится путем импорта функции get_formatted_name() из модуля
# name_function.
from name_function import get_formatted_name
print("Enter 'q' at any time ti quit.")
while True:
first = input("\nPlease give me a first name: ")
if first =='q':
break
last = input("Please give me a last name: ")
if last =='q':
break
formatted_name = get_formatted_name(first, last)
print(f"\tNeatly formatted name: {formatted_name}.")
|
258b95d7a40c7c62c7b195cc4fffd038e2ba0373 | hahapang/py_tutor | /magic_number.py | 320 | 3.703125 | 4 | # Аналогичнофайлу из предыдущего коммита.
# Условие answer (17) не равго 42. Так как условие
# истино - блок с отступом выполняется!
#
answer = 17
if answer != 42: #1
print("That is not correct answer.Please tre again!")
|
6aa4ee170811b133b8d66b3bc6ae6c87812412bf | christislord12/Panda3D-Project-Collection | /panda3dcgshaders/8.py | 8,642 | 3.5 | 4 | """
Like 0.py we restart from scratch and create a basic example with one point
light, that only supports diffuse lighting. There is no shader attached to this
example. If you do not understand this sample then open the Panda3D manual and
try to understand e.g. the Disco-Lights sample.
When we talk about lighting we talk about an "effect" that we can see with our
eyes. Live is a game, just with better graphic. Lighting is still something you
may do your own research and invent a cool new idea, no one had before. We often
only approximate lighting and invent new terms that do not exist in reality e.g.
there is no specular light in real live. For better lighting we often need to
pre calculate some values in an often slow pre process. We start here only with
one basic lighting model: Diffuse Lighting.
The basic idea of diffuse lighting is: The steeper the angle between the light
and a surface, the less light particles can reach the surface. The following
figures show an example with a directional light and a wall.
1. 100% of the light reaches the wall.
2. ~50% of the light reaches the wall.
3. 0% of the light reaches the wall.
| /
1. -> | 2. -> / 3. -> ---
| /
If no light reaches a wall, the wall cannot reflect any light particles and
therefore you cannot see anything. This idea is only one basic idea. This idea
e.g. says nothing about the fact that if a wall reflects some light, it may be
possible that this light reaches another wall, which may reflect this light
particles once more.
Given that there is one wall behind another wall:
| |
-> | |
| |
If we translate our idea to this situation, it means, that both walls got the
same amount of light, because the angle between the light surface and the light
source is equal for both walls. This is of course dead wrong, because the first
wall occludes the second wall, so there is more or less no light at all.
The default lighting model the fixed function pipeline offers to Panda3D has
tons of flaws, even though it helps to increase realism. Let us stick to this
mediocre lighting model for now (better lighting models are often extremely slow
and only with tricks you may use them in 60 FPS applications).
To calculate how much light reaches our triangle (or wall) we need a tool that
helps us to distinguish if a triangle looks toward a light source or not. One
possibility to do this is a surface normal. In the preceding examples we assumed
that the surface normal is perpendicular to the surface. This is not always
true, as we see later, therefore we like to define a normal at least for each
triangle (or face). When you have a look at the cube.egg once more you see that
for every polygon, a normal is specified. If Panda3D needs to triangulate the
model for the GPU it assigns every triangle, that belongs to the same polygon,
the same normal.
That is not the whole truth, in fact, the GPU likes to have a normal for every
vertex. Why this is a good idea, is shown by another example. Open the enclosed
figures.svg or figures.png and look at figure 8-1. If we have a cube, there are
at least two possibilities to assign normals. The visual difference you may see
later is that the left cube has sharp edges, while the right cube has smooth
edges (on the right cube, the normals on each corner have a small gap in
between, this gap is only here to see that every vertex has a normal). Metal
like objects may have sharper edges while wooden objects may not. An artist may
influence how a model looks like (with lighting enabled) if he/she modifies the
normals. Back to our "whole truth" problem. As you can see it is impossible to
create a smooth cube if every polygon or triangle only has one normal. We need
at least one normal for every vertex.
The cube.egg model is an example of cube with sharp edges, while the
cube-smooth.egg model is an example of a cube with smooth edges. Try to see the
difference between this two files.
The fixed function pipeline of a GPU (that is the pipeline Panda3D uses if there
is no call to setShader or setAutoShader) is not that sophisticated. Better said
the GPUs were not powerful enough to calculate this very simple lighting model
per fragment/pixel, they only can calculate it per vertex. The larger your
triangles on your screen, the falser the result.
One more definition for diffuse lighting is, that it does not depend on the
viewers position. That is not true for all effects e.g. the "output" of a mirror
depends on the viewers position. Specular lighting simulates a mirror like
effect for lights and therefore depends on the viewers position.
Diffuse lighting is especially suited for rough surfaces, because of our
definition that the surfaces should distribute light in any direction,
independent of any other environmental effects.
Back to our problem: We have a surface normal, we have a light position and we
say that only this two things should matter. We now can calculate a direction
vector from the light to our triangle. Because it is a point light, that
distributes light in any direction, this assumption is correct. After this first
operation we calculate the angle between this direction and surface normal.
Based on this angle we can calculate how much diffuse light we have on a
triangle.
| |
1. -> <-| 2. -> |->
| |
In example 1. we have 100% diffuse light while in the example 2. there is 0%
diffuse lighting.
There are two possibilities to calculate this angle. We do some trigonometry, or
we use the dot product. Both ideas are equivalent, but the second is faster to
calculate.
Read the following page to get in-depth information.
http://en.wikipedia.org/wiki/Dot_product
We will later see how to calculate exactly each of this steps. I only like to
introduce some concepts here.
"""
import sys
import math
import direct.directbase.DirectStart
from direct.interval.LerpInterval import LerpFunc
from pandac.PandaModules import PointLight
base.setBackgroundColor(0.0, 0.0, 0.0)
base.disableMouse()
base.camLens.setNearFar(1.0, 50.0)
base.camLens.setFov(45.0)
camera.setPos(0.0, -20.0, 10.0)
camera.lookAt(0.0, 0.0, 0.0)
root = render.attachNewNode("Root")
"""
We set up a default point light here. You may modify the color of the light, but
in the next examples we assume, that the light has no attenuation and is white.
There is a dummy model attached to this node, to see where the light should be.
Because this light is parented to render, and we only enable light on the cubes,
this model does not influence the lighting nor is it lit by the light itself.
"""
pointlight = PointLight("Light")
light = render.attachNewNode(pointlight)
modelLight = loader.loadModel("misc/Pointlight.egg.pz")
modelLight.reparentTo(light)
"""
DIRTY
Replace cube.egg with cube-smooth.egg and try to understand why both outputs
differ.
"""
modelCube = loader.loadModel("cube.egg")
cubes = []
for x in [-3.0, 0.0, 3.0]:
cube = modelCube.copyTo(root)
cube.setPos(x, 0.0, 0.0)
cube.setLight(light)
cubes += [ cube ]
base.accept("escape", sys.exit)
base.accept("o", base.oobe)
"""
We move around our light. Because this basic application only supports per
vertex lighting you often can see some odd artifacts if only one vertex of a
face is lit.
The bounding box around all cubes ranges from (-4.0, -1.0, -1.0) to (4.0, 1.0,
1.0). Therefore we set the radius of the virtual sphere (the motion path of the
light) to something that is only a little bit larger than 4.0. This helps later
to see the visual difference from per vertex lighting to per pixel lighting.
"""
def animate(t):
radius = 4.3
angle = math.radians(t)
x = math.cos(angle) * radius
y = math.sin(angle) * radius
z = math.sin(angle) * radius
light.setPos(x, y, z)
def intervalStartPauseResume(i):
if i.isStopped():
i.start()
elif i.isPaused():
i.resume()
else:
i.pause()
interval = LerpFunc(animate, 10.0, 0.0, 360.0)
base.accept("i", intervalStartPauseResume, [interval])
def move(x, y, z):
root.setX(root.getX() + x)
root.setY(root.getY() + y)
root.setZ(root.getZ() + z)
base.accept("d", move, [1.0, 0.0, 0.0])
base.accept("a", move, [-1.0, 0.0, 0.0])
base.accept("w", move, [0.0, 1.0, 0.0])
base.accept("s", move, [0.0, -1.0, 0.0])
base.accept("e", move, [0.0, 0.0, 1.0])
base.accept("q", move, [0.0, 0.0, -1.0])
run()
|
618105d73f3df6c48f4760c14401e7ef202b66af | christislord12/Panda3D-Project-Collection | /panda3dcgshaders/2.py | 2,227 | 3.5 | 4 |
"""
The first useful sample. After this tutorial we are able to draw our cubes,
which look like cubes. With our knowledge we are not able to color them
correctly, but we can do some nice stuff and see the result. If everything is
black this time, something must be wrong.
"""
import sys
import direct.directbase.DirectStart
base.setBackgroundColor(0.0, 0.0, 0.0)
base.disableMouse()
base.camLens.setNearFar(1.0, 50.0)
base.camLens.setFov(45.0)
camera.setPos(0.0, -20.0, 10.0)
camera.lookAt(0.0, 0.0, 0.0)
root = render.attachNewNode("Root")
modelCube = loader.loadModel("cube.egg")
cubes = []
for x in [-3.0, 0.0, 3.0]:
cube = modelCube.copyTo(root)
cube.setPos(x, 0.0, 0.0)
cubes += [ cube ]
shader = loader.loadShader("2.sha")
"""
DIRTY
Try to disable the shader on the root node and then enable it only on one or two
cubes and see what happens. You can do this before you start to modify the
shader.
"""
root.setShader(shader)
#cubes[0].setShader(shader)
#cubes[2].setShader(shader)
"""
DIRTY
If you have tested how you can enable/disable a shader on individual nodes, and
how the scene graph works with shaders, you can modify this lines (comment or
remove the three Python lines above) and load two shaders at the same time. e.g.
2.sha and 1.sha. Apply 2.sha to one cube, and 1.sha to another cube. Because
1.sha does nothing the cube with this shader should disappear.
"""
#shader1 = loader.loadShader("1.sha")
#shader2 = loader.loadShader("2.sha")
#cubes[0].setShader(shader2)
#cubes[1].setShader(shader1)
"""
DIRTY
Do you like to see the model matrix of each cube? You may only understand this
if you read the comment for vshader in 2.sha.
"""
#for cube in cubes:
# print cube.getMat()
base.accept("escape", sys.exit)
base.accept("o", base.oobe)
def move(x, y, z):
root.setX(root.getX() + x)
root.setY(root.getY() + y)
root.setZ(root.getZ() + z)
base.accept("d", move, [1.0, 0.0, 0.0])
base.accept("a", move, [-1.0, 0.0, 0.0])
base.accept("w", move, [0.0, 1.0, 0.0])
base.accept("s", move, [0.0, -1.0, 0.0])
base.accept("e", move, [0.0, 0.0, 1.0])
base.accept("q", move, [0.0, 0.0, -1.0])
run()
|
0c07ac63e4e0c8bdb25ff27d3f18419705cc3506 | AnkitaPisal1510/list | /listmagic1.py | 746 | 3.625 | 4 | m=[
[8,3,4],
[1,5,9],
[6,7,2]
]
A=15
k=0
while k<len(m):
column=0
sum=0
l=len(m[k])
while column<l:
sum=sum+m[k][column]
column+=1
print(sum,"column")
x=sum+sum+sum
k+=1
print(x)
i=0
while i<len(m):
row=0
sum1=0
while row<len(m[i]):
sum1+=m[row][row]
row+=1
print(sum1,"row")
h=sum1+sum1+sum1
i+=1
print(h)
s=m[0][0]+m[1][1]+m[2][2]
d=m[0][2]+m[1][1]+m[2][0]
if s==A:
if d==A:
mn=s+d
print("diagonal:",mn)
if sum==sum1==A:
print("it is majic square")
else:
print("it is not majic square")
else:
print("oit is not majic square")
else:
print("it is not majic square")
|
ee51b89083daa92736666f1712448406f4b118c3 | AnkitaPisal1510/list | /listdifference.py | 149 | 3.546875 | 4 | #difference
# l=[1,2,3,4,5,6]
# p=[2,3,1,0,6,7]
# i=0
# j=[]
# while i<len(p):
# if l[i] not in p:
# j.append(l[i])
# i+=1
# print(j) |
d9ebfa0746c3b2daf9bb4796bc910aaa34842e8a | AnkitaPisal1510/list | /listmagic.py | 713 | 3.5625 | 4 | #
#majic square
# a=[
# [8,3,8],
# [1,5,9],
# [6,7,2]
# ]
# row1=row2=row3=0,0,0
# col1=col2=col3=0,0,0
# dia1=dia2=0,0
# i=0
# b=len(a)
# while i<b:
# c=len(a[i])
# j=0
# while j<c:
# if i==0:
# row1=row1+a[i][j]
# col1=col+a[j][i]
# elif i==1:
# row2=row2+a[i][j]
# col2=col2+a[j][i]
# else:
# row3=row3+a[i][j]
# col3=col3+a[j][i]
# j+=1
# i+=1
# m=0
# k=2
# while m<c:
# dia1=dia1+a[m][m]
# dia2=dia2+a[m][k]
# m+=1
# k-=1
# if row1==row2==row3==col1==col2==col3==dia1==dia2:
# print("it is majic square")
# else:
# print("it is not majic")
|
e085c19faf6fe9e11e547c31d30f02e8f29a9d4f | superxingzai/bhattacharyya-distance | /bhatta_dist.py | 4,095 | 3.75 | 4 | """
The function bhatta_dist() calculates the Bhattacharyya distance between two classes on a single feature.
The distance is positively correlated to the class separation of this feature. Four different methods are
provided for calculating the Bhattacharyya coefficient.
Created on 4/14/2018
Author: Eric Williamson ([email protected])
"""
import numpy as np
from math import sqrt
from scipy.stats import gaussian_kde
def bhatta_dist(X1, X2, method='continuous'):
#Calculate the Bhattacharyya distance between X1 and X2. X1 and X2 should be 1D numpy arrays representing the same
# feature in two separate classes.
def get_density(x, cov_factor=0.1):
#Produces a continuous density function for the data in 'x'. Some benefit may be gained from adjusting the cov_factor.
density = gaussian_kde(x)
density.covariance_factor = lambda:cov_factor
density._compute_covariance()
return density
#Combine X1 and X2, we'll use it later:
cX = np.concatenate((X1,X2))
if method == 'noiseless':
###This method works well when the feature is qualitative (rather than quantitative). Each unique value is
### treated as an individual bin.
uX = np.unique(cX)
A1 = len(X1) * (max(cX)-min(cX)) / len(uX)
A2 = len(X2) * (max(cX)-min(cX)) / len(uX)
bht = 0
for x in uX:
p1 = (X1==x).sum() / A1
p2 = (X2==x).sum() / A2
bht += sqrt(p1*p2) * (max(cX)-min(cX))/len(uX)
elif method == 'hist':
###Bin the values into a hardcoded number of bins (This is sensitive to N_BINS)
N_BINS = 10
#Bin the values:
h1 = np.histogram(X1,bins=N_BINS,range=(min(cX),max(cX)), density=True)[0]
h2 = np.histogram(X2,bins=N_BINS,range=(min(cX),max(cX)), density=True)[0]
#Calc coeff from bin densities:
bht = 0
for i in range(N_BINS):
p1 = h1[i]
p2 = h2[i]
bht += sqrt(p1*p2) * (max(cX)-min(cX))/N_BINS
elif method == 'autohist':
###Bin the values into bins automatically set by np.histogram:
#Create bins from the combined sets:
# bins = np.histogram(cX, bins='fd')[1]
bins = np.histogram(cX, bins='doane')[1] #Seems to work best
# bins = np.histogram(cX, bins='auto')[1]
h1 = np.histogram(X1,bins=bins, density=True)[0]
h2 = np.histogram(X2,bins=bins, density=True)[0]
#Calc coeff from bin densities:
bht = 0
for i in range(len(h1)):
p1 = h1[i]
p2 = h2[i]
bht += sqrt(p1*p2) * (max(cX)-min(cX))/len(h1)
elif method == 'continuous':
###Use a continuous density function to calculate the coefficient (This is the most consistent, but also slightly slow):
N_STEPS = 200
#Get density functions:
d1 = get_density(X1)
d2 = get_density(X2)
#Calc coeff:
xs = np.linspace(min(cX),max(cX),N_STEPS)
bht = 0
for x in xs:
p1 = d1(x)
p2 = d2(x)
bht += sqrt(p1*p2)*(max(cX)-min(cX))/N_STEPS
else:
raise ValueError("The value of the 'method' parameter does not match any known method")
###Lastly, convert the coefficient into distance:
if bht==0:
return float('Inf')
else:
return -np.log(bht)
def bhatta_dist2(x, Y, Y_selection=None, method='continuous'):
#Same as bhatta_dist, but takes different inputs. Takes a feature 'x' and separates it by class ('Y').
if Y_selection is None:
Y_selection = list(set(Y))
#Make sure Y_selection is just 2 classes:
if len(Y_selection) != 2:
raise ValueError("Use parameter Y_selection to select just 2 classes.")
#Separate x into X1 and X2:
X1 = np.array(x,dtype=np.float64)[Y==Y_selection[0]]
X2 = np.array(x,dtype=np.float64)[Y==Y_selection[1]]
#Plug X1 and X2 into bhatta_dist():
return bhatta_dist(X1, X2, method=method)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.