text
stringlengths 37
1.41M
|
---|
a = [10,20,30]
# add with append() method
a.append(40)
print(a)
# add with insert() method
a.insert(2, 50)
print(a)
# with method extend()
a.extend([66,77,88])
print(a)
# append will always count a data as one data
b = [10,20]
b.append([30,40])
print(b)
# if list added by extend() method, the string will be input per caracter
c = [10,20,30]
c.extend("Hellow World")
print(c)
|
# Filtering List
a = [1,-3,4,-2,5,7,-4]
b = [1,2,3,4,5,6]
# Filtering Negative Number
negatif = [i for i in a if i < 0]
print(negatif)
# Filtering positive number
positive = [i for i in a if i > 0]
print(positive)
# Filtering ganjil genap
c = ['genap' if i % 2 == 0 else 'ganjil' for i in b]
print(c)
# Filtering square number
square = [i**2 for i in b]
print(square)
|
cart = []
f = open('input').read()
santa = f[::2]
robo_santa = f[1::2]
def santa_tracker(nick):
x = 0
y = 0
counter = 0
for i in nick:
# print(i)
# write arrow to x/y. Save every step.
# Compare new step to all old steps: if duplicated, do not increment counter
if i == '^':
y += 1
elif i == '>':
x += 1
elif i == 'v':
y += -1
elif i == '<':
x += -1
coord = x,y
if coord not in cart:
counter += 1
cart.append(coord)
return counter
big_counter = santa_tracker(santa) + santa_tracker(robo_santa)
print(big_counter)
# NO +1 for start location |
from __future__ import print_function
import json
import requests
import urllib
# TODO: do I need urllib?
# Fall back to Python 2's urllib2 and urllib
from urllib2 import HTTPError
from urllib import quote
from urllib import urlencode
import config
# OAuth credentials
CLIENT_ID = config.YELP_CLIENT_ID
CLIENT_SECRET = config.YELP_CLIENT_SECRET
# API constants
API_HOST = 'https://api.yelp.com'
SEARCH_PATH = '/v3/businesses/search'
BUSINESS_PATH = '/v3/businesses/' # Business ID will come after slash.
TOKEN_PATH = '/oauth2/token'
GRANT_TYPE = 'client_credentials'
def get_bearer_token():
"""Get yelp api bearer token.
Returns:
dict: OAuth bearer token and expiration time, obtained using client_id
and client_secret.
Raises:
RequestException: An error occurs from the HTTP request.
"""
# Set parameters for request
url = '{0}{1}'.format(API_HOST, quote(TOKEN_PATH.encode('utf8')))
data = urlencode({
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': GRANT_TYPE,
})
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
# Make request to Yelp API for bearer token
print('Requesting Yelp API bearer token.')
response = requests.request('POST', url, data=data, headers=headers)
print('Yelp API bearer token response: {0}'.format(response.status_code))
# Raise if there are errors
response.raise_for_status()
return response
def request(host, path, bearer_token, url_params=None):
"""Given a bearer token, send a GET request to the API.
Args:
host (str): The domain host of the API.
path (str): The path of the API after the domain.
bearer_token (str): OAuth bearer token, obtained using client_id and
client_secret.
url_params (dict): An optional set of query parameters in the request.
Returns:
dict: The JSON response from the request.
Raises:
RequestException: An error occurs from the HTTP request.
"""
# Set parameters for request
url_params = url_params or {}
url = '{0}{1}'.format(host, quote(path.encode('utf8')))
headers = {
'Authorization': 'Bearer %s' % bearer_token,
}
# Make request to api
print(u'Querying {0} ...'.format(url))
response = requests.request('GET', url, headers=headers, params=url_params)
print(u'API Response: {0}.'.format(response.status_code))
# Raise for any errors
response.raise_for_status()
return response.json()
def search(url_params):
"""Query the Search API by a search term and location.
Args:
url_params (dict): Parameters to pass to Yelp API.
Returns:
dict: The JSON response from the request.
Raises:
RequestException: An error occurs from the HTTP request.
"""
# Get bearer token response
bearer_token = get_bearer_token().json().get('access_token')
# If there is no access token, most likely an error
return request(API_HOST, SEARCH_PATH, bearer_token, url_params)
def get_business(bearer_token, business_id):
"""Query the Business API by a business ID.
Args:
bearer_token (str): OAuth bearer token, obtained using client_id and
client_secret.
business_id (str): The ID of the business to query.
Returns:
dict: The JSON response from the request.
"""
business_path = BUSINESS_PATH + business_id
return request(API_HOST, business_path, bearer_token)
|
import hashlib, binascii, os
import csv
from tkinter import messagebox
PSEUDOS_FILE = "pseudos.csv"
PSEUDO_DEFAULT_INPUT = "Enter Username"
# hash : the simple hash of password
def hash(password) :
hash_object = hashlib.sha512( password.encode() ).hexdigest()
return hash_object
# pseudoIsExiste : the pseudo existe ?
def pseudoIsExiste(pseudo_search) :
isExiste = False
with open(PSEUDOS_FILE) as csvfile:
reader = csv.reader(csvfile, delimiter=';', quotechar=',',
quoting=csv.QUOTE_MINIMAL)
for row in reader:
pseudo = row[0]
if(pseudo == pseudo_search):
isExiste = True
break
return isExiste
# getPasswordByPseudo : return the password of pseudo
def getPasswordByPseudo(pseudo_search) :
password = None
with open(PSEUDOS_FILE) as csvfile:
reader = csv.reader(csvfile, delimiter=';', quotechar=',',
quoting=csv.QUOTE_MINIMAL)
for row in reader:
pseudo = row[0]
if(pseudo == pseudo_search):
password = row[1]
break
return password
# hash_password : hash password with salt
def hash_password(password):
"""Hash a password for storing."""
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'),
salt, 100000)
pwdhash = binascii.hexlify(pwdhash)
return (salt + pwdhash).decode('ascii')
# verify_password : verify password with hash password
def verify_password(stored_password, provided_password):
"""Verify a stored password against one provided by user"""
salt = stored_password[:64]
stored_password = stored_password[64:]
pwdhash = hashlib.pbkdf2_hmac('sha512',
provided_password.encode('utf-8'),
salt.encode('ascii'),
100000)
pwdhash = binascii.hexlify(pwdhash).decode('ascii')
return pwdhash == stored_password |
import sqlite3
# Create a database in RAM
db = sqlite3.connect('mydbCommune.db')
# Creates or opens a file called mydb with a SQLite3 DB
db = sqlite3.connect('mydbCommune.db')
####################################################"DROP ALL TABLE"###############################################
cursor = db.cursor()
cursor.execute('DROP TABLE IF EXISTS commune')
db.commit()
cursor = db.cursor()
cursor.execute('DROP TABLE IF EXISTS departement')
db.commit()
cursor = db.cursor()
cursor.execute('DROP TABLE IF EXISTS region')
db.commit()
cursor = db.cursor()
cursor.execute('DROP TABLE IF EXISTS nouvelleRegion')
db.commit()
####################################################"CREATE ALL TABLE"###############################################
# CREATE : Communes
# CREATE TABLE commune(nom_commune VARCHAR ,code_commune INTEGER,population_totale INTEGER, code_departement VARCHAR, PRIMARY KEY ([code_departement],[code_commune]))
cursor = db.cursor()
cursor.execute('''
CREATE TABLE commune(nom_commune VARCHAR ,code_commune INTEGER,population_totale INTEGER, code_departement VARCHAR)
''')
db.commit()
# CREATE : Departement
cursor = db.cursor()
cursor.execute('''
CREATE TABLE departement(code_departement VARCHAR PRIMARY KEY, nom_departement TEXT, code_region INTEGER, 'code_nouvelle_region' INTEGER)
''')
db.commit()
# CREATE : Region
cursor = db.cursor()
cursor.execute('''
CREATE TABLE region(code_region INTEGER PRIMARY KEY, nom_region TEXT)
''')
db.commit()
# CREATE : Nouvelles Regions
cursor = db.cursor()
cursor.execute('''
CREATE TABLE nouvelleRegion(code_region INTEGER PRIMARY KEY, nom_region TEXT, nb_com INTEGER)
''')
db.commit()
db.close() |
print(1)
# This is a comment
# The below code sets a variable to equal a value notice how this variable does not use single quotes
a = 1
b = 2
# We will now print both variables
print(a,b)
# Now lets add two variable together
print(a+b)
# What happens if you try to add a string and an integer
c = '3'
print(a+c)
# You should receive the following error "TypeError: unsupported operand type(s) for +: 'int' and 'str'"
|
x=float(input("Введите число: "))
def f(x):
pass
if -2.4<=x<=5.7:
return pow(x,2)
else:
return 4
print(f(x))
|
import csv
with open('strInput.csv', 'r') as csv_file:
csv_reader=csv.DictReader(csv_file) #read from the strInput csv file
with open('strTransactions.csv', 'w', newline='') as new_file:
fieldnames = ['Date', 'Time', 'Transaction No.', 'Status', 'Store No.', 'Location Code', 'POS Terminal No.',
'Receipt No.', 'Cashier Staff ID', 'Sales Staff ID','Line Net PMount',
'Line Discount PMount','Line GST PMount']
csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames) #DictWriter function allows to manipulate content using Dictionary datas tructure
csv_writer.writeheader() #write coloumn entry to strTransactions.csv
for line in csv_reader:
csv_writer.writerow({'Date': line['Date'], 'Time': line['Time'], 'Transaction No.': line['Transaction No.'],
'Status': line['Status'], 'Store No.': line['Store No.'],
'Location Code': line['Location Code'],
'POS Terminal No.': line['POS Terminal No.'], 'Receipt No.': line['Receipt No.'],
'Line Net PMount':line['Line Net PMount'],'Line Discount PMount':line['Line Discount PMount'],
'Line GST PMount':line['Line GST PMount'],'Cashier Staff ID': line['Cashier Staff ID'],
'Sales Staff ID': line['Sales Staff ID']}) #write content from strInput to according entry in strTransactions.csv use Dictionary data structure
with open('strInput.csv', 'r') as csv_file: #read from the strInput csv file
csv_reader = csv.DictReader(csv_file)
with open('strLineItems.csv', 'w',newline='') as newfile:
fieldnames=['Transaction No.','Item ID','Item Description','Item Quantity','Item Unit Price']
csv_writer=csv.DictWriter(newfile,fieldnames=fieldnames) #DictWriter function allows to manipulate content using Dictionary datas tructure
csv_writer.writeheader() #write coloumn entry to strLineItems.csv
for line in csv_reader:
csv_writer.writerow({'Transaction No.': line['Transaction No.'],'Item ID':line['Item ID'],
'Item Description':line['Item Description'],
'Item Quantity':line['Item Quantity'],
'Item Unit Price':line['Item Unit Price']}) #write content from strInput to according entry in strLineItems.csv use Dictionary data structure |
numbers = [1, 3, 7, 4, 3, 0, 6, 3, 7 ,8 ,4 ,4 ,4 ,6 ,7 ,6 ,5 ,4, 5, 4, ]
harf = ["a", "g", "h", "k", "l", "m", "f" , "d" , "s" ]
print(max(numbers))
print(max(harf))
print(numbers.count(3))
most_frequent = max(numbers, key = numbers.count) # Burada max() fonksiyonu keyi olarak count belirledik, ve listenin içinde en çok geçen elemanı verir
# count() fonksiyonu da bir list fonksiyonu olduğu için list ismi ile birlikte belirtilmelidir. len() fonksiyonunu key için kullanırken böyle birşey yok
repeat = numbers.count(most_frequent)
result = f"the most frequent number is {most_frequent} and it was {repeat} times repeated"
print(result) |
"""Task : Find out if the given word is "comfortable words" in relation to the ten-finger keyboard use.
A comfortable word is a word which you can type always alternating the hand you type with (assuming you type using a Q-keyboard and use of the ten-fingers standard).
The word will always be a string consisting of only letters from a to z.
Write a program which returns True if it's a comfortable word or False otherwise.
Examples
Given word Desired Output (explanation)
tester False (uses only left-hand fingers)*
polly False (uses only right-hand fingers)*
clarusway True (uses both hand fingers)*"""
left = set("qwertasdfghzxcvb") # Sol el harflerini bir küme yaptık
right = set("üğpoıuyişlkjçömn") # Sağ el harflerini bir küme yaptık
word = set(input("Please enter a word: ")) #Kullanıcıdan bir kelime aldık ve kümeye attık
result = bool(word.intersection(left)) and bool(word.intersection(right)) # Kullanıcının girdiği kelime kümesi ile sol-sağ el kümelerinin bir kesişimi olup olmadığına baktık
print(result) # Varsa zaten boolean olarak True yoksa False döner
print(word.intersection(left))
print(word.intersection(right))
# Bir başka çözüm (specific kelimeler için)
# left_hand = {"q", "a", "z", "w", "s", "x", "e", "d", "c", "r", "f", "v", "t", "g", "b"}
# right_hand = {"y", "h", "n", "u", "j", "m", "ı", "k", "ö", "o", "l", "ç", "p", "ş", "ğ", "ü", "i"}
# tester = set("tester")
# polly = set("polly")
# clarus = set("clarus")
# print("tester is comfortable word :", tester.issubset(left_hand) and tester.issubset(right_hand))
# print("polly is comfortable word :", polly.issubset(left_hand) and polly.issubset(right_hand))
# print("clarus is comfortable word :", not clarus.issubset(left_hand) and not clarus.issubset(right_hand)) |
import datetime
today = datetime.datetime.now()
date = "{today.month}/{today.day}/{today.year}".format(today=today)
print(date)
print("Welcome To Internet Banking")
Bank = input("customer's Bank: ")
Account_Name = input("Account Name: ")
Account_Number = int(input("Your Account Number: "))
initial_balance = float(input("How Much Do You Have In Your Account: "))
print("What Will You Like To Do?")
Options = input("Transfer?,Buy Airtime?, Pay Bill?: ")
if Options=="Buy Airtime".lower():
Network = input("Network: ")
Number = float(input("Phone Number: "))
Amount = float(input("Amount: "))
if Amount<initial_balance:
Balance = initial_balance-Amount
print("Your Recharge Of",Amount,"Sucessful")
print("Thank You For Banking With Us. Your Balance: ",Balance)
else:
print("Insuficient Balance")
if Options=="Pay Bill".lower():
print("Which Of These Bill Are You Paying For")
Bill = input("PHCN?/GOTV?/DSTV?/STARTIME?: ")
Account_Name = input("Account Name: ")
Card_Number = float(input("Card's Serial Number: "))
Amount = float(input("Amount: "))
if Amount<initial_balance:
Balance = initial_balance-Amount
print("Your Recharge Of",Amount,"Sucessful")
print("Thank You For Banking With Us. Your Balance: ",Balance)
else:
print("Insuficient Balance")
if Options=="Transfer".lower():
Which_Bank = input("Recipent's Banks: ")
def transfer(amount,initial_balance):
return initial_balance-amount
amount = int(input("amount to be transfer: "))
balance = transfer(amount,initial_balance)
if amount>initial_balance:
print("Insuficient Balance")
else: balance
for Options in range(1):
if Bank==Which_Bank and amount<initial_balance:
transfer(amount,initial_balance)
print("Operation Succesful")
print("your Account Balance: ",balance)
break
if Bank!=Which_Bank:
print("Note You Will Be Charge N50. Do You Wish To Continue?")
Response = input("Y/N: ")
if Response=="N".lower():
print("Thank You For Banking With Us")
break
if Response=="Y".lower():
transfer(amount,initial_balance)
print("Operation Sucessful")
print("Thank You For Banking With Us. Your Balance:",balance-50)
|
class Solution:
def isValid(self, s: str) -> bool:
if len(s) == 0: return True
stack = []
matching = {")" : "(", "]" : "[", "}" : "{"}
for p in s:
# if p is a close bracket,
if p == ')' or p == ']' or p == '}':
# return False if the stack is empty
if len(stack) == 0:
return False
else:
# check the top element of the stack
top = stack.pop()
# return False if the brackets not matching
if top != matching[p]:
return False
else:
# p is open bracket, add p to stack
stack.append(p)
if len(stack) == 0: return True
return False
|
# Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
# Machine 1 (sender) has the function:
# string encode(vector<string> strs) {
# // ... your code
# return encoded_string;
# }
# Machine 2 (receiver) has the function:
# vector<string> decode(string s) {
# //... your code
# return strs;
# }
# So Machine 1 does:
# string encoded_string = encode(strs);
# and Machine 2 does:
# vector<string> strs2 = decode(encoded_string);
# strs2 in Machine 2 should be the same as strs in Machine 1.
# Implement the encode and decode methods.
# Note:
# The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
# Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
# Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string.
"""
# the trick is delimiter that is not valid ascii
# \u03F4 is Greek letter ϴ
if len(strs) == 0: return None
return '\u03F4'.join(strs)
# if len(strs) == 0:
# return chr(258)
# return chr(257).join(x for x in strs)
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings.
"""
return [] if s is None else s.split('\u03F4')
# if s == chr(258):
# return []
# return s.split(chr(257))
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(strs))
|
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 13:56:39 2018
@author: Roland
"""
# WORK STREAM =================================================================
# Generate population --> Grow Food --> Move Individuals --> Eat Food
# IMPORT PACKAGES =============================================================
import random
import matplotlib.pyplot as plt
# CREATE A DICTIONARY FOR OUR POPULATION ======================================
# As part of the construction process we will use a dictionary to keep record
# of which statistic is stored in each index for our individuals:
ind_info = {
"name":0,
"x_pos": 1,
"y_pos":2,
"max_energy":3,
"curr_energy":4,
"speed":5,
"eaten":6,
"control":7}
# Now we can quickly determine which index to use when coding. For example, if
# we want to reference the energy of the individual, we simply type:
ind_info["curr_energy"]
#... and this gives us the index we need to use!
# GENERATE OUR POPULATION =====================================================
# Create a function to generate our population. We will create lists and then
# zip them into a list of tuples:
def spawnPopulation(popSize, me):
name = list(range(popSize))
x_pos = [0] * popSize
y_pos = [0] * popSize
max_energy = [me] * popSize # <- to be kept constant
curr_energy = max_energy[:] # <- to be updated as the individual moves
speed = [1] * popSize
eaten = [0] * popSize # <- indicate whether the individual has eaten
control = [me] * popSize # <- measures whether energy just goes up because of the lower bound
# Pull together our population using zip()
population_zip = zip(name, x_pos, y_pos, max_energy, curr_energy, speed, eaten, control)
# And create a list of nested lists
population = [list(l) for l in population_zip]
#print("COMPLETED - SPAWNING POPULATION")
return(population)
# -------------------------------------S---------------
# How do we reference individuals in the population?
# population[0] # <- pulls the first individual
# population[0][ind_info["name"]] # <- pulls the first individual's name
# ----------------------------------------------------
# SIMULATE MOVING =============================================================
# WE NEED TO ADJUST THIS TO ADD SOME SORT OF "SENSE" TO THE INDIVIDUALS MOVEMENT
# We need to shift the x or y coordinate by 1/-1 at each step.
# We'll define a move() function:
def move(population):
""" Moves our individuals in a random direction and then reduces their energy
by 1. This function takes the population list as an argument. """
# For each individual we determine an axis to move on and a direction to move:
# Initialize empty lists:
axis = []
direction = []
# Loop through the population:
for i in range(len(population)):
axis.append(random.randint(1,2)) # <- randomize 1 or 2 and use this as an indexed references
if random.randint(0,1) == 1: # <- This if-else clause is probably not the best method
direction.append(1)
else:
direction.append(-1)
# Now use these to update population and 'move' our individuals!
for i in range(len(population)):
# Only move individuals who have not eaten this round and who still have energy:
if population[i][ind_info["eaten"]] == 0 and population[i][ind_info["curr_energy"]] > 0:
population[i][axis[i]] = population[i][axis[i]] + direction[i]
# We also need to reduce the energy of our individuals.
# We can use our dictionary ind_info to reference the positions!
# This means we can reference specific charactersistics of our individuals
# without using ugly indexes (and getting all confused when we come back to
# look at our code)!
population[i][ind_info["curr_energy"]] = population[i][ind_info["curr_energy"]] - 1
# Dirty fix for this movement off the map
# We say that any creature that tries to move "off" the map, moves on the same axis
# but turns around and moves the other way. That way we can fix it by just adding 2
# to any x or y values that are less than zero.
for i in range(len(population)):
if population[i][ind_info["x_pos"]] < 0:
population[i][ind_info["x_pos"]] = population[i][ind_info["x_pos"]] + 2
if population[i][ind_info["y_pos"]] < 0:
population[i][ind_info["y_pos"]] = population[i][ind_info["y_pos"]] + 2
#print("COMPLETED - MOVING POPULATION")
return(population)
# START OF DAY PHASE ==========================================================
# We start by simulating the food.
# We create a list of tuples containing the coordinates for each piece of food.
# We can create a function to make this a little tidier:
def grow_food(foodCount, mapSize):
""" Samples x and y coordinates within the range of the map and then
uses these value to create tuples to act as coordinates for food """
food_x = []
food_y = []
for i in range(foodCount):
food_x.append(int(random.uniform(0, mapSize + 1)))
food_y.append(int(random.uniform(0, mapSize + 1)))
food_zip = zip(food_x, food_y)
food = [list(l) for l in food_zip]
# Give a visual of where our food has grown:
# plt.scatter(*zip(*food), color = "green")
# plt.show()
#print("COMPLETED - GROWING FOOD")
return(food)
# FOOD CONSUMPTION ============================================================
# We need to loop through our population and check each food location to see if
# anyone has found something to eat.
def eatFood(p, f):
""" Loops through the population to get the (x,y) loc for each individaul and
compares them to the (x,y) locations of all the remaining food. If there is a match
then the food is eaten (removed from the food list) and the eaten status of the
individual is updated. """
for i in range(len(p)):
# Skip any individuals who have already eaten this round:
if p[i][ind_info["eaten"]] == 1:
continue
# Now for individuals who have not yet eaten:
xloc = p[i][ind_info["x_pos"]] # <- get x location of current individual
yloc = p[i][ind_info["y_pos"]] # <- get y location of current individual
loc = [xloc, yloc] # <- combine to create a complete location
# Now loop through each piece of food to see if we get a match
for j in range(len(f)):
if loc == f[j]:
p[i][ind_info["eaten"]] = 1 # <- update the eaten status for the individual
p[i][ind_info["curr_energy"]] = 0 # <- reduce energy to 0 as its not needed
del(f[j]) # <- remove the food from the map
break
global population
population = p
global food
food = f
#print("COMPLETED - EATING FOOD")
# UPDATE DEAD/ALIVE STATUS ====================================================
def killIndividuals(p):
""" Deletes any individuals who are both out of energy and did not find food
to eat this round. """
# Initialize our death records
death_records = []
for i in range(len(p)):
# Check if the individual is out of energy AND has not eaten this round:
if p[i][ind_info["curr_energy"]] == 0 and p[i][ind_info["eaten"]] == 0:
death_records.append(i) # <- if so, add this individual to the death records
# Figure out who the survivors are via the death records:
survivors = set(range(len(p))).difference(death_records)
# Update the global population list:
global population
population = [p[s] for s in survivors]
#print("COMPLETED - MORTICIAN'S REPORT")
# RESET INDIVIDUALS ===========================================================
# At the end of the day all the surviving members of the population head back to
# camp at (0,0). We assume that all indivduals who ate make it back to camp safely
# and without loss of energy.
def returnToCamp(p):
""" Resets the (x,y) position, energy level and eaten status of the population. """
for i in range(len(p)):
p[i][ind_info["curr_energy"]] = p[i][ind_info["max_energy"]]
p[i][ind_info["x_pos"]] = 0
p[i][ind_info["y_pos"]] = 0
p[i][ind_info["eaten"]] = 0
return(p)
# MUTATIONS ===================================================================
# For each new child, we give a chance to mutate their characteristics.
def mutate(c):
# Mutate maximum energy:
mutation_result = random.uniform(0,1)
if mutation_result < 0.1:
c[ind_info["max_energy"]] = c[ind_info["max_energy"]] - 1
if mutation_result > 0.9:
c[ind_info["max_energy"]] = c[ind_info["max_energy"]] + 1
return(c)
# REPRODUCTION ================================================================
# We need to add a reproduction process. Individuals will "reproduce" if they
# successfully eat food. The reproduction is carried out by creating a replica
# of the parent. For now, given there is no mutation in the program we will just
# directly copy the attributes of the parent.
def reproduce(p):
global population_records
# Initialize our birth records:
birth_records = []
# loop through each individual
for i in range(len(p)):
# check if the individual has eaten:
if p[i][ind_info["eaten"]] == 1:
# if so, create a replica:
child = p[i][:]
# mutate:
child = mutate(child)
# update the name:
child[ind_info["name"]] = population_records[-1] + 1
# and update the population records
population_records.append(population_records[-1] + 1)
# add child to the population
birth_records.append(child)
# Add new births to population:
p = p + birth_records
# Print our completion message:
#print("COMPLETED - REPRODUCTION")
# Finally return our new population:
return(p)
# PULL IT ALL TOGETHER ========================================================
# parameters
kMapSize = 15 # <- Only set up for a square plane right now (x = y)
kPopSize = 100
kFoodCount = 100
# Spawn our population
population = spawnPopulation(kPopSize, me = 30)
# Create a replica that we store as the initial population. We can use this to
# compare to the final population to see how the natural selection process works:
initial_population = population[:]
# Generate our birth records:
population_records = list(range(kPopSize))
average_energy = []
for days in range(1000):
# Keep a tracker of how the energy progress through the days
average_energy.append(sum(list(zip(*population))[ind_info["max_energy"]]) / len(population))
# Give the user an output of what day we're on:
print(days)
# Reproduce!
population = reproduce(p = population)
# Return to camp
population = returnToCamp(p = population)
# Grow Food
food = grow_food(kFoodCount, kMapSize)
# Only run while individuals still have energy AND food still exists
while sum(list(zip(*population))[ind_info["curr_energy"]]) > 0 and len(food) > 0:
# Move population
population = move(population)
# Eat food
eatFood(p = population, f = food)
# Kill 0 energy individuals
killIndividuals(p = population)
# PLOTTING ====================================================================
# Compare the starting energy of all individuals to the final energy:
plt.hist(list(zip(*population))[ind_info["max_energy"]])
plt.hist(list(zip(*initial_population))[ind_info["max_energy"]], color = "red")
# And a tracker of how the average energy develops as the days go on:
plt.plot(average_energy)
# PLAYGROUND ==================================================================
# How do we play around with speed?
# We need a downside to speed (it costs more energy)
# If someone has 2 speed, they get 2 moves on each move turn. We need to search for food
# after each movement (since the individual won't just move past food because they have
# an extra move turn).
|
import speech_recognition as sr
import turtle
from word2number import w2n
r = sr.Recognizer()
skk = turtle.Turtle()
#Opening file and including basic libraries
file = open('output.py','w')
file.write("import turtle\n")
file.write("skk = turtle.Turtle()\n")
skk.pensize(5)
file.write("skk.pensize(5)\n")
skk.shape('turtle')
file.write("skk.shape('turtle')\n")
#list for colors and numbers in text
colors = ['red','black','blue','green']
num_rep=['one','two','three','four','five','six','seven','eight','nine','zero',
'eleven','twelve','thrteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen',
'twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'
'hundred','thousand']
#taking voice input in loop
while(1):
with sr.Microphone() as source:
text=''
print("Speak Anything :")
audio = r.listen(source, phrase_time_limit=10)
try:
text = r.recognize_google(audio)
print("You said : {}".format(text))
except:
print("Sorry could not recognize what you said")
words=text.split()
size=len(words)
i=0
while i<size:
words[i]=words[i].lower()
i+=1
print(words)
i=0
while i<size:
if(words[i]=='forward' and i<size):
i+=1
#if(not words[i].isnumeric() and not words[i] in num_rep):
#continue
if(words[i]=='by' or words[i]=='to'):
i+=1;
if(words[i].isnumeric()):
number1=int(words[i])
i+=1
else:
s=''
if(words[i] in num_rep):
i+=1
while(i<size and words[i] in num_rep):
s.append(words[i]+' ')
i+=1
i-=1
if(s==''):
continue
number1=w2n.word_to_num(s)
skk.forward(number1)
file.write("skk.forward({})\n".format(number1))
elif(words[i]=='backward'):
i+=1
if(not words[i].isnumeric()):
i+=1
if(words[i].isnumeric()):
number1=int(words[i])
i+=1
else:
i-=1
s=''
if(words[i] not in num_rep):
i+=1
while(i<size and words[i] in num_rep):
s.append(words[i]+' ')
i+=1
i-=1
number1=w2n.word_to_num(s)
skk.backward(number1)
file.write("skk.backward({})\n".format(number1))
elif(words[i]=='left' or words[i]=='lift'):
i+=1
if(i>=size):
number1=90
elif(not words[i].isnumeric()):
number1=90
elif(words[i].isnumeric()):
number1=int(words[i])
i+=1
else:
s=''
if(words[i] in num_rep):
i+=1
while(i<size and words[i] in num_rep):
s.append(words[i]+' ')
i+=1
i-=1
number1=w2n.word_to_num(s)
skk.left(number1)
file.write("skk.left({})\n".format(number1))
elif(words[i]=='right' or words[i]=='write'):
i+=1
if(i>=size or (words[i] not in num_rep and not words[i].isnumeric())):
number1=90
elif(words[i].isnumeric()):
number1=int(words[i])
i+=1
else:
s=''
number1=0
if(words[i] in num_rep):
i+=1
while(i<size and words[i] in num_rep):
s.append(words[i]+' ')
i+=1
i-=1
number1=w2n.word_to_num(s)
skk.right(number1)
file.write("skk.right({})\n".format(number1))
elif(words[i]=='pen'):
i+=1
if(words[i]=='up'):
skk.penup()
file.write("skk.penup()\n")
elif(words[i]=='down'):
skk.pendown()
file.write("skk.pendown()\n")
elif(words[i]=='colour' or words[i]=='color'):
i+=1
if(words[i]=='to' or words[i]=='it'):
i+=1;
if(words[i] not in colors):
skk.color("black")
file.write('skk.color("black")\n')
i+=1
else:
skk.color(words[i])
file.write('skk.color("{}")\n'.format(words[i]))
elif(words[i]=='go' or (words[i]=='move' and words[i+1]=='to')):
if(words[i+1]=='to'):
i+=2
else:
i+=1
if(words[i].isnumeric()):
number1=int(words[i])
i+=1
if(words[i]=='comma' or words[i]=='and'):
i+=1;
if(words[i].isnumeric()):
number2=int(words[i])
i+=1
skk.goto(number1,number2)
elif(words[i]=='dot'):
if(i>0 and words[i-1] in colors):
cur_cul=words[i-1]
while(i<size and not words[i].isnumeric()):
i+=1
skk.dot(int(words[i]),cur_cul)
file.write('skk.dot()\n')
elif(words[i]=='stamp'):
skk.stamp()
file.write('skk.stamp()\n')
elif(words[i]=='shape' or words[i]=='make' or words[i]=='change'):
i+=1
while(words[i]=='to' or words[i]=='it'):
i+=1;
skk.shape(words[i])
file.write('skk.shape("{}")\n'.format(words[i]))
elif(words[i]=='end' or words[i]=='and'):
break
else:
i+=1
if(i<size):
file.close()
break
turtle.done()
|
#!/usr/bin/env python
# coding=utf-8
import threading
import time
# 线程共享全局变量
g_cnt = 100
def start_routine_a():
global g_cnt
g_cnt = 1024
print 'routine a %d' % g_cnt
def start_routine_b():
global g_cnt
print 'routine b %d' % g_cnt
def start_routine_c(arg):
arg.append(4)
print arg
def start_routine_d(arg):
print arg
if __name__ == '__main__':
g_list = [1, 2, 3]
print 'global cnt = %d' % g_cnt
t1 = threading.Thread(target=start_routine_a)
t2 = threading.Thread(target=start_routine_b)
t1.start()
time.sleep(1)
t2.start()
t3 = threading.Thread(target=start_routine_c, args=(g_list,))
t4 = threading.Thread(target=start_routine_d, args=(g_list,))
t3.start()
time.sleep(1)
t4.start()
|
#!/usr/bin/env python
# coding=utf-8
# value1 can be access by 'from private import *'
value1 = 100
# _value2 can not be access by 'from private import *'
_value2 = 200
class Person():
def __init__(self):
self.__age = 9
self.__name = 'anonymous'
def get_age(self):
print '%s age is %s' % (self.__name, self.__age)
def set_age(self, n):
print 'set %s age to %s' % (self.__name, n)
self.__age = n
p = Person()
# dir(p)
# 可以看到私有的属性被改名了
# _Person__age, _Person__name
# print dir(p)
p.get_age()
p.set_age(911)
p.get_age()
|
#!/usr/bin/env python
# coding=utf-8
import urllib
import urllib2
# using baidu to search keyword
# url prefix
tmp_url = "http://www.baidu.com/s"
# enter the keyword for searching
keyword = raw_input("Enter the keyword: ")
# encode the keyword for url
query = {'wd': keyword}
kw = urllib.urlencode(query)
# baidu search url format
url = tmp_url + "?" + kw
# headers for the reqest
headers = {"User-Angent": "Mozilla 5.10"}
# url request and open
request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request)
# read from response
html = response.read()
print html
# save the result
filename = keyword + ".html"
with open(filename, "w") as fn:
fn.write(html)
|
#!/usr/bin/env python
# coding=utf-8
# 三种形式多任务: 进程,线程,协程
# 本例即为协程
# 只要task1和task2切换足够快
# 就相当于有两个任务同时运行
def task1():
while True:
print('task one running---')
yield None
def task2():
while True:
print('task two running+++')
yield None
t1 = task1()
t2 = task2()
# main loop
while True:
# __next__ python3 feature
next(t1) # t1.__next__()
next(t2) # t2.__next__()
|
from .neuron import Neuron
import numpy as np
class IFNeuron(Neuron):
firing_threshold = 0
current_potential = 0
def __init__(self, firing_threshold):
self.firing_threshold = firing_threshold
def reset(self, inputShape):
"""
Resets the neuron to resting state
with the given size of `input`
"""
self.current_potential = np.zeros(inputShape)
def compute(self, input):
"""
Integrate and Fire if `current_potential` is
more than `firing_threshold`
TODO
"""
pass |
import os,sys
#Name of the first level folder
val = input ("Enter the Parent folder:")
#confirmation if the name is correct
print (val)
#change accoring to your preference
path = ("C:\\Users\\darshanr\\Documents\\PythonTesting\\Testfolder\\"+str(val))
#complete path of where the folder will be created
print ("Folder Created at:",path)
#enter if the path does not exist
if not os.path.exists(path):
#create folder at the specified path
os.mkdir(path)
print("The current working directory is %s" % path)
try:
#open txt with folder names
with open("Folder_Names.txt", 'r') as x:
for line in x:
#strip and replace all unwanted symbols
line = line.strip('\n')
line = line.replace(' ','_')
line = line.replace(',','_')
line = line.replace(':','_')
#adding folder name to the existing path
path_new = (path+"\\"+str(line))
print (path_new)
#create subfolder in the path provided by er
os.mkdir(str(path_new))
path_new = path
x.close()
except OSError as e:
print(e)
print("TC Directory not created")
else:
print ("Path exists, choose another path") |
from typing import List
import heapq
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
res = []
for num in nums:
if len(res) < k:
heapq.heappush(res, num)
elif num > res[0]:
heapq.heappop(res)
heapq.heappush(res, num)
return heapq.heappop(res)
S = Solution()
numbers = [1]
target = 1
print(S.findKthLargest(numbers, target))
|
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n // 2):
for j in range((1 + n) // 2):
(
matrix[i][n - 1 - j],
matrix[n - 1 - j][n - 1 - i],
matrix[n - 1 - i][j],
matrix[j][i],
) = (
matrix[j][i],
matrix[i][n - 1 - j],
matrix[n - 1 - j][n - 1 - i],
matrix[n - 1 - i][j],
)
print(matrix)
s = Solution()
s.rotate(matrix=[[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]])
|
from typing import List
"""
交换过的元素还需要做判断
"""
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i, left, right = 0, 0, len(nums) - 1
while i <= right:
if i < left:
i += 1
elif nums[i] == 0:
nums[i], nums[left] = nums[left], nums[i]
left += 1
elif nums[i] == 2:
nums[i], nums[right] = nums[right], nums[i]
right -= 1
else:
i += 1
return nums
S = Solution()
print(S.sortColors([2, 0, 2, 1, 1, 0]))
|
# The data we need to retrieve
# 1. The total number of votes casted.
# 2. A complete list of candidates who received votes.
# 3. The percentage of votes each candidate won.
# 4. The total number of votes each candidate won.
# 5. The winner of the election based on popular vote.
import csv
import os
'''file_to_upload=os.path.join("Resources", "election_results.csv")'''
'''file_to_load='Resources/election_results.csv'
election_data=open(file_to_load, 'r')
#To do: Perform analysis
election_data.close()'''
'''with open(file_to_upload)as election_data:
#To do: Perform analysis
print(election_data)'''
'''file_to_save=os.path.join("analysis", "election_analysis.txt")
with open(file_to_save, "w") as txt_file:
txt_file.write("Arapahoe, ")
txt_file.write("Denver, ")
txt_file.write("Jefferson")
txt_file.write("Arapahoe, Denver, Jefferson")
txt_file.write("Counties in the election\n-------------------------------------\n")
txt_file.write("Arapahoe\nDenver\nJefferson")'''
file_to_load=os.path.join("Resources", "election_results.csv")
file_to_save=os.path.join("analysis", "election_results.txt")
total_votes=0
total=0
candidate_options=[]
candidate_votes={}
county_options=[]
county_votes={}
winning_candidate=""
winning_count=0
winning_percentage=0
county_winning_name=""
county_winning_count=0
county_winning_percentage=0
with open(file_to_load) as election_data:
file_reader=csv.reader(election_data)
headers=next(file_reader)
'''print(headers)'''
for row in file_reader:
total_votes+=1
candidate_name=row[2]
county_name=row[1]
if(candidate_name not in candidate_options):
candidate_options.append(candidate_name)
candidate_votes[candidate_name]=0
candidate_votes[candidate_name]+=1
if(county_name not in county_options):
county_options.append(county_name)
county_votes[county_name]=0
county_votes[county_name]+=1
#print(row)
with open(file_to_save, "w") as txt_file:
total_vote_summary= (f"Election Results\n"
f"------------------------------\n"
f"Total Votes: {total_votes:,}\n"
f"------------------------------\n")
print(total_vote_summary, end="")
txt_file.write(total_vote_summary)
county_vote_summary = (f"County Votes:\n")
print(county_vote_summary)
txt_file.write(county_vote_summary)
for county in county_votes:
county_vote_count = county_votes[county]
count_percenatge = float(county_vote_count)/float(total_votes) * 100
county_summary = f"{county}: {count_percenatge:.1f}% ({county_vote_count:,})\n"
print(f"{county}: {count_percenatge:.1f}% ({county_vote_count:,})\n")
txt_file.write(county_summary)
if(county_vote_count > county_winning_count and count_percenatge > county_winning_percentage):
county_winning_count = county_vote_count
county_winning_percentage=county_winning_percentage
county_winning_name = county
county_max_summary = (
f"---------------------------\n"
f"Largest County Turnout: {county_winning_name}\n"
f"---------------------------\n"
)
txt_file.write(county_max_summary)
print(county_max_summary)
for candidate in candidate_votes:
votes = candidate_votes[candidate]
vote_percentage = float(votes) / float(total_votes) * 100
candidate_results_summary = (f"{candidate}: {vote_percentage:.1f}% ({votes:,})\n")
print(f"{candidate}: {vote_percentage:.1f}% ({votes:,})\n")
txt_file.write(candidate_results_summary)
if (votes > winning_count) and (vote_percentage > winning_percentage):
winning_count = votes
winning_percentage= vote_percentage
winning_candidate=candidate
winning_candidate_summary= (
f"------------------------------\n"
f"Winner: {winning_candidate}\n"
f"Winning vote count: {winning_count:,}\n"
f"Winning percentage: {winning_percentage:.1f}%\n"
f"------------------------------\n"
)
txt_file.write(winning_candidate_summary)
print(winning_candidate_summary)
|
"""
Contains the main loop of the game and core functions
"""
import sys
sys.path.append('../')
from command_line_parser.textParser import *
from game_state import *
import misc.miscDescriptions
def main_main():
print "Welcome to The Haunted Python Mansion"
print "Main Menu"
print "[1] Start New Game"
print "[2] Load Game"
print "[3] Exit"
return raw_input(">>")
def select_saved_games():
print "Here's a list of saved games. Pick one"
# display list of saved game files
for file_name in os.listdir('../saved_games/'):
if os.path.isdir("../saved_games/"+file_name) is True:
print file_name
# prompt player the file name and do file name input validation
file_name_matched = False
prompt_counter = 3
while file_name_matched is False and prompt_counter > 0:
selected_file_name = raw_input(">>")
for file_name in os.listdir('../saved_games/'):
if file_name == selected_file_name:
return selected_file_name
prompt_counter -= 1
# if player enter unmatched name for 3 times, let one decide keep retrying or load new game
if prompt_counter is 0:
print "no matching game state found for 3 tries."
print "retry to enter game state name? enter yes to retry. if not yes, will start new game."
retry_yes_no = raw_input(">>")
if retry_yes_no.lower() == "yes":
prompt_counter = 3
else:
print retry_yes_no.lower()
return None
def play(game_state):
text_parser = TextParser()
print misc.miscDescriptions.introduction
game_state.display_current_room()
while True:
user_input = raw_input(">>")
if user_input.lower().replace(" ","") == "loadgame":
# confirms with the user that this really is desired
print "If the game is not saved, this current game state will be deleted."
print "Are you sure to load game? enter yes to loadgame."
load_yes_no = raw_input(">>")
if load_yes_no.lower() != "yes":
game_state.display_current_room()
continue
else:
game_state = GameState(select_saved_games())
game_state.display_current_room()
continue
parsed_command = text_parser.getCommand(user_input, game_state.get_current_room(), game_state.player)
if parsed_command and "error" not in parsed_command.keys():
if game_state.player.debug:
print parsed_command
game_state.execute_action(parsed_command)
elif "error" in parsed_command.keys():
print parsed_command["error"]
else:
print "I don't understand that"
if __name__ == "__main__":
menu_input = main_main()
if menu_input == '1':
game = GameState()
play(game)
elif menu_input == '2':
selected_game_save = select_saved_games()
game = GameState(selected_game_save)
play(game)
elif menu_input == '3':
exit()
|
# Unit8_불과 비교, 논리 연산자 알아보기
# 연습문제: 합격 여부 출력하기(practice_operator.py)
korean = 92
english = 47
mathematics = 86
science = 81
print(korean >= 50 and english >= 50 and mathematics >= 50 and science >= 50)
# 심사문제: 합격 여부 출력하기(judge_comparison_logical_operator.py)
# 표준 입력: 90 80 85 80
# 표준 출력: False
korean, english, mathematics, science = map(int, input().split())
print(korean >= 90, english > 80, mathematics > 85, science >=80) |
# 함수가 호출될 때마다 1씩 감소
def countdown(n):
number = n + 1 # 입력받은 숫자부터 시작해 값이 1씩 감소해야 하니까 1을 더함.
def count():
nonlocal number # countdown 함수의 지역변수 number 값을 변경할 수 있도록 만들어줌.
number -= 1
return number
return count # 함수를 반환할 때는 이름만 반환
n = int(input())
c = countdown(n) # 여기서 c는 클로저 함수 / 함수 count를 둘러싼 환경(지역변수, 코드 등)을 유지하고 있다가 함수가 호출될 때 꺼내서 사용!
for i in range(n):
print(c(), end=' ') |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 2 22:09:01 2021
@author: JAQUELINA SANCHEZ
Implementacion del metodo de Newton Raphson
"""
def funcionFX(x):
return (x**4-6.4*(x**3)+6.45*(x**2)+20.538*x-31.752)
#derivada 1 de f(x)
def primerDerivada(x):
return (4*(x**3)-19.2*(x**2)+12.9*x+20.538)
#derivada 2 de f(x)
def segundaDerivada(x):
return (12*(x**2)-38.4*x+12.9)
def funcionGX(x):
funcion = funcionFX(x)
primeraDer = primerDerivada(x)
segundaDer = segundaDerivada(x)
return (x-(funcion*primeraDer)/((primeraDer**2)-funcion*segundaDer))
def errorA(actual,anterior):
return abs((actual-anterior)/actual)*100
def criterioConvergencia(derivada):
if abs(derivada) < 1:
return True
else:
return False
def RalstonRabinowitz(x,e,n):
print("\t\t Iniciando método de Ralston Rabinowitz")
i =0
actual = x
while i < n:
gX = funcionGX(actual)
fX = funcionFX(actual)
derF1 = primerDerivada(actual)
derF2 = segundaDerivada(actual)
error = errorA(gX,actual)
print("i={i},x={x:.7f},f(x)={fX:.7f},f'(x)={fx1:.7f},f''(x)={fx2:.7f},error = {e:.7f}".format(x=actual,fx1=derF1,fx2=derF2,fX=fX,e=error,i=i))
if error < e:
print("Se ha encontrado una raiz en {0:.7f}".format(gX))
break
actual = gX
i = i+1
RalstonRabinowitz(3.28,0.1,200) |
import string
import re
def universal_finder(filename, find_list):
# filename is name of receipt txt file from receipt image
# find_list is list of target words
marked_list = [] # List of lines that contains target words
found_words = [] # List of target words that were triggered
# Open file, read line by line and look for target words
# Add entire line to marked_list if line contains target word
file = open(filename, 'r')
lines = file.readlines()
for i in range(0, len(lines)):
for word in find_list:
if word in lines[i]:
marked_list.append(lines[i])
found_words.append(word)
file.close()
return marked_list, found_words
def find_store_name(filename):
# Just looks at the first line of the receipt txt
# Pray that it's there
file = open(filename, 'r')
store_name = file.readline()
file.close()
print(store_name.lower())
return store_name.lower() # Turns it lowercase for easier processing
def find_payment_method(filename):
# Usually only one instance of one of the target words
# Doesn't handle case if there is more than of these target words in the file
suggestive_words = ["CASH", "Cash", "CREDIT", "Credit", "DEBIT", "Debit"]
total_list, payment_method = universal_finder(filename, suggestive_words)
print(payment_method[0].lower())
return payment_method[0].lower()
def find_total_number(filename):
# Finds instances of target word
# Total usually shows up multiple times ie subtotal and total
# Stores these possible totals and then picks the higher one
# Doesn't work for Tesco receipts
suggestive_words = ["Total", "Paid", "total", "TOTAL"]
total_list, found_words = universal_finder(filename, suggestive_words)
confusion_matrix = [] # Stores the potential totals
# Go through the line, only keep the numbers and decimal points
for i in range(0, len(total_list)):
construct_total = []
for characters in total_list[i]:
if characters in string.digits or characters == ".":
construct_total.append(characters)
total_amount = ''.join(construct_total)
confusion_matrix.append(total_amount)
real_total_baby = max(confusion_matrix) # Picks highest total as the real total
print(real_total_baby)
return real_total_baby
'''
def numbered_dates_find(target_string):
# Linny did this magic
matches = re.findall('(\d{2}[\/ ](\d{2}|January|Jan|February|Feb|March|'
'Mar|April|Apr|May|May|June|Jun|July|Jul|August|Aug|September|'
'Sep|October|Oct|November|Nov|December|Dec)[\/ ]\d{2,4})', target_string)
return matches[0][0]
'''
def find_date(filename):
suggestive_words = ["/", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sept", "Oct", "Nov", "Dec", "January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", "November", "December",
"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST",
"SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]
total_list, found_words = universal_finder(filename, suggestive_words)
target_word = found_words[0].lower()
numbered_date = numbered_dates_find(total_list[0])
print(numbered_date)
return numbered_date
def yelpSearch(store, city="Edmonton"):
yelp_api = YelpAPI("BkeVvBepP5xWd8hfOi_Pud4wx3d1NWAx7XV_oopCygqKDNuJyE1MBr5TqGhNlBf1KM-cVcz05YsyTGkAkeVq73yTbwbER51fVxc9Qq4vGBhwtCQkjZvPP9LBkvNDXHYx")
op = yelp_api.search_query(term=store, location=city, sort_by='rating', limit = 5)
title1 = ''
title2 = ''
title = []
try:
title1=op['businesses'][0]['categories'][0]['title']
except IndexError:
print('Retailer not Recognized')
try:
title2=op['businesses'][0]['categories'][1]['title']
except IndexError:
pass
title.append(title1)
title.append(title2)
# Testing and debugging
testing_file = tesseract('receipt8.jpg')
print('Total Paid: ')
paid = find_total_number(testing_file)
print('Payment Method: ')
method = find_payment_method(testing_file)
print('Store Name: ')
store = find_store_name(testing_file)
print('Transaction Date: ')
date = find_date(testing_file)
|
def binary_exponentiation(x,n,m):
if(n == 0):
return 1
elif(n%2 == 0): # IF n is even
return binary_exponentiation(x**2 % m, n/2, m)
else: # if n is odd
return (x * binary_exponentiation(x**2 % m, (n-1)/2, m)) % m
def binary_exponentiation_it(x,n,m):
result = 1
while(n > 0):
if(n%2 == 1): # if n is odd
result = (result*x) % m
x = x**2 % m
n //= 2
return result
x = binary_exponentiation(3,10,51)
print(x) |
from urllib.parse import urlparse
from urllib.request import Request, urlopen
def read_text_method(request):
"""Overwrites the default method for reading text from a URL or file to allow :class:`urllib.request.Request`
instances as input. This method also raises any :exc:`urllib.error.HTTPError` exceptions rather than catching
them to allow us to handle different response status codes as needed."""
use_http = isinstance(request, Request) or urlparse(request).scheme != ''
if use_http:
with urlopen(request) as f:
return f.read().decode('utf-8')
else:
with open(request) as f:
return f.read()
|
import pandas as pd
csv = 'btc'
def pandasclean(csv):
df = pd.read_csv('cryptodata/'+ csv +'usd.csv',parse_dates=['Date'],usecols=[1,2,3,4,5])
df = df.set_index('Date').sort_index(ascending=True)
df.dropna(inplace=True)
return df
print(pandasclean(csv)) |
# -*- coding: utf-8 -*-
the_count =[1, 2, 3, 4, 5]
fruits = ['apples', 'orange', 'pears', 'apricots']
change =[1, 'pennies', 2, 'dimes', 'quarters']
# This first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits: #遍历列表
print "A fruit of type: %s" % fruit
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change :
print "I got %r" %i
# we can also build list, first start with an empty one
# elements = []
elements = range(0,6) #直接给的是字符串格式的元素
elements[3:3] = ['insert'] #0:3直接将前三个覆盖;3:3将插入第三个之后
lenght=len (elements) #len() 查询列表有几个元素
print "this elements has %d elements" %lenght
# then use the range function to do 0 to 5 counts
#for i in range(0, 6):
#print "Adding %d to the list." %i
# append is a function that lists understand
#elements.append(i) #往列表尾部里增加元素
# now we can print them out too
for i in elements: #遍历列表
print"Element was: %r" %i
first = elements[0]
second = elements[1]
third = elements[2]
forth = elements[-1] # 倒数第一
fifth = elements[-2] #倒数第二
sixth =elements[-3]
print first, second, third, forth, fifth, sixth
|
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if "0" in next or "1" in next :
how_much = int(next)
else:
dead ("Man, learn to tyoe a mumber.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
weird_room()
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to nove the bear?"
bear_moved = False
while True:
next = raw_input("> ")
if next == "take honey":
dead("The bear looks at you then slaps your face off.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chew you leg off.")
elif next == "open door" and bear_moved:
gold_room()
else :
print "I got no idea what that means."
def weird_room():
print " Because you have take too much gold."
print " We must test you wether have qualification own the wealth."
print " Now if you do,the wealth belong you ,if not you belong here forever,no quit!"
next = raw_input("who are you?")
if "WUHU" ==next :
print " The money belong you ,my lord!"
exit(100)
elif "Your master is all" ==next:
print " yeah , my lord I have waited for you for 1000 years."
print " Behind the wall ,there are more gold."
print " Please take!"
exit (0) #exit procedure
else:
print "Thank you for stay with me ,you and gold all are belonging here."
dead("You are living the weird house for lives")
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you fiee for your life or eat your head?"
next = raw_input("> ")
if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty!")
else:
cthulhu_room()
def dead(why):
print why,"Good job!"
exit(0)
def start():
print "You are in a dark room."
print "There is door to your right and left."
print "Which one do you take?"
next = raw_input("> ")
if next == "left":
bear_room ()
elif next == "right":
cthulhu_room
else:
dead("You stumble around the room until you starve.")
start()
|
from random import randint
YourAnswer = 0
Guess = randint(0,20)
j = 10
i = 0
print("Now let's guess the numnber between 0 to 19")
while i <10 and Guess != int(YourAnswer):
print("Come on you have %d times" %j)
YourAnswer = input("please input your answer:")
if int(YourAnswer)-Guess >0:
print("Bigger!")
elif int(YourAnswer)-Guess <0:
print("Smaller!")
else:
print("Biggo ,that's right!")
i += 1
j -= 1
if Guess == int(YourAnswer):
print("Congratulaitions,your are the winner")
else:
print("I'm sorry for your missing the answer")
|
class Animal (object):
def __init__ (self,other):
self.other = other
print self.other
def show (self):
for line in self.other:
print line
def like (self):
self.mi = range(0,8)
return self.mi
# return self.other
myAnimal = Animal(["There are alot of anmimals",
"every one has there lifes",
"I love life in here"])
myAnimal.show()
class Person(object):
def __init__(self,doing):
self.doing = doing
def yourName (self):
games = self.doing.values()
print games
myPerson = Person({"zhangsan":"football","lisi":"basketball","wangwu":"volleyball"})
myPerson.yourName()
class Fish(object):
def __init__(self,fishes):
self.fishes = fishes
def EatFish(self):
j = 1
for i in self.fishes:
print " this is %d kind fish to eat ,that is %s" %(j,i)
j += 1
myFish = Fish(["hongshao Fish","qingzhen Fish","jian Fish","meng Fish"])
myFish.EatFish()
"""
Mi = range(0,7)
class Bike(object):
def __init__(self,tool):
self.tool = tool
def play(self):
for newLine in self.tool:
print newLine
a_bike = Bike(myAnimal)
a_bike.play()
"""
|
# -*- coding: utf-8 -*-
# create a mapping o f state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of status and sone cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print '_' * 10
print "NY State has:", cities['NY']
print "OR State has:", cities['OR']
# print some status
print '_' * 10
print "Michigan's abbreviation is:", states['Michigan']
print "Floridas's abbreviation is: ", states['Florida']
# do it by using the status then cities dict
print '_' *10
print "Michaigan has: ", cities[states['Michigan']]
print "Florida has: " ,cities[states['Florida']]
# print every state abbreviation
print '_' * 10
for state, abbrev in states.items():
print "%s is abbreviated %s" %(state, abbrev)
#print every city in state
print '_' *10
for abbrev, city in cities.items():
print "%s has the city %s" %(abbrev,city)
#now do both at the same time
print '_' * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" %(
state,abbrev,cities[abbrev])
print '_' *10
# safely get a abbreviation by state that might not be there
state = states.get('Texas',False)
if not state:
print "Sorry,no Texas."
# get a city with a default value
city = cities.get('TX','Does Not Exists')
print "The city for the state 'TX' is : %s" %city
mylove = {'apple':'big','orange':'soft','banana':'sweet'}
mylove['watermalon'] = 'watery'
print "I love the frite: ",mylove['watermalon']
print mylove.items() # 取出字典里的所有元素
print mylove.get('applle',4) # 取出字典里某个元素,没有显示后面的值
for a,b in mylove.items(): #for 循环取出所有知道
print " I like %s is %s" %(a,b)
print mylove.keys()
print mylove.values()
mylove.update(cities)
print mylove
print mylove.popitem()
print cmp(states,cities)
|
'''
Specification:
Class
get current temporary directory
load tar file and extract to temporary directory
overwrite tar file with temporary directory
'''
import sys
import os
import tempfile
import tarfile
import shutil
class TarfileHandler():
# Properties
tarFilePath = ''
tempDir = ''
# Methods
def extractTarToTemp(self, tarFilePath):
'''
Create a temp directory and extrac everything in the tarfile into the temp dir
This Block used return True/None to indicate whether success or not. While the
createTarfile block used raising exceptions (means should be called in try statement
with error handling instead of a if statement)
'''
tempDir = tempfile.mkdtemp()
file_name, file_ext = os.path.splitext(tarFilePath)
if file_ext == ".tar": # check if file had format .tar.gz
try:
with tarfile.open(tarFilePath, "r") as tar:
tar.extractall(path=tempDir) # untar file into same directory
return tempDir
except:
pass
finally:
pass
# delete the temp directory unless returned before (extracting succeeded)
self.deleteDir(tempDir)
def overwriteTarWithTemp(self):
''' Overwrite the loaded tarfile with the temp dir '''
if len(self.tarFilePath)>0 and len(self.tempDir)>0:
try:
with tarfile.open(self.tarFilePath, "w") as tar:
tar.add(self.tempDir, arcname = '', recursive = True)
return True
except:
return None
finally:
return None
def createTar(self, tarFilePath):
assert (not os.path.exists(tarFilePath)), 'Failed create tar file, file already exists!'
tempDir = self.createTempDir()
# Here need a try statement to exclude invalid file names
try:
with tarfile.open(tarFilePath, "w") as tar:
tar.add(tempDir, arcname = '', recursive = True)
return tempDir
except:
self.deleteDir(tempDir) # delete the old one if exists
raise ValueError('Failed create tar file, file name not valid!')
finally:
pass
def createTempDir(self):
''' Create an empty TempDir with folder source and empty folders bgm and img '''
tempDir = tempfile.mkdtemp()
#tempDir = os.path.join(tempBaseDir)#,'source')
#os.mkdir(tempDir)
os.mkdir(os.path.join(tempDir,'bgm'))
os.mkdir(os.path.join(tempDir,'img'))
return tempDir
#os.mkdir(os.path.join(self.tempDir,'source/img'))
def deleteDir(self, dir):
''''''
if os.path.exists(dir) and os.path.isdir(dir):
shutil.rmtree(dir)
# Private Methods, Be careful only for internal use!!
def getTempDir(self):
'''Get the current temporary directory'''
return tempfile.mkdtemp()
if __name__ == "__main__":
thisTar = './source/template.tar'
tarfileHandler = TarfileHandler()
print(tarfileHandler.extractTarToTemp(thisTar))
print(tarfileHandler.tempDir)
print(tarfileHandler.tarFilePath)
#tarfileHandler.overwriteTarWithTemp()
#tarfileHandler.createTempDir()
#tarfileHandler.createTar('test.tar')
#print(tarfileHandler.tempDir) |
# Time
import time
seconds = time.time()
print (seconds)
countdown = 5
while (countdown >= 0):
print (countdown)
countdown -= 1
time.sleep(1)
else:
print ("Vrmmmmm!")
# Multiplication Game
import random
print ("Welcome to the Multiplication Game\n")
# Generates two random numbers in variables.
rand1 = random.randint(1,9)
rand2 = random.randint(1,9)
# Countdown
print ("Here is the Question!")
countdown = 3
while (countdown > 0):
print (countdown)
countdown -= 1
time.sleep(1)
else:
print ("\n\n")
# Measure Initial Time
ti = time.time()
# Ask user the question
question = int(input(str(rand1) + " x " + str(rand2) + ": "))
# Measure Final Time
tf = time.time()
# Check the answer
# Correct answer, print out correct and elapsed time
if (question == rand1 * rand2):
print ("Correct")
print ("Elapsed Time: " + str(tf - ti))
else:
print ("Nice Try... Wrong answer")
'''
# (Optional) Calendar
import calendar
cal = calendar.month(2021, 2)
print (cal)
cal = calendar.TextCalendar(calendar.SUNDAY)
c = cal.formatmonth(2021,2)
print ("Here is the calendar:" )
print (c)
''' |
import SuffixTree
import TreeNode
class TreeGhost(object): #non leaf nodes in boundary path
def __init__(self, node):
self.x = TreeNode.e #x value stays the same while e increases with each iteration
self.node = node
node.ghosts.add(self)
self.start = TreeNode.e #this will determine length of node.name when ghost becomes a node
self.walked = 0
def get_index(self):
return TreeNode.e - self.x
def __repr__(self):
return str(self.number) + ": " + self.node.name |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 24 17:40:32 2018
@author: longjiemin
"""
#
from random import randint
def insertion_sort(nums):
for i in range(1,len(nums)):
for j in range(i-1,-1,-1):
if nums[i] < nums[j]:
if j == 0:
swap(0,i,nums)
continue
else:
swap(j+1,i,nums)
break
print(nums)
return nums
def swap(index1,index2,nums):
num = nums[index2]
nums[index1+1:index2+1] = nums[index1:index2]
nums[index1] = num
return nums
if __name__ == 'main':
nums = [randint(1,100) for i in range(15)]
print('nums_unsorted',nums)
print('nums_sorted',insertion_sort(nums))
nums = [randint(1,100) for i in range(1000)]
insertion_sort(nums) |
#2
#由两个堆栈组成的队列,add,poll,peek,
#问题:__repr__函数无反应
class de_list():
'''
dfsdf
'''
def __init__(self,nums):
self.stack1 = list(nums)
self.stack2 = list([])
for i in range(len(nums)-1,0-1,-1):
self.stack2.append(self.stack1[i])
def push(self,num):
self.stack1.append(num)
self.stack2 = list([])
for i in range(len(self.stack1)-1,0-1,-1):
self.stack2.append(self.stack1[i])
def poll(self):
self.stack2.pop()
self.stack1 = list([])
for i in range(len(self.stack2)-1,0-1,-1):
self.stack1.append(self.stack2[i])
def peek(self):
return self.stack2[-1]
def __repr__(self):
return self.stack2
def __str__(self):
return print(self.stack2)
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 10 11:35:25 2018
@author: longjiemin
"""
#给定一个无序数组,求出需要排序的最短子数组长度
#难度:1星
#思路:进行两次遍历,一次从左至右,一次从右至左。每一次记录遍历书中的最小值,当arr[i]>min时,意味着min值必然要一到min值的位置,记录i的位置。
#但会两个索引位置,则其切片就只需要排列的部分。
def getminlen(arr):
min_index_left = -1
min_value_left = arr[0]
for i in range(len(arr)):
if min_value_left > arr[i]:
break
else:
if min_value_left < arr[i]:
min_value_left = arr[i]
min_index_left = i
if min_index_left == -1:
print('its sorted')
return
min_index_right = -1
min_value_right = arr[len(arr)-1]
for i in range(len(arr)-1,-1,-1):
if min_value_right < arr[i]:
break
else:
if min_value_right > arr[i]:
min_value_right = arr[i]
min_index_right = i
return arr[min_index_left:min_index_right+1]
arr = [1,5,3,4,2,6,7] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 16 21:39:48 2018
@author: admin
"""
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
cur1 = pHead1
cur2 = pHead2
if cur1 is None: return cur2
if cur2 is None: return cur1
if cur1.val < cur2.val:
res = cur1
cur1 = cur1.next
else:
res = cur2
cur2 = cur2.next
res_head = res
while cur1 and cur2:
if cur1.val < cur2.val:
res.next = cur1
cur1 = cur1.next
res = res.next
else:
res.next = cur2
cur2 = cur2.next
res = res.next
if cur1:
res.next = cur1
else:
res.next = cur2
return res_head
#已通过验证,注意cur1,cur2为空的时候 |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 17 10:00:03 2017
@author: longjiemin
"""
'''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
'''
class Solution(object):
def __init__(self):
self.dict=
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in nums:
if i in a.keys():
a[i] = a[i] +1
else:
a[i] = 1
for i in a.keys():
if a[i] > len(nums)//2:
break
return i
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 20:18:35 2018
@author: admin
"""
#
#要求:时间N,空间1
#难度:一星
#思路:分析输出的特性,负累加和必然丢掉
#
#检测通过
def maxSum(nums):
max_sum = -float('inf')
cur = 0
if len(nums) == 0:
return None
for i in range(len(nums)):
cur += nums[i]
max_sum = max(max_sum,cur)
cur = cur if cur>0 else 0
return max_sum |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 19 10:05:09 2018
@author: admin
"""
#题目:
#要求:
#难度:
#思路:审题,排序数组中,不降序,分析输入数据特点,寻找三元组则先固定住一个值,(第一个值),确定固定的含义
#要点:整理清楚解题思路,再写代码
#测试:已通过
def printUniquePair(arr,target):
left = 0
right = len(arr) -1
res = []
while left < right:
if arr[left] + arr[right] == target:
res.append([arr[left],arr[right]])
left += 1
right -= 1
elif arr[left] + arr[right] < target:
left += 1
else:
right -= 1
return res
test = [-8,-4,-3,0,1,2,4,5,8,9]
print(printUniquePair(test,10))
def printUniqueTriad(arr,target):
res = []
for i in range(len(arr)-3):
left = i+1
right = len(arr) - 1
target2 = target -arr[i]
while left < right:
if arr[left] + arr[right] == target2:
res.append([arr[i],arr[left],arr[right]])
left += 1
right -= 1
elif arr[left] + arr[right] < target2:
left += 1
else:
right -= 1
return res
test = [-8,-4,-3,0,1,2,4,5,8,9]
print(printUniqueTriad(test,10)) |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 15 11:39:49 2018
@author: longjiemin
"""
#斐波拉契序列的递归与动态规划
#补充题目1,,给定一个N,代表台阶数,一次可以跨2个或1个台阶,返回多少种走法
#假设成熟的母牛每年都会生一头小母牛,并且永远不会死,每一只小母牛3年之后成熟又可以生小母牛,假设第一年有一头
#小母牛,问年后牛的数量
#要求:时间复杂度(logN)
#难度:3星
#分析:使用传统的动态规划算法只能达到0(n),可以利用矩阵的特性,通过归并运算加快特性
class f():
def f1(self,n):
if n == 1 or n ==2:
return 1
else:
res = self.mul([1,1],self.matrixpower([[1,1],[1,0]],n-2))
return res[0]
#使用 [0]*len(nums2[0])]*len(nums1) 引发了视图问题
def mul(self,nums1,nums2):
nums3 = [[0]*len(nums2[0])]*len(nums1)
for i in range(len(nums1)):
for j in range(len(nums2[0])):
list1=nums1[i]
list2 =[k[j] for k in nums2]
value = sum(map(lambda x,y:x*y,list1,list2))
print(i,j,list1,list2,value)
nums3[i][j] = value
print(nums3[i][j])
print(nums3)
return nums3
def matrixpower(self,nums1,n):
if n==1:
return nums1
elif n==2:
return self.mul(nums1,nums1)
elif n>=3:
return self.mul(self.matrixpower(nums1,n//2),self.matrixpower(nums1,n-n//2))
|
from settings import messages
import os
import random
import time
import pygame
"""
KADI is a card game played by one person vs a computer opponent
the game is quite simple, the first person to finish his/her card-hand wins
"""
# global variables
# CENTER_CARD is the card that will always be at the center of the table
CENTER_CARD = []
# DECK is the game deck of cards
# DECK = []
# PLAYERS is a list of the players in the game
PLAYERS = []
# suits is a suit of cards
# SUITS = 'SDHC'
class Card(object):
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return '{0}{1}'.format(self.suit, self.rank)
@staticmethod
def make_cards(deck):
for suit in 'SDHC':
for rank in range(1, 14):
deck.append(suit + str(rank))
list(deck)
yield Card(suit, rank)
class Human(Card):
"""
Creates the human player attributes
"""
def __init__(self, ):
class Computer(Card):
"""
computer objects
"""
def __init__(self, comp, comp_hand=None):
super(Computer, self).__init__(deck=None)
if comp_hand is None:
comp_hand = []
self.comp = comp
self.comp_hand = comp_hand
def __str__(self):
return '{0} your cards are : {1}'.format(self.comp, self.comp_hand)
def make_hand(self):
self.comp_hand.append(self.deck[-4:])
# class PlayingCard(Human, Computer, Card):
# def __init__(self):
#
#
# def human_playing_card(self):
# return self.player_hand.remove(self.deck)
#
# def comp_playing_card(self):
# pass
# class ArtificialIntelligence(Card,Computer):
# """
# Game A.I used by the computer to play
# """
# def __init__(self, comp, move):
# super(ArtificialIntelligence, self).__init__(comp)
# self.move = move
#
#
# def check_first_payer(self):
# """
# this method helps
# """
class Score(object):
def __init__(self, high_score, score=0):
self.high_score = high_score
self.score = score
def get_score(self):
return self.score
def set_score(self):
self.score = self.update_score()
def update_score(self):
self.score += 5
return self.score
def get_high_score(self):
return list(self.high_score)
@classmethod
def set_high_scores(cls, scores):
for high_score in sorted(scores[-3:]):
yield cls(high_score)
def main():
# Initializes the game
Human.name = raw_input('Enter your name')
PLAYERS.append(Human.name)
# PLAYERS.append(Computer.comp)
# # first player to play
# first_player = random.choice(PLAYERS)
#
# # getting the second player logic
# fi = 0 # obvious first index in the players list
# fpi = PLAYERS.index(first_player) # index of the player playing first
# if fpi == fi: # if the first_player's index equals the first index of PLAYERS list
# fi += 1 # then we increament fi by 1
# second_player = PLAYERS[fi] # since they are only 2 players it makes sence to give the payer 2 index fi
#
#
# print 'Congratulation, ' + first_player + 'your will have the first turn in this game'
# shuffles the card deck
# Card.make_cards()
while len(Card.deck) > 0 or len(Card.deck) <= 52:
messages("may the game begin their is no cheating" % (PLAYERS,))
# deals to the human
Human.make_hand()
# deals to the computer
Computer.make_hand()
# places the starting card in the midde of the table
CENTER_CARD.append(Card.deck[-1:])
print CENTER_CARD
print Human.player_hand
print Human.name + ' it is your turn to play'
human_playin_card = raw_input('play card:')
for equal_card in (Human.player_hand , Computer.comp_hand):
if human_playin_card is equal_card or human_playin_card[0] is equal_card[0]:
CENTER_CARD.append(Human.player_hand.remove(human_playin_card))
# if (human_playin_card[-1] or human_playin_card[-1]) in :
# call the "main" function if running this script
if __name__ == '__main__':
main()
|
import turtle
def main():
window = turtle.Screen()
mike = turtle.Turtle()
make_square(mike)
turtle.mainloop()
def make_square(mike):
length = int(input("Tamaño del cuadrado: "))
for i in range(4):
make_line_and_turn(mike,length)
def make_line_and_turn(mike,length):
mike.forward(length)
mike.left(90)
if __name__ == "__main__":
main() |
mi_diccionario = {}
mi_diccionario['proweb'] = 9
mi_diccionario['android dev'] = 9
mi_diccionario['algoritmos'] = 8
#Iterar en llaves
for key in mi_diccionario.keys():
print(key)
for value in mi_diccionario.values():
print(value)
for llave,valor in mi_diccionario.items():
print("Llave: {} , Valor: {}".format(llave,valor)) |
def merge(list, p, q, r):
left = []
for i in range(p, q + 1):
left.append(list[i])
right = []
for j in range(q + 1, r + 1):
right.append(list[j])
i = 0
j = 0
for k in range(p, r + 1):
if i < len(left) and j < len(right) and left[i] <= right[j]:
list[k] = left[i]
i = i + 1
elif i < len(left) and j < len(right) and left[i] > right[j]:
list[k] = right[j]
j = j + 1
elif i < len(left) and j >= len(right):
list[k] = left[i]
i = i + 1
elif i >= len(left) and j < len(right):
list[k] = right[j]
j = j + 1
def merge_sort(list, p, r):
if p < r:
q = (p + r) // 2
merge_sort(list, p, q)
merge_sort(list, q + 1, r)
merge(list, p, q, r)
def main():
list = [9, 7,4,2,4,6,7,1,34,67,7,7,4,2,1,56,7,8]
merge_sort(list, 0, len(list) - 1)
print(list)
if __name__ == '__main__':
main()
|
import copy
class Node:
def __init__(self, value=None):
self.value = value
self.adj_list = []
adj_count = 0
self.up = None
self.down = None
self.right = None
self.left = None
self.posx = 0
self.posy = 0
def get_value(self):
return self.value
def get_list(self):
return self.adj_list
def get_posx(self):
return self.posx
def get_posy(self):
return self.posy
def app_list(self, num):
self.adj_list.append(num)
def set_value(self, value):
self.value = value
def set_posx(self, posx):
self.posx = posx
def set_posy(self,posy):
self.posy = posy
def set_up(self, node):
self.up = node
def set_down(self, node):
self.down = node
def set_left(self, node):
self.left = node
def set_right(self, node):
self.right = node
def get_up(self):
return self.up
def get_down(self):
return self.down
def get_right(self):
return self.right
def get_left(self):
return self.left
class Board:
def __init__(self):
rows, cols = (3, 3)
self.board = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
def __getitem__(self,index1):
return self.board[index1]
def __setitem__(self,index1,node):
self.board[index1] = node
def populate_board(self, args):
x = args.split(" ")
insert_count = 0
for i in range(0, 3):
for j in range(0, 3):
node = Node(x[insert_count])
self.board[i][j] = node
self.board[i][j].set_posx(j)
self.board[i][j].set_posy(i)
if self.board[i][j].get_value() == 0:
self.zero_tile = self.board[i][j]
insert_count = insert_count + 1
for i in range(0, 3):
for j in range(0, 3):
if i == 0 and j == 0:
self.board[i][j].set_down(self.board[i+1][j])
self.board[i][j].set_right(self.board[i][j+1])
elif i == 1 and j == 0:
self.board[i][j].set_up(self.board[i-1][j])
self.board[i][j].set_down(self.board[i+1][j])
self.board[i][j].set_right(self.board[i][j+1])
elif i == 2 and j == 0:
self.board[i][j].set_up(self.board[i-1][j])
self.board[i][j].set_right(self.board[i][j+1])
elif i == 0 and j == 1:
self.board[i][j].set_down(self.board[i+1][j])
self.board[i][j].set_right(self.board[i][j+1])
self.board[i][j].set_left(self.board[i][j-1])
elif i == 1 and j == 1:
self.board[i][j].set_up(self.board[i-1][j])
self.board[i][j].set_down(self.board[i+1][j])
self.board[i][j].set_left(self.board[i][j-1])
self.board[i][j].set_right(self.board[i][j+1])
elif i == 2 and j == 1:
self.board[i][j].set_up(self.board[i-1][j])
self.board[i][j].set_left(self.board[i][j-1])
self.board[i][j].set_right(self.board[i][j+1])
elif i == 0 and j == 2:
self.board[i][j].set_down(self.board[i+1][j])
self.board[i][j].set_left(self.board[i][j-1])
elif i == 1 and j == 2:
self.board[i][j].set_up(self.board[i-1][j])
self.board[i][j].set_down(self.board[i+1][j])
self.board[i][j].set_left(self.board[i][j-1])
elif i == 2 and j == 2:
self.board[i][j].set_up(self.board[i-1][j])
self.board[i][j].set_left(self.board[i][j-1])
def get_value(self):
Node.get_value()
def print_board(self):
for i in range(0, 3):
for j in range(0, 3):
print(self.board[i][j].get_value())
def search_board(self, num):
for i in range(0, 3):
for j in range(0, 3):
value = self.board[i][j].get_value()
if int(value) == num:
temp = self.board[i][j]
return temp
def list_board(self, state):
board_list = []
for i in range(0, 3):
for j in range(0, 3):
board_list.append(state[i][j].get_value())
return board_list
def aStar(start_state, end_state):
cur_list = start_state.list_board(start_state)
end_list = end_state.list_board(end_state)
if cur_list == end_list:
print("the given start state is equal to the given end state!!")
return 0
# setting the start state to open and having no closed states yet
closed_states = []
open_states = [start_state]
# NOT SURE IF I NEED A PATH TAKEN LIST!!!
path_taken = []
#setting fNum, hNum, and gNum to 0 to start
fNum = 0
hNum = 0
gNum = 0
# setting the current state to the start state and moving it
# to the closed list
current_state = copy.deepcopy(start_state)
hNum = Manhatten(current_state, end_state)
closed_states.append(cur_list)
open_states.remove(start_state)
# While loop to iterate through states
while current_state != end_state:
# finding the "blank" or zero node on the board
node_zero = current_state.search_board(0)
# creating new states based on what directions are open
# and adding them to the open states list with their fNum values
if node_zero.get_up() != None:
#new_state = Board()
#new_state.populate_board(str(cur_list))
# copying the current state into a new state
new_state = copy.deepcopy(current_state)
# creating a temp node for the node above the 0 node
temp_node = node_zero.get_up()
# editing the new state by swapping the temp node and zero node
new_state[temp_node.posy][temp_node.posx] = node_zero
new_state[node_zero.posy][node_zero.posx] = temp_node
# generating an updated board for new state
new_state = gen_board(new_state)
# calculating the manhatten number
hNum = Manhatten(new_state, end_state)
# calculating the f number
fNum = gNum + hNum
# a way to see if the new state is in the closed and open lists
cur_list = new_state.list_board(new_state)
if cur_list == end_list:
print("match!!")
return 0
# setting match found to false
match_found = False
temp_list = []
# checking to see if current list is in closed states
if cur_list not in closed_states:
# checking to see if match found is in open states
for first,*args in open_states:
# if a match is found, match found is set to true
temp_list = first.list_board(first)
if temp_list == cur_list:
match_found = True
break
# adding the new state to the open list
if match_found == False:
open_states.append((new_state, fNum))
if node_zero.get_down() != None:
#new_state = Board()
#new_state.populate_board(str(cur_list))
# copying the current state into a new state
new_state = copy.deepcopy(current_state)
# creating a temp node for the node above the 0 node
temp_node = node_zero.get_down()
# editing the new state by swapping the temp node and zero node
new_state[temp_node.posy][temp_node.posx] = node_zero
new_state[node_zero.posy][node_zero.posx] = temp_node
# generating an updated board for new state
new_state = gen_board(new_state)
# calculating the manhatten number
hNum = Manhatten(new_state, end_state)
# calculating the f number
fNum = gNum + hNum
# a way to see if the new state is in the closed and open lists
cur_list = new_state.list_board(new_state)
if cur_list == end_list:
print("match!!")
return 0
# setting match found to false
match_found = False
temp_list = []
# checking to see if current list is in closed states
if cur_list not in closed_states:
# checking to see if match found is in open states
for first,*args in open_states:
# if a match is found, match found is set to true
temp_list = first.list_board(first)
if temp_list == cur_list:
match_found = True
break
# adding the new state to the open list
if match_found == False:
open_states.append((new_state, fNum))
if node_zero.get_right() != None:
#new_state = Board()
#new_state.populate_board(str(cur_list))
# copying the current state into a new state
new_state = copy.deepcopy(current_state)
# creating a temp node for the node above the 0 node
temp_node = node_zero.get_right()
# editing the new state by swapping the temp node and zero node
new_state[temp_node.posy][temp_node.posx] = node_zero
new_state[node_zero.posy][node_zero.posx] = temp_node
# generating an updated board for new state
new_state = gen_board(new_state)
# calculating the manhatten number
hNum = Manhatten(new_state, end_state)
# calculating the f number
fNum = gNum + hNum
# a way to see if the new state is in the closed and open lists
cur_list = new_state.list_board(new_state)
if cur_list == end_list:
print("match!!")
return 0
# setting match found to false
match_found = False
temp_list = []
# checking to see if current list is in closed states
if cur_list not in closed_states:
# checking to see if match found is in open states
for first,*args in open_states:
# if a match is found, match found is set to true
temp_list = first.list_board(first)
if temp_list == cur_list:
match_found = True
break
# adding the new state to the open list
if match_found == False:
open_states.append((new_state, fNum))
if node_zero.get_left() != None:
#new_state = Board()
#new_state.populate_board(str(cur_list))
# copying the current state into a new state
new_state = copy.deepcopy(current_state)
# creating a temp node for the node above the 0 node
temp_node = node_zero.get_left()
# editing the new state by swapping the temp node and zero node
new_state[temp_node.posy][temp_node.posx] = node_zero
new_state[node_zero.posy][node_zero.posx] = temp_node
# generating an updated board for new state
new_state = gen_board(new_state)
# calculating the manhatten number
hNum = Manhatten(new_state, end_state)
# calculating the f number
fNum = gNum + hNum
# a way to see if the new state is in the closed and open lists
cur_list = new_state.list_board(new_state)
if cur_list == end_list:
print("match!!")
return 0
# setting match found to false
match_found = False
temp_list = []
# checking to see if current list is in closed states
if cur_list not in closed_states:
# checking to see if match found is in open states
for first,*args in open_states:
# if a match is found, match found is set to true
temp_list = first.list_board(first)
if temp_list == cur_list:
match_found = True
break
# adding the new state to the open list
if match_found == False:
open_states.append((new_state, fNum))
#SORT OPEN STATES BASED ON FNUM(THE SECOND NUMBER IN THE TUPLE)
gNum = gNum + 1
sort_list(open_states)
# NOW CURRENT STATE CHANGES TO THE FIRST STATE IN THE OPEN STATES LIST
temp_tup = open_states[0]
current_state = copy.deepcopy(temp_tup[0])
# REMOVE THAT STATE AND ADD IT TO THE CLOSED STATES LIST
closed_states.append(cur_list)
open_states.pop(0)
# CHECK TO SEE IF CURRENT STATE MATCHES END STATE
if cur_list == end_list:
print("the current state is the end state!!!")
return 0
# IF NOT REPEATE PROCESS UNTIL IT DOES
def Manhatten(current_state, end_state):
hNum = 0
for i in range(0, 9):
temp_current_node = current_state.search_board(i)
temp_end_node = end_state.search_board(i)
current_posx = temp_current_node.get_posx()
current_posy = temp_current_node.get_posy()
end_posx = temp_end_node.get_posx()
end_posy = temp_end_node.get_posy()
xDiff = current_posx - end_posx
yDiff = current_posy - end_posy
if xDiff < 0:
xDiff = xDiff * -1
if yDiff < 0:
yDiff = yDiff * -1
hNum = hNum + xDiff + yDiff
return hNum
def gen_board(new_state):
new_order = []
for i in range(0, 3):
for j in range(0, 3):
value = new_state[i][j].get_value()
new_order.append(value)
new_args = " ".join(new_order)
temp = Board()
temp.populate_board(new_args)
return temp
def sort_list(tup):
tup.sort(key = lambda x: x[1])
return tup
def main():
start = "0 1 2 3 4 5 6 7 8"
end = "1 2 3 4 5 6 0 7 8"
startState = Board()
startState.populate_board(start)
endState = Board()
endState.populate_board(end)
aStar(startState,endState)
main()
|
#nodes for storing both the number and value of squares on the sudoku board
class Node:
def __init__(self, x, y, value):
self.value = value
self.x = x
self.y = y
if self.value == "0":
self.domain = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
else:
self.domain = None
def set_x(self, x):
self.x = x
def set_y(self, y):
self.y = y
def get_x(self):
return self.x
def get_y(self):
return self.y
def set_value(self, val):
self.value = val
|
'''
Data types and functions translating between the (x,y) coordinate system and
latitude/longitude coordinates.
'''
import collections
import math
EARTH_RADIUS = 6378137
point = collections.namedtuple('point', ['x', 'y'])
coordinate = collections.namedtuple('coordinate', ['lat', 'lng'])
def midDistance(coord1,coord2):
midPoint = point((lng2x(coord1.lng)+lng2x(coord2.lng))/2,(lat2y(coord1.lat)+lat2y(coord2.lat))/2)
return mercPoint2Coord(midPoint)
def coordDistance(coord1,coord2):
dlon=coord2.lng-coord1.lng
dlat=coord2.lng-coord1.lng
a=(math.pow(math.sin(dlat/2),2)+math.cos(coord1.lat)*math.cos(coord2.lat)*(math.pow(math.sin(dlon/2),2)))
c=2*math.atan2(math.sqrt(a),math.sqrt(1-a))
d=EARTH_RADIUS*c
return math.fabs(d)
def deg2rad(deg):
return deg * math.pi / 180.0
def rad2deg(rad):
return rad * 180.0 / math.pi
def x2lng(x):
return rad2deg( x/EARTH_RADIUS )
def lng2x(lng):
return deg2rad(lng) * EARTH_RADIUS
def y2lat(y):
return rad2deg( (2.0*math.atan(math.exp(y / EARTH_RADIUS))-math.pi/2.0) )
def lat2y(lat):
return math.log( math.tan ( math.pi / 4.0 + deg2rad(lat) / 2.0 ) ) * EARTH_RADIUS
# return 180.0/math.pi*math.log(math.tan(math.pi/4.0+a*(math.pi/180.0)/2.0))
def coord2MercPoint(coord):
return point(lng2x(coord.lng), lat2y(coord.lat))
def mercPoint2Coord(pt):
return coordinate( y2lat(pt.y), x2lng(pt.x))
|
from typing import Any, Callable
from fpe.asserts import AssertNonCallable, AssertWrongArgumentType
def flip(func: Callable[[Any, Any], Any]) -> Callable:
"""Decorator swaps arguments provided to decorated function.
Thus flip(f)(x, y) == f(y, x)
Borrowed from flip :: (a -> b -> c) -> b -> a -> c
"""
# only callable
assert callable(func), AssertNonCallable()
def flipped(first: Any, second: Any) -> Any:
"""Swapping provided arguments to given function.
Thus f(x, y) -> f(y, x)
"""
return func(second, first)
flipped.__name__ = getattr(func, "__name__", "Unknown")
if hasattr(func, "__doc__"):
flipped.__doc__ = getattr(func, "__doc__")
return flipped
def even(num: int) -> bool:
"Return True if given num is even, otherwise False"
# only int
assert isinstance(num, int), AssertWrongArgumentType("int")
return not (num % 2)
def odd(num: int) -> bool:
"Return True if given num is odd, otherwise False"
# only int
assert isinstance(num, int), AssertWrongArgumentType("int")
return bool(num % 2)
|
__author__ = "Shashwat Tiwari"
__email__ = "[email protected]"
class Solution:
def get_pascal_triangle(self, n):
line = [[0 for i in range(n+1)] for j in range(n+1)]
line[0][0] = 1
for i in range(n+1):
for j in range(i+1):
if j == 0 or j == i:
line[i][j] = 1
else:
line[i][j] = line[i-1][j-1] + line[i-1][j]
for l in line:
print l
def get_kth_line(self, k):
row = [0]*(k+1)
row[0] = 1
for line in range(k+1):
for i in range(line,-1,-1):
if i == 0 or i == line:
row[i] = 1
else:
row[i] = row[i-1]+row[i]
print row
if __name__ == "__main__":
Solution().get_pascal_triangle(4)
Solution().get_kth_line(4) |
__author__ = "Shashwat Tiwari"
__email__ = "[email protected]"
"""
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
"""
class Solution(object):
def rotatedSearch(self, arr, target):
low = 0
high = len(arr)-1
while low <= high:
mid = (low + (high-low)//2)
if arr[mid] == target:
return mid
elif arr[mid] >= arr[low]:
if target >= arr[low] and target < arr[mid]:
high = mid-1
else:
low = mid+1
elif arr[mid] <= arr[high]:
if target <= arr[high] and target > arr[mid]:
low = mid+1
else:
high = mid-1
return -1
if __name__ == "__main__":
arr = [4,5,6,6,7,7,0,1,2]
target = 0
print(Solution().rotatedSearch(arr, target))
|
__author__ = "Shashwat Tiwari"
__email__ = "[email protected]"
from collections import defaultdict
class Graph:
def __init__(self, number_of_verticies):
self.graph = defaultdict(list)
self.time = -1
self.arrival = [-1]*number_of_verticies
self.departure = [-1]*number_of_verticies
def addEdge(self, source, destination, isDirected=False):
if not isDirected:
self.graph[destination].append(source)
self.graph[source].append(destination)
def arrival_departure(self, vertex, visited):
visited[vertex] = True
self.time += 1
self.arrival[vertex] = self.time
for nei in self.graph[vertex]:
if visited[nei] == False:
self.arrival_departure(nei, visited)
self.time += 1
self.departure[vertex] = self.time
def arrival_departure_interface(self):
visited = [False]*len(self.graph)
for vertex in self.graph:
if visited[vertex] == False:
self.arrival_departure(vertex, visited)
def print_graph(self):
for vertex in self.graph:
print vertex,
for nei in self.graph[vertex]:
print "("+str(nei)+")",
print "start_time "+str(self.arrival[vertex])+" end_time " + str(self.departure[vertex])
if __name__ == "__main__":
graph = Graph(4)
graph.addEdge(0,1, True)
graph.addEdge(1,2, True)
graph.addEdge(1,3, True)
graph.addEdge(2,3, True)
graph.addEdge(2,1, True)
graph.addEdge(3,0, True)
graph.arrival_departure_interface()
graph.print_graph() |
__author__ = "shashwat tiwari"
__email__ = "[email protected]"
class LIS:
"""
m[i] = max(m[j]) + 1 (for all j < i), if arr[i] > arr[j]
"""
def get_lis(self, arr):
lis = [1]*len(arr)
for i in range(1, len(arr)):
lis[i] = max([lis[j]+1 if (lis[j]+1 > lis[i] and arr[i] > arr[j]) else lis[i] for j in range(i)])
return max(lis)
if __name__ == "__main__":
print LIS().get_lis([1,3,5,6,8,9,3,6,0,12,21,8]) |
__author__ = "shashwat tiwari"
__email__ = "[email protected]"
class KnapSack:
def get_max_value(self, weights, values, capacity):
memo = [[None for i in range(capacity+1)] for j in range(len(weights))]
return self.helper(weights, values, capacity, len(weights)-1, memo)
def helper(self, weights, values, capacity, n, memo):
if n == 0 or capacity == 0:
memo[n][capacity] = 0
return 0
if memo[n][capacity] != None:
return memo[n][capacity]
if weights[n] > capacity:
result = self.helper(weights, values, capacity, n-1, memo)
else:
# current item taken
current_taken = values[n] + self.helper(weights, values, capacity - weights[n],n-1, memo)
# current item not taken
current_not_taken = self.helper(weights, values, capacity, n-1, memo)
result = max(current_taken, current_not_taken)
memo[n][capacity] = result
return result
if __name__ == "__main__":
print KnapSack().get_max_value([10,20,30],[60,10,120],50)
|
__author__ = "Shashwat Tiwari"
__email__ = "[email protected]"
"""
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
"""
from LinkedList import LinkedList, ListNode
class Solution(object):
def reverseLinkedListBetween(self, head, m, n):
fakeNode = ListNode(-1)
fakeNode.next = head
prev = fakeNode
current = head
pos = 1
while pos < m and current != None:
prev = current
current = current.next
pos += 1
while pos < n and current != None:
nt = current.next.next
current.next.next = prev.next
prev.next = current.next
current.next = nt
pos += 1
return fakeNode.next
if __name__ == "__main__":
head = None
linked_list = LinkedList()
head = linked_list.insert(head, 1, True)
head = linked_list.insert(head, 2, True)
head = linked_list.insert(head, 3, True)
head = linked_list.insert(head, 4, True)
head = linked_list.insert(head, 5, True)
head = linked_list.insert(head, 6, True)
head = linked_list.insert(head, 7, True)
head = linked_list.insert(head, 8, True)
head = linked_list.insert(head, 9, True)
head = linked_list.insert(head,10, True)
res = Solution().reverseLinkedListBetween(head, 2, 4)
linked_list.printLL(res)
|
def Prime(num):
if num>=2:
for x in range(2,num):
if num%x==0:
print(num, "is not prime")
break
elif num%x!=0:
print(num,"is a prime")
break
else:
print("enter a number larger than 2")
-----------------------------------------------
def Prime(num):
if num>=2:
for x in range(2,num):
if num%x==0:
return False
return True
|
import networkx as nx
def ruta():
graf = nx.DiGraph()
archivo = open("guategrafo.txt", "r")
contenido = archivo.readlines()
archivo.close()
for lineas in contenido:
string = lineas.split(" ")
graf.add_node(string[0])
graf.add_node(string[1])
graf.add_edge(string[0],string[1],weight=float(string[2]))
path = nx.floyd_warshall_predecessor_and_distance(graf)
nodos = graf.nodes()
ciudadI = input("Ingrese la ciudad de la cual desea partir: ")
while ciudadI not in graf.nodes():
print ("La ciudad que ingreso no se encuentra en la base de datos")
ciudadI = input("Ingrese la ciudad de la cual desea partir: ")
ciudadD = input("Indique la ciudad de destino: ")
while ciudadD not in graf.nodes():
print ("La ciudad que ingreso no se encuentra en la base de datos")
ciudadD = input("Indique la ciudad de destino: ")
try:
predecesor1 = path[0][ciudadI][ciudadD]
ciudades = []
ciudades.append(predecesor1)
#print predecesor1
cont = 0
if predecesor1!=ciudadI:
while cont == 0:
predecesor = path[0][ciudadI][predecesor1]
ciudades.append(predecesor)
predecesor1 = predecesor
if predecesor1 == ciudadI:
cont = 1
else:
predecesor1 = predecesor
#print predecesor1
imprimir = []
for i in reversed(ciudades):
if ciudadI!=i:
imprimir.append(i)
print ("La ruta mas corta de ", ciudadI, " a ", ciudadD, " es por: ")
print (ciudadI, "-> "+"-> ".join(imprimir),"->", ciudadD)
print ("La distancia en kilometros es: ")
print (path[1][ciudadI][ciudadD])
except:
print ("No existen rutas entre esas ciudades")
def centroGrafo():
graf = nx.DiGraph()
archivo = open("guategrafo.txt", "r")
contenido = archivo.readlines()
archivo.close()
for lineas in contenido:
string = lineas.split(" ")
graf.add_node(string[0])
graf.add_node(string[1])
graf.add_edge(string[0],string[1],weight=float(string[2]))
Centro = nx.center(graf, e=None)
print("Centro del grafo: "+", ".join(Centro))
def add(origen, destino, distancia):
archivo = open("guategrafo.txt", "w")
archivo.write(origen + " " + destino + " " + distancia+"km" + "\n")
archivo.close()
def remove(origen, destino, distancia):
f = open("guategrafo.txt","r")
lines = f.readlines()
f.close()
file = open("guategrafo.txt","w")
for line in lines:
if line!= origen+" "+destino+" "+distancia:
file.write(line)
file.close() |
import numpy as np # Useful because incoming images are numpy arrays
# import cv2 # Only used when run as main script
# A NOTE ON NOTATION:
# The way numpy numbers its arrays is
# right-handed, just like in math, but turned
# 90 degrees clockwise. That is, the pair
# (x,y) is:
# ----- Y
# | RIGHT IN NUMPY
# |
# X
# Ordinarily, when programming, one expects the following,
# left-handed coordinate system, where (i,j) is:
# ----- I
# | WRONG IN NUMPY
# |
# J
# - - - - - - - - - - - #
# Function filledCircle
# - - - - - - - - - - - #
# Draws a filled circle
# in an image at a specified
# location
# Input:
# x - x position of center
# y - y position of center
# r - radius of circle
# img - 8-bit integer matrix
# Output:
# modified version of img,
# with circle drawn.
# NOTE:
# matrices, like img, are
# passed to functions by
# reference, which means img
# is automatically modified
# in the calling function
# - - - - - - - - - - - #
def filledCircle(x,y,r,img):
rsize = img.shape[0]
csize = img.shape[1]
maxDist = r*r
for i in range(0,rsize):
for j in range(0,csize):
if (i-x)**2 + (j-y)**2 <= maxDist:
img[i,j] = 255
return img
if __name__ == '__main__':
import cv2
image = np.zeros([1080,1920,3])
filledCircle(image.shape[0]//2,image.shape[1]//2,100,image[:,:,1])
cv2.imshow('circleTest',image)
cv2.waitKey(0)
cv2.imwrite('ReferenceImages/circle.png',image)
cv2.destroyAllWindows() |
import argparse
from os import listdir
from os.path import isfile
import os
parser = argparse.ArgumentParser(description="Project root directory from where to count")
parser.add_argument('--dir', help="Path of the root")
args = parser.parse_args()
count = 0
def count_lines(current_path):
global count
list_dir = listdir(current_path)
for a in list_dir:
current = current_path +"/" + a
if isfile(current) and current.endswith("py"):
file = open(current, 'r')
count = count + len(file.readlines())
file.close()
print current
project_path = args.dir
directories = [x[0] for x in os.walk(project_path)]
for directorie in directories:
count_lines(directorie)
print "\n"
print "{} Rows of Python code".format(count)
|
# Program that reads in the string and outputs how long it is
# Author: Ante Dujic
inputString = input ("Enter a string: ")
lengthOfString = len (inputString)
print ("The length of {} is {}" .format (inputString, lengthOfString)) |
# Program that makes a list with 10 random numbers (20000 - 10000)
# Author: Ante Dujic
import numpy as np
minSalary = 20000
maxSalary = 80000
numberOfEntries = 10
np.random.seed (1)
salaries = np.random.randint (minSalary, maxSalary, numberOfEntries)
salariesPlus = salaries + 5000
salariesMult = salaries * 1.05
newSalaries = salariesMult.astype (int)
print (salaries)
print (salariesPlus)
print (salariesMult)
print (newSalaries) |
# Program that plots a histogram of the salaries
# Author: Ante Dujic
import numpy as np
import matplotlib.pyplot as plt
minSalary = 20000
maxSalary = 80000
numberOfEntries = 100
np.random.seed (1)
salaries = np.random.randint (minSalary, maxSalary, numberOfEntries)
plt.hist (salaries)
plt.show () |
# Program that checks variable type
# Author: Ante Dujic
# List of variables
i = 3
fl = 3.5
isa = True
memo = 'how now Brown Cow'
lots = []
# Checking variable type
print ('Variable {} is a type: {} and value: {}' .format ('i', type(i), i))
print ('Variable {} is a type: {} and value: {}' .format ('fl', type(fl), fl))
print ('Variable {} is a type: {} and value: {}' .format ('isa', type(isa), isa))
print ('Variable {} is a type: {} and value: {}' .format ('memo', type(memo), memo))
print ('Variable {} is a type: {} and value: {}' .format ('lots', type(lots), lots)) |
def double_char(str):
new = ""
for c in str:
new+=c*2
return new |
import math
i=0
sum=0
while i<100:
sum+=int(input())
i+=1
print(sum) |
def Excel(s):
L = len(s)
i = L
j = 0
Num = 0
print(i)
while i>0:
Num = Num + (26**j)*(ord(s[i-1])-64)
i = i - 1
j = j + 1
return Num
print(Excel("A"))
|
import unittest
import leap_year
class testCaseAdd(unittest.TestCase):
def test_volume(self):
self.assertEqual(leap_year.leapyear(2004),"is a leap year")
self.assertEqual(leap_year.leapyear(2012),"is a leap year")
self.assertEqual(leap_year.leapyear(2007),"is not a leap year")
self.assertEqual(leap_year.leapyear(2001),"is not a leap year")
#tests for additon, then subtraction, then multiply, and then division
#select right options in terminal when testing
if __name__ == '__main__':
unittest.main() |
N = int(input())
for i in range(0,N):
turn = int(input())
if turn <= 1 or (turn%7 == 0) or (turn%7 == 1):
print("Second")
else:
print("First")
|
#!/bin/python3
import sys
def fib(n):
score = 0
if n == 0:
return 0
elif n == 1:
return 1
return fib(n-1) + fib(n-2)
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
tmp = []
for i in range(3,n,3):
f = fib(i)
if i <= n:
tmp.append(f)
print(sum(tmp)) |
from operator import attrgetter # method for working with specific attributes of an object
class ShortestPath: # main class
def __init__(self, row, col, grid):
self.__row = row
self.__col = col
self.__matrix = [[0 for i in range(self.__col)] # matrix for grid input
for j in range(self.__row)]
self.__matrix = grid
self.__dist = [[100000 for i in range(self.__col)] # matrix for applying 'infinite' weight for each cell that has not been visited yet by Dijkstra function
for j in range(self.__row)]
self.__visited = [[False for i in range(self.__col)] # matrix for the distinction of whether a cell has been visited or not, indicated by True or False
for j in range(self.__row)]
self.__grid = [['*' for i in range(self.__col)] # matrix for representing the final grid, with the start point, the weight value for each cell that has been visited and the destination point
for j in range(self.__row)]
self.__shortest_path_tree = [] # list for storing the shortest path leading to the destination point
class __Cell: # class for storing the cell coordinates and the weight of distance leading to that cell
def __init__(self, x, y, distance):
self.x = x
self.y = y
self.distance = distance
def _PrintSolution(self, x, y): # prints the final grid and shortest path
for row in self.__grid:
print(row)
print(
"\nThe destination point is " + str(self.__matrix[x][y]) + " and it's weight is " + str(self.__dist[x][y]))
print(self.__shortest_path_tree)
def _isInsideGrid(self, i, j): # indicating whether a cell is inside the boundaries of the grid or not
return 0 <= i < self.__col and 0 <= j < self.__row
def Dijkstra(self, xs, ys, xd, yd): # Dijkstra Algorithm
dx = [0, 1, 0, -1, 1, -1, 1, -1] # lists dx and dy store the pairs of movement that the algorithm makes in order to define the distance from the source cell to it's neighbors (up, down, right, left, diagonal)
dy = [-1, 0, 1, 0, 1, 1, -1, -1]
priority_list = [ShortestPath.__Cell(0, 0, 0)] # priority list that stores the cell that have been visited by the algorithm
for i in range(self.__row): # initializing the cells that will act as obstacles, their value is zero (0)
for j in range(self.__col):
if self.__matrix[i][j] == 0:
self.__visited[i][j] = True
self.__grid[i][j] = '#'
else:
self.__visited[i][j] = False
for i in range(self.__row): # initializing the source cell
for j in range(self.__col):
if i == xs and j == ys:
self.__matrix[i][j] = 0
self.__dist[i][j] = 0
self.__grid[i][j] = 's'
self.__visited[i][j] = True
while priority_list: # main loop
cell = min(priority_list, key=attrgetter('distance')) # the cell with the lowest value is becoming the source cell and is stored in the shortest path list, this cell can not be visited again by the algorithm so it's value
self.__shortest_path_tree.append(cell.distance) # is set to True in the visited matrix
self.__visited[cell.x][cell.y] = True
priority_list.remove(cell)
for i in range(8):
x = cell.x + dx[i]
y = cell.y + dy[i]
if not self._isInsideGrid(x, y): # checks whether the cell is within the boundaries of the matrix
continue
if not self.__visited[x][y]: # if the cell is not contained inside self.__visited matrix then proceed
if self.__dist[x][y] > self.__dist[cell.x][cell.y] + self.__matrix[x][y]: # if the weight (distance) of the cell in check is greater than the value of the source cell plus the cell in check in the main matrix the proceed
self.__dist[x][y] = self.__dist[cell.x][cell.y] + self.__matrix[x][y] # update the weight (distance) of the cell in check with the value of the source cell plus the value of the cell in check in the main matix
priority_list.append(ShortestPath.__Cell(x, y, self.__dist[x][y])) # append this cell in the priority list
self.__grid[x][y] = str(self.__dist[x][y]) # update the weight of the target cell in the grid
if x == xd and y == yd: # if the coordinates of the target cell are the same as those of the destination cell
self.__grid[x][y] = 'd' # update the value of the target cell with the letter 'd' indicating destination
return self._PrintSolution(x, y) # return the _PrintSolution method in order to print the final grid and the shortest path leading to the destination cell
if __name__ == '__main__':
grid = [[31, 100, 0, 12, 18], # main grid
[10, 13, 0, 157, 6],
[100, 113, 0, 11, 33],
[88, 0, 0, 21, 140],
[99, 32, 111, 11, 20]]
# grid = [[1, 1, 1, 1, 1, 0, 1, 1, 1, 1], # you can try this grid also
# [1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
# [1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
# [1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
# [1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
# [1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
# [1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
# [1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
# [1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
# [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
g = ShortestPath(5, 5, grid) # instantiation of ShortestPath class
g.Dijkstra(0, 0, 4, 4) # Dijkstra Algorithm
|
#visualização de dados
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,3,7,2,1]
titulo = "Gráfico de barras"
eixox = "Eixo X"
eixoy = "Eixo Y"
#legendas
plt.title(titulo)
plt.xlabel(eixox)
plt.ylabel(eixoy)
plt.scatter(x,y)
plt.plot(x,y)
plt.bar(x, y)
plt.show() |
# Time Complexities:
# Avg Worst
# Access O(n) O(n)
# Search O(n) O(n)
# Insert O(1) O(1)
# Delete O(1) O(1)
# Note: insertion is O(1) bc the operation is constant time (changing pointers). Unlike array where you have to shift elements. Finding the place to insert (indexing) is O(n)
# Space Complexity:
# Worst - O(n)
from Node import Node
class LinkedList:
# head is a node
def __init__(self, head):
self.head = head
def size(self):
ptr = self.head
counter = 0
while ptr is not None:
ptr = ptr.next
counter += 1
return counter
def printList(self):
ptr = self.head
while ptr is not None:
print(ptr.val, end=" ")
ptr = ptr.next
print("\n")
def insert(self, node, index):
counter = 0
cur = None
next = self.head
while counter < index:
cur = next
next = next.next
counter += 1
if cur is not None:
cur.next = node
node.next = next
if index == 0:
self.head = node
def insertAtEnd(self, node):
ptr = self.head
while ptr.next is not None:
ptr = ptr.next
ptr.next = node
def remove(self, node):
counter = 0
prev = Node(0) # dummy
cur = self.head
while cur.val != node.val:
prev = cur
cur = cur.next
if cur == self.head:
self.head = self.head.next
prev.next = cur.next
def main():
zero = Node(0)
one = Node(1)
two = Node(2)
three = Node(3)
zero.next = one
one.next = two
two.next = three
lst = LinkedList(zero)
lst.printList()
four = Node(4)
lst.insert(four, 4)
lst.printList()
twoPointFive = Node(2.5)
lst.insert(twoPointFive, 3)
lst.printList()
negOne = Node(-1)
lst.insert(negOne, 0)
lst.printList()
lst.insertAtEnd(Node(5))
lst.printList()
lst.remove(twoPointFive)
lst.printList()
print("Size is: " + str(lst.size()))
if __name__ == "__main__":
main()
|
from collections import defaultdict
class Graph:
def __init__(self):
# use defaultdict instead of dict bc when adding edges, if the edge not in graph,
# it will not raise error and add it to dict
# put list in constructor because the values of each key will be a list
# so this knows to create a default list (empty list) if the key is not in the dictionary
self.graph = defaultdict(list)
# adds vertex v as an adjacent node to vertex u
def addEdge(self, u, v):
self.graph[u].append(v)
def BFS(self, s):
queue = []
visited = []
queue.append(s)
visited.append(s)
while queue:
v = queue.pop(0)
print(v, end=" ")
for adjacent in self.graph[v]:
if adjacent not in visited:
queue.append(adjacent)
visited.append(adjacent)
print("\n")
def DFS(self, s):
stack = []
visited = []
stack.append(s)
visited.append(s)
while stack:
v = stack.pop()
print(v, end=" ")
# i reverse it so it goes down left side first
self.graph[v].reverse()
for adjacent in self.graph[v]:
if adjacent not in visited:
stack.append(adjacent)
visited.append(adjacent)
print("\n")
if __name__ == "__main__":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print ("Following is Breadth First Traversal"
" (starting from vertex 2)")
g.BFS(2)
g2 = Graph()
g2.addEdge(4, 2)
g2.addEdge(4, 6)
g2.addEdge(2, 1)
g2.addEdge(2, 3)
g2.addEdge(6, 5)
g2.addEdge(6, 7)
g2.BFS(4)
g2.DFS(4)
g3 = Graph()
g3.addEdge(4, 6)
g3.addEdge(4, 2)
g3.addEdge(2, 3)
g3.addEdge(2, 1)
g3.addEdge(6, 7)
g3.addEdge(6, 5)
g3.BFS(4)
g3.DFS(4)
# I'm noticing that the order of inserting the edges matters
# But technically they are still a BFS or DFS, you can sort the list and/or reverse it to try to go in a direction you want
|
from random import choice
with open('dictionary.txt', 'r') as f:
words = f.readlines()
list = {}
for i in words:
i = i.strip()
if len(i) in list:
list[len(i)].append(i)
else:
list[len(i)] = [i]
t = True
while t:
try:
i = raw_input('Enter a number between 1 and 28 that\'s not 26 or 27: ')
t = True
if int(i) >= 1 and int(i) <= 28 and int(i) is not 26 and int(i) is not 27 and not i.isalpha():
i = int(i)
t = False
except:
pass
word = choice(list[i])
guesses = 0
gword = []
for _ in xrange(i):
gword.append('_')
lost = False
print 'Word:', ''.join(gword)
over = False
while not over:
t = 0
for a in xrange(i):
if word[a].find(gword[a]) < 0:
break
else:
t += 1
if t is len(word):
over = True
elif guesses > 10:
print "You lost! The word was:", word
lost = True
over = True
else:
g = raw_input('Please guess a single letter: ')
t = True
while t:
if len(g) is not 1:
g = raw_input('Please guess a SINGLE letter: ')
elif not g.isalpha():
g = raw_input('Please guess a single LETTER: ')
else:
t = False
g = g.lower()
if g in word:
l = 0
while gword.count(g) is not word.count(g):
ind = word.find(g, l)
l = ind + 1
gword[ind] = g
print 'Correct Guess!', ''.join(gword)
else:
print "Incorrect guess"
print "Additional Guesses left: ", 10-guesses
guesses += 1
if not lost:
print 'You won!' |
import re
from time import gmtime, strptime
def main():
age = input("Please Enter Birthdate (01/27/1998):")
while not re.match('\d\d/\d\d/\d\d\d\d', age):
age = input("Please Enter Birthdate (01/27/1998):")
date = gmtime()
age = strptime(age, "%m/%d/%Y")
print("Age In Seconds:", ((date.tm_year - age.tm_year) * 365 + (date.tm_yday - age.tm_yday)) * 86400)
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
# #####################################
# @Author: Feyiz135
# @Time: 2017-05-07
# #####################################
"""
生成各种类型的随机数据
"""
import random
from datetime import date, datetime, timedelta
import string
def _gen_data(iterable, length, exc=None):
"""
:param iterable: 数据源
:param length: 输出字符串的长度
:param exc: 排除以exc中的值开头的字符串
:return: 字符串
"""
s = ''
while 1:
s = random.choice(iterable)
if exc and s.startswith(exc):
continue
break
return s + ''.join([random.choice(iterable) for _ in range(length - 1)])
def gen_random_string(length=8):
"""
返回一个由大小写字母、数字与下划线随机组成的字符串
:param length: 字符串的长度
:return:非数字开头的字符串
"""
chars = string.ascii_letters + string.digits + "_"
return _gen_data(chars, length, tuple(string.digits))
def gen_random_hex(length=8):
"""
返回一个指定长度的随机十六进制数构成的字符串
:param length: 长度
:return: 十六进制字符串
"""
return _gen_data(string.hexdigits, length, '0')
def gen_random_int(length=6):
"""
返回一个指定长度的随机整数
:param length:
:return:
"""
return int(_gen_data(string.digits, length, '0'))
def gen_random_bin(length=8):
"""
返回一个指定长度的随机二进制数构成的字符串
:param length:
:return:
"""
return _gen_data(['0', '1'], length, '0')
def gen_random_bool():
"""随机返回一个二进制数"""
return random.randint(0, 1)
def gen_one_item(sequence):
"""随机返回序列中的一项"""
return random.choice(sequence)
def gen_relative_date(days=1):
"""
返回一个相对于今日的日期
:param days:天数差
:return: 年-月-日
"""
return date.today() - timedelta(days=days)
def gen_relative_time(hours=1, minutes=2, seconds=3):
"""
返回相对于此刻的时间
:param hours: 小时差
:param minutes: 分钟差
:param seconds: 秒数差
:return: 时:分:秒
"""
return (datetime.now() - timedelta(hours=hours, minutes=minutes, seconds=seconds)).strftime('%X')
def gen_relative_datetime(days=0, hours=1, minutes=2, seconds=3):
"""
返回相对于此时的一个时间点
:param days: 天数差
:param hours: 小时差
:param minutes: 分钟差
:param seconds: 秒数差
:return: 年-月-日 时:分:秒
"""
return (datetime.now() - timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)).strftime('%Y-%m-%d %H:%M:%S')
def gen_timestamp():
"""
返回此时的时间戳
:return: 长度为13位的int
"""
return int(datetime.now().timestamp() * 1000)
def gen_random_plate_number():
"""返回一个随机的车牌"""
REGION = ['京', '津', '冀', '晋', '蒙', '辽', '吉', '黑', '沪', '苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂',
'湘', '粤', '桂', '琼', '渝', '川', '黔', '滇', '藏', '陕', '甘', '青', '宁', '新']
region = random.choice(REGION)
city = random.choice(string.ascii_uppercase)
number = random.sample(_gen_data(string.ascii_uppercase, 2) + _gen_data(string.digits, 3), 5)
return region + city + "".join(number)
if __name__ == "__main__":
print(gen_relative_time())
|
def power(x,y):
if y==0:
return 1
elif x==0:
return 0
elif y%2==0:
return power(x,y/2)*power(x,y/2)
else:
y=(y-1)/2
return x*power(x,y)*power(x,y)
result=power(2,3)
print result
|
listw = ["hello", "hi", "hey", "super", "snehashish", "yaju", "yes"]
emlis = []
word = input()
for i in listw:
if word in i:
emlis.append(i)
print(emlis) |
import random
def print_board(a):
print(a[1], " | ", a[2], " | ", a[3])
print("-------------------")
print(a[4], " | ", a[5], " | ", a[6])
print("-------------------")
print(a[7], " | ", a[8], " | ", a[9])
def is_board_full(board):
return board.count(" ") == 1
def is_free(board, pos):
return board[pos] == " "
def insert_letter(board, l, move):
board[move] = l
def player_move(board, let):
flag = True
while flag:
move = input("Enter player move from 1-9: ")
try:
move = int(move)
if move > 0 and move < 10:
if is_free(board, move):
flag = False
insert_letter(board, let, move)
else:
print("No vacant space")
else:
print("Enter valid input in range of 1-9.")
except:
print("Enter valid input.")
def is_winner(board, le):
return (board[1] == le and board[2] == le and board[3] == le) or (
board[4] == le and board[5] == le and board[6] == le) or (
board[7] == le and board[8] == le and board[9] == le) or (
board[1] == le and board[4] == le and board[7] == le) or (
board[2] == le and board[5] == le and board[8] == le) or (
board[9] == le and board[6] == le and board[3] == le) or (
board[7] == le and board[5] == le and board[3] == le) or (
board[9] == le and board[5] == le and board[1] == le)
def select_random(a):
r = random.randrange(0, len(a))
return a[r]
def comp_move(board):
poss_moves = [i for i, j in enumerate(board) if j == " " and i > 0]
move = 0
for let in ['X', 'O']:
for i in poss_moves:
a = board[:]
a[i] = let
if is_winner(a, let):
move = i
return move
open_corners = []
for i in poss_moves:
if i in [1, 3, 7, 9]:
open_corners.append(i)
if len(open_corners) > 0:
move = select_random(open_corners)
return move
if 5 in poss_moves:
return 5
if len(poss_moves) > 0:
move = select_random(poss_moves)
return move
board = [" " for x in range(10)]
def main():
Oddelovac = "=" * 40
Oddelovac_mini = "-" * 40
print(f"""
{"Welcome to Tic Tac Toe":^40}
{Oddelovac}
{"GAME RULES:":^40}
Each player can place one mark (or stone)
per turn on the 3x3 grid. The WINNER is
who succeeds in placing three of their
marks in a:
* horizontal,
* vertical or
* diagonal row
{Oddelovac}
{"Lets start the game!":^40}
{Oddelovac_mini}
""")
print(f"{'1 - player vs player':^40}")
print(f"{'2 - player vs computer':^40}")
print(f"{'3 - computer vs computer':^40}")
p = 0
l = ["Player vs player mode. Let's go.", "Player vs computer mode. Let's go.", "Computer vs computer mode."]
flag = True
while flag:
print()
p = input("Enter the mode game, please: ")
try:
p = int(p)
if p in [1, 2, 3]:
flag = False
print("You have selected: ", l[p - 1])
else:
print("Please select correct option in range of [1,2,3].")
except:
print("Enter valid number.")
print_board(board)
while not (is_board_full(board)):
if not is_winner(board, 'O'):
if p != 3:
print("Player turn.")
player_move(board, 'O')
else:
move = comp_move(board)
if move == 0:
print("Tie game.")
else:
print("Computer placed at ", move, " position.")
insert_letter(board, 'O', move)
# printBoard(board)
print_board(board)
if is_winner(board, 'O'):
print("O\'s won the game '")
break
else:
print("O\'s won the game")
break
if not is_winner(board, 'X'):
if p != 1:
move = comp_move(board)
if move == 0:
print("tie game")
else:
print("computer placed at ", move, " position")
insert_letter(board, 'X', move)
else:
print("player turn")
player_move(board, 'X')
if is_winner(board, 'O'):
print("X\'s won the game '")
break
print_board(board)
else:
print("X\'s won the game'")
break
if is_board_full(board):
print("Tie game.")
main()
|
class StringValidators(object):
def __init__(self):
self.inp = raw_input()
def check_is_any_num(self, inp):
for i in inp:
if i.isalnum():
return True
return False
def check_is_any_pha(self, inp):
for i in inp:
if i.isalpha():
return True
return False
def check_is_any_digit(self, inp):
for i in inp:
if i.isdigit():
return True
return False
def check_is_any_lower(self, inp):
for i in inp:
if i.islower():
return True
return False
def check_is_any_upper(self, inp):
for i in inp:
if i.isupper():
return True
return False
def print_thing(self, arg):
if arg:
print "True"
else:
print "False"
def main(self):
self.print_thing(self.check_is_any_num(self.inp))
self.print_thing(self.check_is_any_pha(self.inp))
self.print_thing(self.check_is_any_digit(self.inp))
self.print_thing(self.check_is_any_lower(self.inp))
self.print_thing(self.check_is_any_upper(self.inp))
if __name__ == '__main__':
SV = StringValidators()
SV.main()
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
#N = int(raw_input())
factorial = lambda x : 1 if x<=1 else x*factorial(x-1)
N = 3
def factorial(x):
if x <=1:
return 1
else:
return x*factorial(x-1)
print(factorial(N))
|
#!/usr/bin/env python3
def sumarray(arr, total, pos):
if pos < len(arr):
total = sumarray(arr, total, pos+1) + arr[pos]
print(total)
return total
def sum2(arr):
total = 0
for i in range(0, len(arr)):
total = total + arr[i]
print(total)
return total
def sum3(arr):
total = 0
if len(arr) > 0:
total = arr[-1]
print(total)
total = total + sum3(arr[:-1])
return total
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print("gcd of 245, 234 : ", gcd(245, 234))
print("gcd of 400, 88 : ", gcd(400, 88))
print("gcd of 99, 36 : ", gcd(99, 36))
arr = [1,2,3]
print("sumarray of 1,2,3 :", sumarray(arr, 0, 0))
arr = [3,8,3]
print("sum2 of 3,8,3 :", sum2(arr))
arr = [23,43,4003]
print("sum3 of 23,43,4003 :", sum3(arr))
|
#!/usr/bin/env python3
import sys
import os
import json
import pathlib
from collections import deque
# Node of DLL
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# Code for inserting data to tree
def insert(self, data):
if self.data:
if data < self.data:
if self.prev is None:
self.prev = Node(data)
else:
self.prev.insert(data)
elif data > self.data:
if self.next is None:
self.next = Node(data)
else:
self.next.insert(data)
else:
self.data = data
# Print tree
def PrintTree(self):
if self.prev:
self.prev.PrintTree()
print( self.data),
if self.next:
self.next.PrintTree()
########################################
# Iterative function to perform postorder traversal on the tree
def postorderIterative(root):
# create an empty stack and push the root node
output = []
stack = deque()
stack.append(root)
# create another stack to store postorder traversal
out = deque()
# loop till stack is empty
while stack:
# pop a node from the stack and push the data into the output stack
curr = stack.pop()
out.append(curr.data)
# push the left and right child of the popped node into the stack
if curr.prev:
stack.append(curr.prev)
if curr.next:
stack.append(curr.next)
# print postorder traversal
while out:
output.append(out.pop())
return output
#############################################
class DoublyLinkedList:
def __init__(self):
self.head = None
#Create/ return new node
def getNode(self, data):
return Node(data)
def sortedInsert(self, data):
new_node = self.getNode(data)
# If list is empty
if self.head is None:
self.head = new_node
# If to be inserted at beginning
elif self.head.data >= new_node.data:
new_node.next = self.head
new_node.next.prev = new_node
self.head = new_node
else:
current = self.head
while((current.next is not None) and (current.next.data < new_node.data)):
current = current.next
new_node.next = current.next
if current.next is not None:
new_node.next.prev = new_node
current.next = new_node
new_node.prev = current
###################################################
def makeOutput(llist):
output = []
root = Node(0)
DLL = DoublyLinkedList()
# Sort inputs
for key in llist:
DLL.sortedInsert(key)
# Insert sorted inputs into tree
for key, value in llist.items():
root.insert(key)
# Iterate tree in a portOrder form and add recpective
# value of key to output list
for i in postorderIterative(root):
output.append(llist[i])
return output
|
from disjoint_sets import DisjointSets
class Solution:
def findCircleNum(self, M) -> int:
n = len(M)
ds = DisjointSets()
for i in range(n):
ds.make_set(i)
for i in range(n):
for j in range(i + 1):
if M[i][j] == 1:
ds.union(i, j)
return ds.get_count()
|
# coding=utf-8
"""helper file for path function"""
import os
def list_images(base_path, contains=None):
"""
return the set of files that are valid
Args:
base_path:
contains:
Returns:
"""
return list_files(base_path, valid_ext=(".jpg", ".jpeg", ".png", ".bmp", ".ppm"), contains=contains)
def list_files(base_path, valid_ext=(".jpg", ".jpeg", ".png", ".bmp"), contains=None):
"""
loop over the directory structure
Args:
base_path:
valid_ext:
contains:
Returns:
"""
for (root_dir, dir_names, file_names) in os.walk(base_path):
# loop over the file_names in the current directory
for filename in file_names:
# if the contains string is not none and the filename does not contain
# the supplied string, then ignore the file
if contains is not None and filename.find(contains) == -1:
continue
# determine the file extension of the current file
ext = filename[filename.rfind("."):].lower()
# check to see if the file is an image and should be processed
if ext.endswith(valid_ext):
# construct the path to the image and yield it
image_path = os.path.join(root_dir, filename).replace(" ", "\\ ")
yield image_path
|
import random
# deck = []
def print_header():
print("BLACKJACK!")
print("Blackjack payout is 3:2")
print()
def user_input():
while True:
player_money = int(input("Starting player money: "))
if player_money < 0 or player_money > 10000:
print("Invalid amount. Must be from 0 to 10,000")
else:
break
# Check for valid Bet amounts
while True:
print("")
bet_amount = input("Bet amount: ")
print()
if bet_amount == "x":
break
bet_amount = int(bet_amount)
if bet_amount < 5:
print("The minimum bet is 5")
continue
if bet_amount > 1000:
print("The maximum is bet is 1,000")
continue
# check for enough money
while True:
bet_amount = int(bet_amount)
if bet_amount > player_money:
print("You don't have enough money to make that bet.")
bet_amount = input("Bet amount: ")
else:
# print("Move on")
return player_money, bet_amount
break
break
def card_deck():
values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Ace', 'Jack', 'Queen', 'King']
suites = ['Hearts', 'Clubs', 'Diamonds', 'Spades']
deck = [[value + ' of ' + suit, value] for suit in suites for value in values]
random.shuffle(deck)
for i in range(len(deck)):
if deck[i][1] == "Queen":
deck[i][1] = 10
elif deck[i][1] == "King":
deck[i][1] = 10
elif deck[i][1] == "Jack":
deck[i][1] = 10
elif deck[i][1] == "Ace":
deck[i][1] = 11
return deck
def deal_card(deck):
card = deck.pop(0)
return card
def blackjack_rules(dealer_cards_total, players_cards_total,
player_money, bet_amount, dealer_cards,
player_cards):
# print("dealer_cards_total ", dealer_cards_total)
# print("player_cards_total ", players_cards_total)
# player busts
if players_cards_total > 21:
print("YOUR CARDS: ")
for cards in player_cards:
print(cards)
print("Bummer, your busted!, you loose")
print("Player money =", player_money - bet_amount)
play_again()
exit()
# dealer wins
elif dealer_cards_total > players_cards_total:
print("Dealer Won!")
print("Player money ", player_money - bet_amount)
print()
# play_again()
# exit()
return
def play_again():
play = input("Play again? (y/n:) ")
if play == "y":
print("debug")
elif play == "n":
print("Bye")
print()
print("Come again soon!")
print()
exit()
def hit_or_stand(deck, player_cards, players_cards_total,
dealer_cards, dealer_cards_total, player_money,
bet_amount, cards):
print()
response = input("Hit or Stand? (h/s): ")
print()
if response == "s":
while True:
card = deal_card_dealer(deck)
dealer_cards.append(card[0])
print("DEALER'S CARDS: ")
for cards in dealer_cards:
print(cards)
dealer_cards_total = dealer_cards_total + int(card[1])
# dealer looses to player
if dealer_cards_total < players_cards_total:
print("Dealer lost!")
print("Player money", player_money + bet_amount)
print()
# play_again()
# exit()
# dealer busts
elif dealer_cards_total > 21:
print("Yay! Dealer busted, you win!")
print("Player money = ", player_money + bet_amount)
print()
play_again()
exit()
print()
print("YOUR POINTS: ", players_cards_total)
print("DEALER'S POINTS: ", dealer_cards_total)
print()
blackjack_rules(dealer_cards_total, players_cards_total,
player_money, bet_amount, dealer_cards,
player_cards)
continue
# print("Yay! Dealer busted, you win!")
if response == "h":
card = deal_card(deck)
player_cards.append(card[0])
players_cards_total = players_cards_total + int(card[1])
blackjack_rules(dealer_cards_total, players_cards_total,
player_money, bet_amount, dealer_cards,
player_cards)
hit_or_stand(deck, player_cards, players_cards_total,
dealer_cards, dealer_cards_total,
player_money, bet_amount, card)
print()
print("YOUR POINTS: ", players_cards_total)
print("DEALER'S POINTS: ", dealer_cards_total)
print()
for cards in player_cards:
print(cards)
else:
print('DONE')
def deal_card_dealer(deck):
card = deal_card(deck)
# print("card =", card)
return card
def main():
dealer_cards = []
dealer_cards_total = 0
player_cards = []
player_cards_total = 0
# player_cards.append()
print_header()
player_money, bet_amount = user_input()
# print("player money =", player_money)
print("DEALER'S SHOW CARD:")
deck = card_deck()
card = deal_card(deck)
dealer_cards.append(card[0])
print(dealer_cards[0])
print()
dealer_cards_total = int(card[1])
print("YOUR CARDS:")
card = deal_card(deck)
player_cards.append(card[0])
player_cards_total = int(card[1])
card = deal_card(deck)
player_cards_total = player_cards_total + int(card[1])
player_cards.append(card[0])
for cards in player_cards:
print(cards)
hit_or_stand(deck, player_cards, player_cards_total,
dealer_cards, dealer_cards_total, player_money,
bet_amount, card)
blackjack_rules(dealer_cards_total, players_cards_total,
player_money, bet_amount, dealer_cards,
player_cards)
main()
if __name__ == "__main__":
main()
|
# from multiprocessing import Pool
# import time
# COUNT = 50000000
# def countdown(n):
# while n>0:
# n -= 1
# if __name__ == '__main__':
# pool = Pool(processes=2)
# start = time.time()
# r1 = pool.apply_async(countdown, [COUNT//2])
# r2 = pool.apply_async(countdown, [COUNT//2])
# pool.close()
# pool.join()
# end = time.time()
# print('Time taken in seconds -', end - start)
import time
from timeit import default_timer as timer
from multiprocessing import Pool, cpu_count
def square(n):
time.sleep(2)
return n * n
def main():
start = timer()
print(f'starting computations on {cpu_count()} cores')
values = (2, 4, 6, 8)
with Pool() as pool:
res = pool.map(square, values)
print(res)
end = timer()
print(f'elapsed time: {end - start}')
if __name__ == '__main__':
main() |
#week 3 Homework kurtis Henry
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year,studentID):
super().__init__(fname, lname)
self.graduationyear = year
self.ID = studentID
def welcome(self): #welcome message
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
if (self.graduationyear == 2020):
print("welcome senior")
def years_to_go(self): #years to go
years = self.graduationyear - 2020
print("you have", years," years to go!!!")
def locker(self): #id locker/detremination
if (self.ID < 1000):
print ("please report to the office for locker assignment")
class Teacher (Person): #new attributes
def __init__(self, fname, lname, experience, salary):
super().__init__(fname, lname)
self.YearsOfExperience = experience
self.pay = salary
def printname(self): #print names
print(self.firstname, self.lastname)
def level (self): #veteran status
if (self.YearsOfExperience <= 5):
print("welcome young professor")
else:
print("welcome back veteran scholar")
def compensation (self): #compensation calculation
raises = self.pay * .15
salaryincrease = self.pay + raises
print ("Once this school year is complete, you salary will increase to: $" + str(salaryincrease))
class Admin (Person): #admin selections
def __init__(self, fname, lname, position, team):
super().__init__(fname, lname)
self.position = position
self.teams = team
def location(self): #print what job based on clerical or not
if ( self.position == "clerical"):
print ("you will work with students to recieve lockers")
else:
print("we look forward to you helping out professors")
def work_time(self): #afternoon worker is b is selected
if (self.teams == "b"):
print("you will work from 12 to 4")
else:
print("you will work 8 to 12")
#test
def main():
x=Student("Kurtis","Henry",2020, 998)
x.welcome()
x.years_to_go()
x.locker()
print()
print()
print()
y = Teacher ("Heather" ,"Bradley", 6, 55000)
y.printname()
y.level()
y.compensation()
print()
print()
print()
x = Admin ("Steve" ,"Bell", "clerical", "b")
x.printname()
x.location()
x.work_time()
main()
|
# coding:utf-8
# author:tntC4stl3
'''
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
'''
fib = [1, 2]
i = 1
# 得到完整的fib列表
while True:
tmp = fib[i] + fib[i-1]
if tmp > 4000000:
break
fib.append(tmp)
i += 1
result = 0
for i in range(1, len(fib), 3): # 偶数的规律是从第二个数开始,每隔3个数就为偶数
result += fib[i]
print result |
#!/usr/bin/env python3.8
"""
ROS A-Star's algorithm path planning exercise solution
Author: Roberto Zegers R.
Copyright: Copyright (c) 2020, Roberto Zegers R.
License: BSD-3-Clause
Date: Nov 30, 2020
Usage: roslaunch unit3_pp unit3_astar_solution.launch
"""
import rospy
def find_neighbors(index, width, height, costmap, orthogonal_step_cost):
"""
Identifies neighbor nodes inspecting the 8 adjacent neighbors
Checks if neighbor is inside the map boundaries and if is not an obstacle according to a threshold
Returns a list with valid neighbour nodes as [index, step_cost] pairs
"""
neighbors = []
# length of diagonal = length of one side by the square root of 2 (1.41421)
diagonal_step_cost = orthogonal_step_cost * 1.41421
# threshold value used to reject neighbor nodes as they are considered as obstacles [1-254]
lethal_cost = 1
upper = index - width
if upper > 0:
if costmap[upper] < lethal_cost:
step_cost = orthogonal_step_cost + costmap[upper]/255
neighbors.append([upper, step_cost])
left = index - 1
if left % width > 0:
if costmap[left] < lethal_cost:
step_cost = orthogonal_step_cost + costmap[left]/255
neighbors.append([left, step_cost])
upper_left = index - width - 1
if upper_left > 0 and upper_left % width > 0:
if costmap[upper_left] < lethal_cost:
step_cost = diagonal_step_cost + costmap[upper_left]/255
neighbors.append([index - width - 1, step_cost])
upper_right = index - width + 1
if upper_right > 0 and (upper_right) % width != (width - 1):
if costmap[upper_right] < lethal_cost:
step_cost = diagonal_step_cost + costmap[upper_right]/255
neighbors.append([upper_right, step_cost])
right = index + 1
if right % width != (width + 1):
if costmap[right] < lethal_cost:
step_cost = orthogonal_step_cost + costmap[right]/255
neighbors.append([right, step_cost])
lower_left = index + width - 1
if lower_left < height * width and lower_left % width != 0:
if costmap[lower_left] < lethal_cost:
step_cost = diagonal_step_cost + costmap[lower_left]/255
neighbors.append([lower_left, step_cost])
lower = index + width
if lower <= height * width:
if costmap[lower] < lethal_cost:
step_cost = orthogonal_step_cost + costmap[lower]/255
neighbors.append([lower, step_cost])
lower_right = index + width + 1
if (lower_right) <= height * width and lower_right % width != (width - 1):
if costmap[lower_right] < lethal_cost:
step_cost = diagonal_step_cost + costmap[lower_right]/255
neighbors.append([lower_right, step_cost])
return neighbors
def indexToWorld(flatmap_index, map_width, map_resolution, map_origin = [0,0]):
"""
Converts a flatmap index value to world coordinates (meters)
flatmap_index: a linear index value, specifying a cell/pixel in an 1-D array
map_width: number of columns in the occupancy grid
map_resolution: side lenght of each grid map cell in meters
map_origin: the x,y position in grid cell coordinates of the world's coordinate origin
Returns a list containing x,y coordinates in the world frame of reference
"""
# convert to x,y grid cell/pixel coordinates
grid_cell_map_x = flatmap_index % map_width
grid_cell_map_y = flatmap_index // map_width
# convert to world coordinates
x = map_resolution * grid_cell_map_x + map_origin[0]
y = map_resolution * grid_cell_map_y + map_origin[1]
return [x,y]
def euclidean_distance(a, b):
distance = 0
for i in range(len(a)):
distance += (a[i] - b[i]) ** 2
return distance ** 0.5
def manhattan_distance(a, b):
return (abs(a[0] - b[0]) + abs(a[1] - b[1]))
def a_star(start_index, goal_index, width, height, costmap, resolution, origin, grid_viz):
'''
Performs A-star's shortes path algorithm search on a costmap with a given start and goal node
'''
# create an open_list
open_list = []
# set to hold already processed nodes
closed_list = set()
# dict for mapping children to parent
parents = dict()
# dict for mapping g costs (travel costs) to nodes
g_costs = dict()
# dict for mapping f costs (total costs) to nodes
f_costs = dict()
# determine g_cost for start node
g_costs[start_index] = 0
# determine the h cost (heuristic cost) for the start node
from_xy = indexToWorld(start_index, width, resolution, origin)
to_xy = indexToWorld(goal_index, width, resolution, origin)
h_cost = euclidean_distance(from_xy, to_xy)
# set the start's node f_cost (note: g_cost for start node = 0)
f_costs[start_index] = h_cost
# add start node to open list (note: g_cost for start node = 0)
open_list.append([start_index, h_cost])
shortest_path = []
path_found = False
rospy.loginfo('A-Star: Done with initialization')
# Main loop, executes as long as there are still nodes inside open_list
while open_list:
# sort open_list according to the lowest 'f_cost' value (second element of each sublist)
open_list.sort(key = lambda x: x[1])
# extract the first element (the one with the lowest 'f_cost' value)
current_node = open_list.pop(0)[0]
# Close current_node to prevent from visting it again
closed_list.add(current_node)
# Optional: visualize closed nodes
grid_viz.set_color(current_node,"pale yellow")
# If current_node is the goal, exit the main loop
if current_node == goal_index:
path_found = True
break
# Get neighbors of current_node
neighbors = find_neighbors(current_node, width, height, costmap, resolution)
# Loop neighbors
for neighbor_index, step_cost in neighbors:
# Check if the neighbor has already been visited
if neighbor_index in closed_list:
continue
# calculate g value of neighbour if movement passes through current_node
g_cost = g_costs[current_node] + step_cost
# determine the h cost for the current neigbour
from_xy = indexToWorld(neighbor_index, width, resolution, origin)
to_xy = indexToWorld(goal_index, width, resolution, origin)
h_cost = euclidean_distance(from_xy, to_xy)
#h_cost = manhattan_distance(from_xy, to_xy) # uncomment to use manhattan distance instead
# calculate A-Star's total cost for the current neigbour
f_cost = g_cost + h_cost
# Check if the neighbor is in open_list
in_open_list = False
for idx, element in enumerate(open_list):
if element[0] == neighbor_index:
in_open_list = True
break
# CASE 1: neighbor already in open_list
if in_open_list:
if f_cost < f_costs[neighbor_index]:
# Update the node's g_cost (travel cost)
g_costs[neighbor_index] = g_cost
# Update the node's f_cost (A-Star's total cost)
f_costs[neighbor_index] = f_cost
parents[neighbor_index] = current_node
# Update the node's f_cost inside open_list
open_list[idx] = [neighbor_index, f_cost]
# CASE 2: neighbor not in open_list
else:
# Set the node's g_cost (travel cost)
g_costs[neighbor_index] = g_cost
# Set the node's f_cost (A-Star total cost)
f_costs[neighbor_index] = f_cost
parents[neighbor_index] = current_node
# Add neighbor to open_list
open_list.append([neighbor_index, f_cost])
# Optional: visualize frontier
grid_viz.set_color(neighbor_index,'orange')
rospy.loginfo('A-Star: Done traversing nodes in open_list')
if not path_found:
rospy.logwarn('A-Star: No path found!')
return shortest_path
# Reconstruct path by working backwards from target
if path_found:
node = goal_index
shortest_path.append(goal_index)
while node != start_index:
shortest_path.append(node)
node = parents[node]
# reverse list
shortest_path = shortest_path[::-1]
rospy.loginfo('A-Star: Done reconstructing path')
return shortest_path
|
'''
Returns document as dict: documents[document] = list of words
'''
def getDocuments(texts, delimiter):
documents = {}
for text in texts:
index = 0
words = []
doc = open(text, 'r')
for word in doc.read().split(delimiter):
index += 1
word = word
if word:
words.append(word)
documents[text] = words
return documents
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.