text stringlengths 37 1.41M |
|---|
a = 0
A = 0
B = 0
C = 0
def FindABC():
for c in range(1000, 3, -1):
C = c
for b in range(c, 2, -1):
B = b
a = 1000 - b - c
if a ** 2 + b ** 2 == c ** 2 and a > 0:
return print(a * b * c)
FindABC()
|
# -*- coding: utf-8 -*-
# Typoglycemia
import random
def Typoglycemia(text):
words = text.split()
result = ""
for word in words:
wordList = list(word)
if len(word) >= 4:
tmp = wordList[1:-1]
random.shuffle(tmp)
result += wordList[0] + "".join(tmp) + wordList[-1]
else:
result += word
result += " "
print(result)
if __name__ == "__main__":
text = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
print(text)
Typoglycemia(text)
|
# -*- coding: utf-8 -*-
# n-gram
def nGram(inStr, n):
l = len(inStr)
for i in range(l):
print(inStr[i:i+n])
if __name__ == "__main__":
s = raw_input(">")
print(s)
nGram(s.replace(" ", ""), 2)
s = s.split()
nGram(s, 2)
|
#%%
class Polygon:
def __init__(self, sides):
self.sides = sides
def display_info(self):
print("A polygon is a two dimensional shape "
"with straight lines")
def get_perimeter(self):
perimeter = sum(self.sides)
return perimeter
class Triangle(Polygon):
def display_info(self):
print("A triangle is a polygon with 3 edges")
class Quadrilateral (Polygon):
def display_info(self):
print("A quadrilateral is a polygo with 4 edges")
#%%
t1 = Triangle([5,6,7])
perimeter = t1.get_perimeter()
print("The perimeter is", perimeter)
print(t1.display_info())
|
from tkinter import *
#definicion de clase App y sus miembros.
class App:
#miemros de App
def __init__(self, master):
#instancia de widget frame, cuyo contenedor debe ser enviadoo como argumento
frame = Frame(master)
#organizacion en bloques
frame.pack()
#instancia de boton
self.button = Button(frame, text="SALIR", fg="red",command=frame.quit)
self.button.pack(side=LEFT)
self.slogan = Button(frame,text="ENTRAR",command=self.write_slogan)
self.slogan.pack(side=LEFT)
def write_slogan(self):
print ("Estamos aprendiendo a usar Tkinter!")
#crea instancia de "App"
root=Tk()
ejemplo=App(root)
root.mainloop() |
import sys
#input: list of tuples of data returned by read_data
#process: calculates the counts and total certified, percentage certified. Also sorts the list in decreasing order of number of certifieds and alphabetically for ties.
# Same function used to calculate top 10 states as well as occupations (inputs modified to achieve this)
#output: returns a sorted list of top 10 entries
def top_10(data):
num_certified={} #dictionary to count how many certified in each category
certified=0 #counter for total number of certified
for item in data:
if item[0]=="CERTIFIED":
if item[1] in num_certified:
num_certified[item[1]]+=1
else:
num_certified[item[1]]=1
certified+=1
list_unsorted=[]
for key in num_certified:
list_unsorted.append((key,num_certified[key],num_certified[key]/certified*100)) #creating unsorted list as required
list_sorted = sorted(list_unsorted, key=lambda item: (-item[1], item[0])) #sorting the list. using -item[1] to ensure descending order.
return list_sorted[:10]
#input: top 10 entries received from the function top_10, type of output-(states or occupations)
#process: creates the appropriate output file based on the type_out parameter. Creates the output string in semi-colon seperated format and stores it in the output file.
#output: None
def print_top10(top_10,type_out):
if type_out=="s": #if the type of output is states, create top_10_states.txt
string="TOP_STATES;NUMBER_CERTIFIED_APPLICATIONS;PERCENTAGE\n"
outfile="top_10_states.txt"
else: #else create top_10_occupations.txt
string="TOP_OCCUPATIONS;NUMBER_CERTIFIED_APPLICATIONS;PERCENTAGE\n"
outfile="top_10_occupations.txt"
for item in top_10:
string+=item[0]+";"+str(item[1])+";"+str(round(item[2],1))+"%\n" #building required line and adding to output string
out_f=open("./output/"+outfile,'w')
out_f.write(string[:-1]) #writing except last character to ignore the last \n
out_f.close()
#input: filename to be processed
#process: creates a list of tuples for each line with only the relevant information, i.e: status, job name and state.
# Also checks if any of the required fields is not available and exits if so.
#output: returns the list of tuples
def read_data(filename):
with open(filename,"r") as input_file:
data=[]
string=input_file.read()
if not string or string[0]=="\n":
print("Empty file. Aborting.") #abort program if file is empty
exit()
string_list=string.split("\n")
#try catch blocks to see if any of the necessary fields are missing and if not, storing their indexes.
#Assuming the names of the relevant fields to be as given in the files uploaded on the drive. If that field name is not found, prompt the user for the current name of the field.
#This is done to account for if the names of the fields are changed in the future.
try:
status_ind=string_list[0].split(";").index("CASE_STATUS")
except:
status_string=input("Assuming Status field to be named \"CASE_STATUS\" which was not found. If named differently, please mention here:")
while True:
try:
status_ind=string_list[0].split(";").index(status_string)
break
except:
status_string=input("Assuming Status field to be named \"CASE_STATUS\" which was not found. If named differently, please mention here:")
try:
name_ind=string_list[0].split(";").index("SOC_NAME")
except:
name_string=input("Assuming Occupation name field to be named \"SOC_NAME\" which was not found. If named differently, please mention here:")
while True:
try:
name_ind=string_list[0].split(";").index(name_string)
break
except:
name_string=input("Assuming Occupation name field to be named \"SOC_NAME\" which was not found. If named differently, please mention here:")
try:
state_ind=string_list[0].split(";").index("WORKSITE_STATE")
except:
state_string=input("Assuming Work state field to be named \"WORKSITE_STATE\" which was not found. If named differently, please mention here:")
while True:
try:
state_ind=string_list[0].split(";").index(state_string)
break
except:
state_string=input("Assuming Work state field to be named \"WORKSITE_STATE\" which was not found. If named differently, please mention here:")
for line in string_list[1:]: #ignoring header, hence[1:]
if line=="":
continue #ignoring empty lines
line_split=line.split(";")
data.append([line_split[status_ind],line_split[name_ind].replace("\"",""),line_split[state_ind]])
return data
data=read_data('./input/h1b_input.csv')
top_10s=top_10([[item[0],item[2]] for item in data]) #using only status and state fields for top 10 states
top_10o=top_10([item[:2] for item in data]) #using only status and occupation fields for top 10 occupations
print_top10(top_10s,"s")
print_top10(top_10o,"o")
print("Done Processing. Please check the output folder for the required files.")
|
first_name = "Eric"
last_name = "Weidman"
age = 28
print "Hello, world!"
print "My name is " + first_name +" " + last_name + ". " "I am " + str(age) + " " + "years old!"
print "Python is neat!"
#This is a comment.
"""This is a comment too.
So is this.
Also this."""
|
# add dependencies
import csv
import os
# assign variable to load a file from path
path1 = "/Users/michaelmanthey/Documents/Bootcamp/Module_3_Python/Challenge/election_results.csv"
path2 = "/Users/michaelmanthey/Documents/Bootcamp/Module_3_Python/Challenge/"
file_to_load = os.path.join(path1)
file_to_save = os.path.join(path2, "election_analysis.txt")
# initialize total vote counter
total_votes = 0
#create list for candidate options
candidate_options = []
#dictionary with candidate options and total votes for each
candidate_votes = {}
#track winning candidate and stats
winning_candidate = ""
winning_count = 0
winning_percentage = 0
with open(file_to_load) as election_data:
file_reader = csv.reader(election_data)
# Read the header row.
headers = next(file_reader)
for row in file_reader:
# Add to the total vote count.
total_votes += 1
# Get the candidate name from each row.
candidate_name = row[2]
if candidate_name not in candidate_options:
#add the candidate name to the candidate list
candidate_options.append(candidate_name)
#track candidate vote counts
candidate_votes[candidate_name] = 0
#add a vote to that candidates count
candidate_votes[candidate_name] += 1
with open(file_to_save, "w") as txt_file:
# Print the final vote count to the terminal.
election_results = (
f"\nElection Results\n"
f"-------------------------\n"
f"Total Votes: {total_votes:,}\n"
f"-------------------------\n")
print(election_results, end="")
# Save the final vote count to the text file.
txt_file.write(election_results)
for candidate_name in candidate_options:
votes = candidate_votes[candidate_name]
#calculate vote_percentage
vote_percentage = float(votes) / float(total_votes) * 100
rounded_percent = round(vote_percentage, 2)
#print candidate name and percentage of votes
#print(f"{candidate_name} received {rounded_percent} % of the total votes.")
if (votes > winning_count) and (vote_percentage > winning_percentage):
winning_count = votes
winning_percentage = vote_percentage
winning_candidate = candidate_name
#print(f"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\n")
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")
print(winning_candidate_summary)
#save winning candidate's results to text file
txt_file.write(winning_candidate_summary) |
class Tree:
def __init__(self, root = None):
self.root = root
def insert(self,val,current = None):
new_node = Node(val)
if current is None:
current = self.root
if self.root is None:
self.root = new_node
return
if val <= current.key:
if current.left is None:
current.left = new_node
else:
self.insert(val, current.left)
else:
if current.right is None:
current.right = new_node
else:
self.insert(val, current.right)
def search(self, val, current = None):
if current is None:
if self.root is None:
return None
current = self.root
if current.key == val:
return current
if val < current.key:
if current.left is None:
return None
else:
return self.search(val, current.left)
else:
if current.right is None:
return None
else:
return self.search(val, current.right)
def preorder(self, current = None, is_root = True):
if current is None and is_root:
current = self.root;
if current is None:
return
print(current.key, end=" ")
self.preorder(current.left, False)
self.preorder(current.right, False)
def inorder(self, current = None, is_root = True):
if current is None and is_root:
current = self.root
if current is None:
return
self.inorder(current.left, False)
print(current.key, end=" ")
self.inorder(current.right, False)
def postorder(self, current = None, is_root = True):
if current is None and is_root:
current = self.root
if current is None:
return
self.postorder(current.left, False)
self.postorder(current.right, False)
print(current.key, end = " ")
class Node:
def __init__(self,key = None):
self.key = key
self.right = None
self.left = None
######################################################
# a = Tree()
# x = [int(i) for i in input().split(" ")]
# for i in x:
# a.insert(i)
# y = a.search(18)
# if y is not None:
# print("Node 18 exists")
# else:
# print("Node 18 should be in the Tree")
# z = a.search(5)
# if z is None:
# print("Node 5 is not present in the Tree")
# else:
# print("Node 5 should not be in the Tree")
# SAMPLE INPUT
# 10 6 20 8 15 3 18
######################################################
# a = Tree()
# x = [int(i) for i in input().split(" ")]
# for i in x:
# a.insert(i)
# a.preorder()
# print()
# a.inorder()
# print()
# a.postorder()
# print()
# SAMPLE INPUT
# 30 40 10 9 20 15 25 90 80
# Sample Output:
#
# 30 10 9 20 15 25 40 90 80
# 9 10 15 20 25 30 40 80 90
# 9 15 25 20 10 80 90 40 30
|
#from the search options of the site- like product name, its description- which is available on the website, and then the image url.
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
#Url who's information you want to scrape
url = "https://www.flipkart.com/search?q=iphone&sid=tyy%2C4io&as=on&as-show=on&otracker=AS_QueryStore_OrganicAutoSuggest_0_3_na_na_na&otracker1=AS_QueryStore_OrganicAutoSuggest_0_3_na_na_na&as-pos=0&as-type=RECENT&suggestionId=iphone%7CMobiles&requestId=eaf0a368-4390-4227-b06e-92dee26d197b&as-searchtext=iph"
uClient = uReq(url)
data_info = uClient.read()
uClient.close()
page_soup=soup(data_info,"html.parser") #parsing of information
containers = page_soup.findAll("div",{"class":"_4rR01T"})
#The product name of that item
container=containers[0]
print("\n"+"*Product name of the 1st item is: "+containers[0].text+"\n")
#print("Number of products on a particular site is: ")
#print(len(contaiers))
#To get the product details of that specific product
contain= page_soup.findAll("div",{"class":"fMghEO"})
description= contain[1].findAll("ul",{"class":"_1xgFaf"})
print("*Product Details: "+description[0].text+"\n")
#To print out the Image Description of that product
co= page_soup.findAll("div",{"class":"CXW8mj"})
print("*Image description: "+ co[0].img["src"])
#..................................................END............................................#
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 9 17:44:18 2021
@author: alok
"""
import os.path
import pandas as pd
import random
from Hangman_parts import parts #to call teh Hangman_parts file
from Hangman_words import words
picked_l = random.choice(words)
picked = picked_l.upper()
name = input('Enter your name:').upper()
score = 0
print( 'Hi',name,', Welcome to the Hangman game.')
print('Guess a name with two words,',len(picked) ,'letters including space.Type space to see the space position.')
right = ['_'] * len(picked)
wrong = []
def update():
for i in right:
print(i, end = ' ')
print()
update()
parts(len(wrong))
def winners():
df = pd.read_csv('/tmp/scorerecordAlo.txt', sep=",")
group = df.groupby("name")["score"].sum()
print(group.head(10))
#Main loop for the game
if __name__ == "__main__":
while True:
print("================")
guess = input("Guess a letter: ").upper()
if guess in picked:
index = 0
for i in picked:
if i == guess:
right[index] = guess
index += 1
update()
print('Right guess!')
else:
if guess not in wrong:
wrong.append(guess)
parts(len(wrong))
print('Wrong guess!')
else:
print('You already guess it.')
print(wrong)
if len(wrong) > 4:
print('You lost the game.')
print('Actual word is : ', picked)
winners()
break
if '_' not in right:
if os.path.exists('/tmp/scorerecordAlo.txt'):
print("file exits")
else:
f=open('/tmp/scorerecordAlo.txt', 'w')
f.write('name' + ',' + 'score'+ '\n')
f.close()
print('You win.')
f = open('/tmp/scorerecordAlo.txt',"a", newline="")
score = score + 10
f.write(name +','+ str(score)+'\n')
f.close()
winners()
break
|
import sqlite3, datetime
connection = sqlite3.connect('data.db')
def create_tables():
with connection:
connection.execute(
"CREATE TABLE IF NOT EXISTS movies ("
"id INTEGER PRIMARY KEY,"
" title TEXT,"
" release_timestamp REAL)")
connection.execute(
"CREATE TABLE IF NOT EXISTS users ("
"username TEXT PRIMARY KEY )")
connection.execute(
"CREATE TABLE IF NOT EXISTS watched ("
"user_username TEXT,"
" movie_id INTEGER,"
" FOREIGN KEY (user_username) REFERENCES users(username),"
" FOREIGN KEY (movie_id) REFERENCES movies(id)) ")
def add_movie(title, release_timestamp):
with connection:
connection.execute("INSERT INTO movies (title, release_timestamp) VALUES (?,?);", (title,
release_timestamp))
def add_user(username):
with connection:
connection.execute("INSERT INTO users VALUES (?)", (username,))
def get_movies(upcoming=False):
cursor = connection.cursor()
if upcoming:
today_timestamp = datetime.datetime.today().timestamp()
cursor.execute("SELECT * FROM movies WHERE release_timestamp>?;", (today_timestamp,))
else:
cursor.execute("SELECT * FROM movies;")
return cursor.fetchall()
def get_watched_movies(watcher_name, upcoming=False):
cursor = connection.cursor()
cursor.execute(
"SELECT movies.* FROM movies JOIN watched ON movies.id=watched.movie_id WHERE watched.user_username=?",
(watcher_name,))
return cursor.fetchall()
def watch_movie(username, movie_id):
with connection:
connection.execute("INSERT INTO watched (user_username, movie_id) VALUES (?,?)", (username, movie_id,))
def search_movie(title):
like_title = f"%{title}%"
cursor=connection.execute("SELECT * from movies WHERE title LIKE ?", (like_title,))
return cursor.fetchall() |
#!/usr/bin/python3
import sys
import unittest
def max(x, y):
"""An auxiliary function that returns the maximum of 2 values.
:rtype: int
"""
if x >= y:
return x
return y
def cut_rod( p, n ):
""" Cutting rod problem: the naive, recursive solution that returns the maximum price.
:param p: the array of prices, with $0 in position 0, and p_i in position i.
:param n: length of rod for which a solution is to be computed (n < p.length)
:type p: list
:type n: int
:rtype: int
"""
if n==0:
return 0
q = -(2**14)
for i in range(1,n+1):
q = max(q, p[i] + cut_rod(p, n-i ))
return q
def memoized_cut_rod( p, n):
""" Cutting rod problem: the memoized, recursive solution that returns the maximum price.
:param p: the array of prices, with $0 in position 0, and p_i in position i.
:param n: length of rod for which a solution is to be computed (n < p.length)
:type p: list
:type n: int
:rtype: int
"""
# initializing the array of subresults with infinite negative values
r = [ -2**14 for i in range(0,n+1) ]
result = memoized_cut_rod_aux(p, n, r)
return result
def memoized_cut_rod_aux(p, n, r):
""" Cutting rod problem: the recursive part of the memoized, recursive solution that returns the maximum price.
:param p: the array of prices, with $0 in position 0, and p_i in position i.
:param n: length of rod for which a solution is to be computed (n < p.length)
:param r: the memo, that stores the optimal price for length i at position i
:type p: list
:type n: int
:type r: list
:rtype: int
"""
if r[n] >= 0:
return r[n]
if n==0:
q = 0
else:
q = -(2**14)
for i in range(1, n+1):
q = max(q, p[i] + memoized_cut_rod_aux(p, n-i, r))
r[n] = q
return q
def memoized_cut_rod_extended( p, n):
""" Cutting rod problem: the memoized, recursive solution that returns the maximum price, as well at the solution array.
The function returns a pair, i.e. a 2-tuple (price, s) where price is the optimal price for the given length n, and s is a list where an element at position i is the length of the optimal first cut for total rod length i.
:param p: the array of prices, with $0 in position 0, and p_i in position i.
:param n: length of rod for which a solution is to be computed (n < p.length)
:type p: list
:type n: int
:rtype: tuple
"""
# initializing the array of subresults with infinite negative values
r = [ -2**14 for i in range(0,n+1) ]
# The solution array will store the optimal first cut for all
# lengths: by default, it associates to each length (indices 1 to 10)
# the length itself, i.e. no cut at all
s = list(range(0,(n+1)))
price = memoized_cut_rod_extended_aux(p, n, r,s)
return (price, s)
########### TODO: modify memoized_cut_rod_aux() ########################
def memoized_cut_rod_extended_aux(p, n, r, s):
""" Cutting rod problem: the recursive part of the memoized, recursive solution that returns the maximum price,
and the solution array.
This recursive subprocedure just returns the price, and maintains the solution array that is passed in as a parameter.
:param p: the array of prices, with $0 in position 0, and p_i in position i.
:param n: length of rod for which a solution is to be computed (n < p.length)
:param r: the memo, that stores the optimal price for length i at position i
:param s: the solution array, where an element at position i is the length of the optimal first cut for total rod length i
:type p: list
:type n: int
:type r: list
:type s: list
:rtype: tuple
"""
if r[n] >= 0:
return r[n]
if n==0:
q = 0
else:
q = -(2**14)
for i in range(1, n+1):
q = max(q, p[i] + memoized_cut_rod_aux(p, n-i, r))
r[n] = q
return q
#####################################################
def bottom_up_cut_rod(p, n):
""" Cutting rod problem: the bottom-up solution that returns the maximum price.
:param p: the array of prices, with $0 in position 0, and p_i in position i.
:param n: length of rod for which a solution is to be computed (n < p.length)
:type p: list
:type n: int
:rtype: int
"""
r = [ None for i in range(0,n+1) ]
r[0]=0
for j in range(1, n+1):
q = -(2**14)
for i in range(1, j+1):
q = max(q, p[i] + r[j-i])
r[j] = q
return r[n]
def extended_bottom_up_cut_rod(p, n):
""" Cutting rod problem: the bottom-up solution that returns the maximum price, as well as the solution array.
The function returns a pair, i.e. a 2-tuple (price, s) where price is the optimal price for the given length n, and s is a list where an element at position i is the length of the optimal first cut for total rod length i.
:param p: the array of prices, with $0 in position 0, and p_i in position i.
:param n: length of rod for which a solution is to be computed (n < p.length)
:type p: list
:type n: int
:rtype: tuple
"""
r = [ None for i in range(0,n+1) ]
r[0]=0
s = [ None for i in range(0,n+1) ]
for j in range(1, n+1):
q = -(2**14)
for i in range(1, j+1):
if q < ( p[i] + r[j-i]):
q = ( p[i] + r[j-i])
s[j]=i
r[j] = q
index_table=list(range(0,n+1))
index_table[0]=None
return (r[n],s[n])
##### TODO ##########################################
def read_solution_array(s, n):
""" Read a solution array, i.e. return the lengths of rod the pieces that make an optimal cut for length n, as a list.
:param s: the solution array, a list where an element at position i is the length of the optimal first cut for total rod length i.
:param n: the length of rod for which a solution is to be read
:rtype: list
"""
pass
############################################################
class Cut_Rod_Test( unittest.TestCase ):
# a class attribute
prices = [0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30]
def test_cut_rod_naive_1(self):
self.assertEqual( cut_rod(self.prices, 5), 13 )
def test_cut_rod_naive_2(self):
self.assertEqual( cut_rod(self.prices, 9), 25 )
def test_memoized_cut_rod_1(self):
self.assertEqual( memoized_cut_rod(self.prices, 5), 13 )
def test_memoized_cut_rod_2(self):
self.assertEqual( memoized_cut_rod(self.prices, 9), 25 )
def test_bottom_up_cut_rod_1(self):
self.assertEqual( bottom_up_cut_rod(self.prices, 5), 13 )
def test_bottom_up_cut_rod_2(self):
self.assertEqual( bottom_up_cut_rod(self.prices, 9), 25 )
def test_memoized_cut_rod_extended_1(self):
max_price, solution_array = memoized_cut_rod_extended(self.prices, 1)
self.assertEqual( max_price, 1 )
self.assertEqual( solution_array, [0, 1])
def test_memoized_cut_rod_extended_2(self):
max_price, solution_array = memoized_cut_rod_extended(self.prices, 5)
self.assertEqual( max_price, 13 )
self.assertEqual( solution_array, [0, 1, 2, 3, 2, 2 ])
def test_memoized_cut_rod_extended_3(self):
max_price, solution_array = memoized_cut_rod_extended(self.prices, 9)
self.assertEqual( max_price, 25 )
self.assertEqual( solution_array, [0, 1, 2, 3, 2, 2, 6, 1, 2, 3] )
def test_read_solution_array_1(self):
max_price, solution_array = memoized_cut_rod_extended(self.prices, 9)
self.assertEqual( read_solution_array( solution_array, 1), [1])
def test_read_solution_array_9(self):
max_price, solution_array = memoized_cut_rod_extended(self.prices, 9)
self.assertEqual( read_solution_array( solution_array, 9), [3,6])
def main():
unittest.main()
if __name__ == '__main__':
main()
|
from random import *
from src.card import *
class Player:
def __init__(self, charac, real):
"""
Class initialiser
:param charac: Selected character
:param boolean real: True if the character is human
"""
self.cards = []
self.character = charac
self.name = charac.name
self.real = real
@staticmethod
def rollDice():
"""
Rolls the dice
:return: a tuple containing the value of each die.
"""
dice1 = randint(1, 6)
dice2 = randint(1, 6)
return dice1, dice2
def checkNextPlayer(self, cards, players):
"""
Finds the first card in the suggested card list that another player is holding.
If no player has the card, None is returned
:param cards: List of cards suggested
:param players: List of players in the game
:return: Card or None
"""
for i, p in enumerate(players): # Outermost loop is for finding position of current player in self.players
if p == self:
for j in range(1, len(players)): # Check next player
if i + j > len(players) - 1: # If we go too far, loop back around
j = -i
for card in players[i + j].cards:
print("check card " + card.name)
if card in cards:
return card # Will only return first card found
print("Check next player")
return None # We have checked all players, so break out of the outermost loop
class HumanPlayer(Player):
def __init__(self, charac):
super().__init__(charac, True)
pass
def suggestion(self, roomcard, weaponcard, charactercard, players):
"""
Human player suggestion method.
Takes input of three cards, compiles into the correct list order and checks other players
in the game for matching cards
:param roomcard: Suggested room
:param weaponcard: Suggested weapon
:param charactercard: Suggested character
:param players: List of players in the game
:return: Card or None
"""
cards = [roomcard, weaponcard, charactercard]
return self.checkNextPlayer(cards, players) # Check if a player in the game has any of the cards suggested
def accusation(self, roomcard, weaponcard, charactercard, envelope):
"""
Human player accusation method
Takes input of three cards, compiles into the correct list order and directly compares it with
the given murder cards envelope.
:param roomcard: Accused room
:param weaponcard: Accused weapon
:param charactercard: Accused character
:param envelope: Game murder envelop (in format [room, weapon, card])
:return: True if the accusation is correct, else False.
"""
cards = [roomcard, weaponcard, charactercard]
return cards == envelope
def showCard(self, suggestedCardsHuman, chosenCard): # showing someone else your card
"""
Show another player, who has made a suggestion, a card of your choice (if that
card is one that has been suggested)
:param suggestedCardsHuman: the cards suggested by the current player
:param chosenCard: the card chosen to be shown to the suggesting player
:return: The players chosen card, or 0 if the player did not have a relevant card
"""
cardsToChooseHuman = []
for card in suggestedCardsHuman:
if card in self.cards:
cardsToChooseHuman.append(card)
# Update UI with cards that can be chosen by the player
if len(cardsToChooseHuman) > 0:
# return UI.getChosenCard()
print("Chosen card")
else:
return 0 # Player does not have any cards, signal game to ask next p
class aiPlayer(Player):
def __init__(self, charac):
Player.__init__(self, charac, False)
def suggestion(self, players):
"""
Ai player suggestion method
Randomly picks a weapon and character card, uses current room.
:param players: List of player in the game
:return: shownCard the card shown the ai player
"""
weapon = choice(list(Weapon.weapons.values()))
room = self.curRoom
char = choice(list(Character.characters.values()))
suggestedCards = [weapon, room, char]
shownCard = self.checkNextPlayer(suggestedCards, players) # retrieve a shown card (if player is shown)
if shownCard != 0: # if there is a shown card, mark notebook
self.notebook.mark(shownCard)
return shownCard
def accusation(self, envelope):
"""
Ai player accusation method
Randomly picks a weapon, room and character to accuse
:param envelope: Game murder envelop (in format [room, weapon, card])
:return: True if the accusation is correct, else False
"""
# Randomly pick cards and use them for accusation
weapon = choice(list(Weapon.weapons.values()))
room = choice(list(Room.rooms.values()))
char = choice(list(Character.characters.values()))
return [room, weapon, char] == envelope
def showCards(self, suggestedCards):
"""
:param suggestedCards: List of another player's suggested cards
:return: The players chosen card, or 0 if the player did not
have a relevant card
"""
cardsToChoose = [] # List of cards available for the player to choose from
for card in suggestedCards:
if card in self.cards:
cardsToChoose.append(card) # if a player has a card that has been suggested, add to list
if len(cardsToChoose) > 0:
return choice(cardsToChoose) # pick a card at random to show
else:
return 0 # Player does not have any cards, signal game to ask next player
|
from src.player import *
from src.card import *
from random import randint, choice, shuffle
class Game:
def __init__(self):
self.curPlayer = None
self.players = []
self.murderCards = None
def addPlayer(self, character):
"""
Adds a player to the current game
:param character: Character card the player is playing as
"""
print("Adding player " + character.name)
self.players.append(HumanPlayer(character))
def sortCards(self):
"""
Creates the murder envelope and deals the cards out to players in the game
"""
# Creating list copies of the dictionaries from card class
weapons = list(Weapon.weapons.values())
rooms = list(Room.rooms.values())
characters = list(Character.characters.values())
p1 = choice(rooms)
p2 = choice(weapons)
p3 = choice(characters)
self.murderCards = [p1, p2, p3] # Randomly pick a card from each category and create the murder envelope
# Remove the murder cards from rest of deck
rooms.remove(p1)
weapons.remove(p2)
characters.remove(p3)
# Combine all cards and shuffle the deck
allCards = weapons + rooms + characters
shuffle(allCards)
p = 0
while len(allCards) > 0: # Deal all the cards out to players
if p > len(self.players) - 1: # Reached end of list so loop back round
p = 0
else:
self.players[p].cards.append(allCards.pop()) # Deal the top card
p += 1
print(len(allCards)) # Should always be 0, indicating all cards have been dealt
def start(self):
"""
Initialises the current player as the first player in the list
"""
self.curPlayer = self.players[0]
print(self.curPlayer.name)
def nextPlayer(self):
"""
Changes the current player to the next player
"""
c = 0
for i, p in enumerate(self.players): # Find the place of the current player in the player list
if p == self.curPlayer:
c = i
break
if c + 1 > len(self.players) - 1: # Reached end of list so loop back round
self.curPlayer = self.players[0]
else:
self.curPlayer = self.players[c + 1]
print(self.curPlayer.name)
def restart(self):
"""
Resets all instance variables
"""
self.curPlayer = None
self.players = []
self.murderCards = None
|
import sys
# dictionaries
# creating new dictionary
# the order of items in dictionary is unpredictable
# items might not retrieved in the same order we inserted
allStatesAndZipCodes = dict()
allAreasAndZipCodes = { 'Washtenaw': 48197, 'Ann Arbor': 48105, 'Ypsilanti': 48198 }
# print(allAreasAndZipCodes['Washtenaw'])
len(allAreasAndZipCodes) # gives the length of the dictionary
# in operator - searches for key in dictionary
print('washtenaw' in allAreasAndZipCodes) # should print False becuase of case-sensitive nature
# to read all the values from dictionary
print(allAreasAndZipCodes.values())
stuff = dict()
print(stuff.get('candy',-1))
|
import math
import random
# function example - no arguments
def printName():
print('Karthik here')
printName()
# function with one argument
def welcomeUser(name):
print('Hello', name, 'welcome to the world of Python')
welcomeUser('Karthik')
# void functions return a special value called 'None' which of type 'NoneType'
# method with return values
def assignUserId(name, userId):
return name + userId
newUser = assignUserId('Karthik', '1991')
print('Welcome', newUser)
|
import sys
# Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages.
# The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail.
# The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file.
# After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.
try:
filename = input('Enter File Name:')
fileHandler = open(filename)
allSenders = dict()
maxValue = 0
maxSender = ''
for line in fileHandler:
line = line.rstrip()
currentListOfWords = line.split()
if line.startswith('From '):
if not currentListOfWords[1] in allSenders:
allSenders[currentListOfWords[1]] = 1
else:
allSenders[currentListOfWords[1]] = allSenders[currentListOfWords[1]] + 1
# greatestSender = max(allSenders, key = allSenders.get)
# print(greatestSender, allSenders[greatestSender])
for sender in allSenders:
if allSenders[sender] > maxValue:
maxSender = sender
maxValue = allSenders[sender]
print(maxSender, maxValue)
except:
print('File Not Found') |
import sys
# Variables, Expression and Statements
message = 'This is Python 3.7.x'
print(message)
#to know the type of varaible use type function
print(type(17))
print(type('Hello Python'))
# Operators and Operands
# Opeators are: + - * / // **
# ** is 'to the power of'
# // is to tell python to ignore decimal part of the remainder
# order of operations happen based on PEMDAS law
x = 10
y = 20
x = x + y
z = y//x
q = x ** 2
v = x/2
print(x)
print(z)
print(q)
print(v)
# string operations
# + Operator - concatenates two string and adds two integers
# When you multiply string with an integer 'x' the result will be string with 'x' times of same value in it
value1 = 'test'
value2 = 2
print(value1 * value2)
# Asking user for the input
# to get the user for the input, use input method
# questionAsked = input('enter today day\n')
# print('Today\'s day is', questionAsked)
# converting string to int - use int(string) method
yourFavNumber = input('Enter your fav number\n')
bffBirthday = int(yourFavNumber) + 16
print('BFF bday is',bffBirthday)
#Lists
countries = ['India', 'USA', 'NZ', 'AUS', 'Pakistan']
print(countries)
|
import socket, sys#, threading, time
#from queue import Queue
"""
NUMBER_OF_THREADS = 2
JOB_NUMBER = [1, 2]
queue = Queue()
all_connections = []
all_address = []
"""
#Create a socket (connecting two or more computers)
def socket_creation():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
#binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
print("Binding the port to " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket, Binding error " + str(msg) + "\n" + "Retrying....")
bind_socket()
#Establish conections with a client (socket must be listening)
def socket_accept():
conn, address = s.accept()
print("Connection has been established " + address[0] + " | Port" + str(address[1]))
send_commands(conn)
conn.close()
#Send commands to client's machine
def send_commands(conn):
while True:
cmd = input()
if cmd == 'quit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024), "utf-8")
print(client_response, end="")
def main():
socket_creation()
bind_socket()
socket_accept()
main() |
import math
#valueSplit is a list of 2 items. The first is number of positive examples,
#the second is the number of negative examples
def calcEntropy(valueSplit):
h = 0.0
probabilityP = valueSplit[0]
probabilityN = valueSplit[1]
totalValues = probabilityN + probabilityP
probabilityP = probabilityP/totalValues
probabilityN = probabilityN/totalValues
h = -probabilityP * math.log2(probabilityP) - probabilityN * math.log2(probabilityN)
#fill this in
return h
#rootValues is a list of the values at the parent node. It consists of 2 items.
#The first is number of positive examples,
#the second is the number of negative examples
#descendantValues is a list of lists. Each inner list consists of the number of positive
#and negative examples for the attribute value you want to split on.
def calcInfoGain(rootValues, descendantValues):
gain = 0.0
totalValues = 0.0
totalEnt = calcEntropy(rootValues)
for node in descendantValues:
totalValues += sum(node) / sum(rootValues) * calcEntropy(node)
gain = totalEnt - totalValues
return gain
if __name__ == "__main__":
attributeName = "Humidity"
rootSplit = [9,5] # 9 positive, 5 negative examples
descendantSplit = [[3,4],[6,1]]
ig = calcInfoGain(rootSplit, descendantSplit)
print("The information gain of splitting on ",attributeName," is: ",ig," bits") |
#values we have
radius=20.0
PI=3.14
#computer area of the circle
area=PI*radius*radius
#print the results
print("area of circle=",area) |
# Print Fibonacci series upto n
a = 0
b = 1
n = 25
while a < n:
print(a)
(a, b) = (b, a + b) |
# insertion sort in increasing order
A = [1, 2, 4, 6, 3, 20]
j = 1
while j < len(A):
key = A[j]
i = j - 1
while i > -1 and A[i] < key:
# swap A[i] and A[i+1]
A[i+1] = A[i]
i -= 1
A[i+1] = key
j += 1
print(A)
|
def main():
# my_list = [8, 7, 6, 5, 4, 3, 2, 1]
my_list = [6, 2, 8, 3, 1, 7, 9, 5, 4]
quick_sort(my_list, 0, len(my_list)-1)
print(my_list)
def quick_sort(numbers, i, j):
if i < j:
l = pivot(numbers, i, j)
print(l)
print(numbers[i:l])
quick_sort(numbers, i, l-1)
print(numbers[l:j])
quick_sort(numbers, l, j)
# noinspection PyPep8Naming
def pivot(numbers, i, j):
p = numbers[i]
k = i
l = j + 1
# move pointer k from left until it points to a value larger than the pivot (p) - or the end of list
while True:
k += 1
if numbers[k] > p or k >= j:
break
# move pointer l from right until it points to a value smaller or equal to the pivot (p)
while True:
l -= 1
if numbers[l] <= p:
break
# if pointer k is to the left of l, swap the elements at k and l - so larger element moves to right; smaller: left.
# do until k is to the right of l i.e. so that everything on the
while k < l:
numbers[k], numbers[l] = numbers[l], numbers[k]
# look for next value larger than pivot from left
while True:
k += 1
if numbers[k] > p:
break
# look for next value smaller than pivot from right
while True:
l -= 1
if numbers[l] <= p:
break
# If pivot smallest value, move to end of sublist...
if l == i:
numbers.insert(j, numbers.pop(l))
print(numbers)
# Otherwise, move pivot to right side of list
else:
numbers[i], numbers[l] = numbers[l], numbers[i]
return l
if __name__ == '__main__':
main()
|
import random
print('This is a book recommendation application')
print('Genres available: history, autobiography, science fiction, non-fiction, children')
selection = input('Please select one of the listed genres to recieve a recommendation: ')
history = ['history book 1', 'history book 2', 'history book 3']
autobiography = ['auto book 1', 'auto book 2', 'auto book 3']
science_fiction = ['sci fi book 1', 'sci fi book 2', 'sci fi book 3']
non_fiction = ['non fiction book 1', 'non fiction book 2', 'non fiction book 3']
children = ['children book 1', 'children book 2', 'children book 3']
if selection == 'history':
print(random.choice(history))
elif selection == 'autobiography':
print(random.choice(autobiography))
elif selection == 'science fiction':
print(random.choice(science_fiction))
elif selection == 'non fiction':
print(random.choice(non_fiction))
elif selection == 'children':
print(random.choice(children))
else:
print('Please select a genre from the list.') |
#!/usr/bin/env python3
# Write a program that given a text file will create a new text file in
# which all the lines from the original file are numbered from 1 to n (where n is
# the number of lines in the file). [use small.txt]
def numbered_lines():
with open("small.txt", "r") as doc:
text = doc.readlines()
file = open("new_small.txt", "w")
number = 1
for line in text:
if len(line) > 0:
file.write(str(number) + " " + line)
number += 1
return None
def main():
numbered_lines()
if __name__ == "__main__":
main()
|
from typing import List
class Solution:
def longestMountain(self, A: List[int]) -> int:
left, mid, right = 0, 0, 0
n, res = len(A), 0
while left < n:
# 寻找升序
mid = left
while mid < n - 1 and A[mid + 1] > A[mid]:
mid += 1
if mid == left:
left = mid + 1
continue
# 寻找降序
right = mid
while right < n - 1 and A[right + 1] < A[right]:
right += 1
if right == mid:
left = right + 1
continue
res = max(res, right - left + 1) # 左右两边都是闭集合
left = right
return res
if __name__ == '__main__':
solution = Solution()
print(solution.longestMountain([2, 1, 4, 7, 3, 2, 5]))
|
from typing import List
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) == 1:
return
last_up = len(nums) - 2
while last_up >= 0 and nums[last_up] >= nums[last_up + 1]:
last_up -= 1
if last_up == -1:
nums[:] = nums[::-1]
else:
first_large = len(nums) - 1
last_up_val = nums[last_up]
while first_large >= 0 and nums[first_large] <= last_up_val:
first_large -= 1
if first_large == -1:
nums[:] = nums[::-1]
else:
nums[last_up] = nums[first_large]
nums[first_large] = last_up_val
nums[last_up + 1:] = nums[last_up + 1:][::-1]
print(nums)
if __name__ == '__main__':
solution = Solution()
nums = [5, 1, 1]
solution.nextPermutation(nums)
|
from typing import List
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
wordSet = set(wordList)
if endWord not in wordSet:
return 0
stack1 = [beginWord]
stack2 = []
step = 1
visited = {w: False for w in wordList}
char_list = [chr(ord('a') + i) for i in range(26)]
while len(stack1) != 0 or len(stack2) != 0:
if len(stack1) == 0:
stack1 = stack2
stack2 = []
step += 1
cur_word = stack1.pop()
for i in range(len(cur_word)):
for j in range(26):
if char_list[j] == cur_word[i]:
continue
tmp_word = cur_word[:i] + char_list[j] + cur_word[i + 1:]
if tmp_word in wordSet and not visited[tmp_word]:
if tmp_word == endWord:
return step + 1
stack2.append(tmp_word)
visited[tmp_word] = True
return 0
if __name__ == '__main__':
solution = Solution()
wordList = ["hot", "dot", "dog", "lot", "log", "cog"]
beginWord = "hit"
endWord = "cog"
print(solution.ladderLength(beginWord, endWord, wordList))
|
def get_rps(player):
while True:
choice = input(f'Player {player}, choose (R)ock/(P)aper/(S)cissors\n').upper()
if choice in ['R', 'S', 'P']:
print('\n'*100)
break
else:
print('Your choice was not R/S/P.')
return choice
p1_wins = 0
p2_wins = 0
play_to = 1
while True:
while True:
choice1 = get_rps(1)
choice2 = get_rps(2)
if choice1 == choice2:
print(f'It\'s a tie between two {choice1}s')
else:
break
winners = {
'R': 'S',
'P': 'R',
'S': 'P'
}
if winners[choice1] == choice2:
p1_wins += 1
else:
p2_wins += 1
if p1_wins == play_to or p2_wins == play_to:
print(f'Player {1 if p1_wins > p2_wins else 2} is the winner!')
while True:
more = input(f'Do you want to play best {play_to+1} out of {(play_to+1)*2-1}?(N/Y)').upper()
if more == 'Y':
play_to += 1
break
elif more == 'N':
break
else:
continue
if more == 'N':
break
|
# Get word to be guessed, and then hide it
# While user has more guesses:
# Ask for user to guess a letter or entire word,
# show word guessed until now and show him number of guesses left
# if letter - reveal letters in word
# if all letters in original word were guessed - notify and end game
# if word
# if wrong - notify
# if right - notify and end game
# reduce number of guesses
# if no more guesses - notify and end game
word = input('Insert a word to be guessed\n')
show_word = '_' * len(word)
print('\n' * 100)
guesses = 10
guessed_letters = set()
while True:
guess = input(f'Guess a letter or word (already guessed {", ".join(guessed_letters) if guessed_letters else "nothing"}): {show_word}\n')
if len(guess) == 1:
guessed_letters.add(guess.lower())
show_word = ''.join([c if c.lower() in guessed_letters else '_' for c in word])
if '_' not in show_word:
print(f'You completed the word: {word}')
break
if len(guess) > 1:
if guess == word:
print(f'You guessed the word: {word}')
break
else:
print(f'Sorry, "{guess}" is not the correct word')
guesses -= 1
if not guesses:
print(f'Sorry, the game has ended. The word was {word}')
break
|
from argparse import ArgumentParser
from magic_formatter import MagicFormatter
if __name__ == '__main__':
"""
if you are running from the terminal you can either pass a text as a String
or a file location, if on the same path just pass the file name.
Also, you need to pass the width of the text you want to format.
"""
parser = ArgumentParser()
parser.add_argument('text', type=str, help='insert text, file name or file path')
parser.add_argument('width', type=int, help='insert width of text')
args = parser.parse_args()
if args:
formatter = MagicFormatter(args.text, args.width)
formatter.reformat_text('output-parte1.txt')
formatter.reformat_text('output-parte2.txt', True)
|
type = 7
# Python Strings https://www.w3schools.com/python/python_strings.asp
if type == 1:
a = """test
123""" # multi line strings
print(a)
print(a[0]) # strings are arrays
if len(a) > 1: # length of a string, use the len() function.
for x in a: # Since strings are arrays, we can loop through the characters in a string, with a for loop.
print(x)
print("test" in a) # Check if "free" is present or use not in to see if its not there
if "free" in a: # check can be used in if
print("Yes, 'test' is present.")
# Slicing Strings
if type == 2:
a = "hello, world!" # first character has index 0.
print(a[:5]) # gives the first five
print(a[2:]) # from 2 to the end
print(a[-5:-2]) # -2 removes 2 from the end and -5 means include form char 5 to the end
# modify Strings
if type == 3:
a = " hello, world! "
print(a.upper()) # all upper case
print(a.lower()) # all lower case
print(a.strip()) # removes white space from start and end
print(a.replace("h", "J")) # replaces first char with the second
print(a.replace(" ", "")) # can be used to remove blank space
print(a.split(",")) # returns ['Hello', ' World!']
# String Concatenation
if type == 4:
a = "Hello"
b = "World"
c = a + " " + b
print(c)
# Format - Strings
if type == 5:
quantity = 3 # index 1
itemno = 567 # index 2
price = 49.95 # index 3
myorder = "I want to pay {2} dollars for {0} pieces of item {1}." # {1} means put index one here so if makes sure they go in the write spots
print(myorder.format(quantity, itemno,
price)) # grab variable and put it in the string if indexed put it there other wise first goes first
# Escape Character
if type == 6:
txt = "We are the so-called \"Vikings\" from the north." # The escape character allows you to use double quotes when you normally would not be allowed
print(txt) # there are other escape characters look them up
# String Methods
if type == 7: # dont work just look and find what you want online
a = "hello, world!"
a.capitalize() # Converts the first character to uppercase
a.casefold()
a.center(20)
a.count("hell")
a.encode()
a.endswith()
a.expandtabs()
a.find()
a.format()
a.format_map()
a.index()
a.isalnum()
a.isalpha()
a.isdecimal()
a.isdigit()
a.isidentifier()
a.islower()
a.isnumeric()
a.isprintable()
a.isspace()
a.istitle()
a.isupper()
a.join()
a.lstrip()
a.maketrans()
a.partition()
a.replace()
a.rfind()
a.rindex()
a.rpartition()
a.rsplit()
a.rstrip()
a.split()
a.splitlines()
a.startswith()
a.swapcase()
a.title()
a.translate()
a.upper()
a.zfill() |
"""
Inventory
---------
Calculate and report the current inventory in a warehouse.
Assume the warehouse is initially empty.
The string, warehouse_log, is a stream of deliveries to
and shipments from a warehouse. Each line represents
a single transaction for a part with the number of
parts delivered or shipped. It has the form::
part_id count
If "count" is positive, then it is a delivery to the
warehouse. If it is negative, it is a shipment from
the warehouse.
Use the functions provided in your solution, where process_log
parses the warehouse log string, and produces a list of
transactions, and process_transactions generates an inventory
dict from a list of transactions. The function generate_inventory
calls process_log, then process_transactions.
"""
def process_log(log):
""" Process a warehouse log string containing part names and counts.
Return an iterator for a list of transactions.
"""
return (line.strip().rsplit(None,1) for line in log.strip().split('\n'))
#ALTERNATE SOLUTION:
#import itertools
#items = log.split()
#return itertools.izip(items[::2],items[1::2])
def process_transactions(transactions, inventory={}):
"""Given a list of transactions and optionally an initial inventory,
compute and return the final inventory for each part.
"""
for part, count in transactions:
inventory[part] = inventory.get(part, 0) + int(count)
return inventory
def generate_inventory(log):
""" Process a warehouse log string containing part names and counts.
Returns a dict with the inventory of each part.
"""
return process_transactions(process_log(log))
if __name__ == '__main__':
warehouse_log = """ lightcycle 10
hoverboard 5
lightsaber 12
lightcycle -3
lightcycle 20
phaser 40
hoverboard -4
lightsaber -8
"""
for part, count in generate_inventory(warehouse_log).iteritems():
print '{0:>20s}: {1:>5d}'.format(part, count)
|
b=input("enter a string\n")
rev=""
for i in range(len(b)-1,-1,-1):
rev=rev+b[i]
if rev==b:
print("string is palindrome")
else:
print("string is not palindrome")
|
b=input("enter a first string\n")
c=input("enter a second string\n")
x=sorted(b)
y=sorted(c)
if x==y:
print("two string are anagram")
else:
print("two strings are not anagram")
|
from constants import GENDER_MALE
from constants import GENDER_FEMALE
class Member(object):
def __init__(self, founder, gender):
"""
founder: string
Initializes a member.
Name is the string of name of this node,
gender specifies the gender of the member
mother, father, spouse are None, and no children
"""
self.name = founder
self.gender = gender
self.mother = None
self.father = None
self.spouse = None
self.children = []
self.siblings = []
def __str__(self):
return self.name
def can_add_child(self):
return self.gender == GENDER_FEMALE
def add_child(self, new_child):
"""
child: Member
Adds another child Member node to this Member
"""
# adding new child to siblings of the parent children
new_child.mother = self
new_child.father = self.spouse
new_child.siblings += self.children
for child in self.children:
child.siblings.append(new_child)
self.children.append(new_child)
self.spouse.children.append(new_child)
def get_son(self):
return [child for child in self.children if child.gender == GENDER_MALE]
def get_daughter(self):
return [child for child in self.children if child.gender == GENDER_FEMALE]
def get_siblings(self):
return self.siblings
def get_brothers(self):
return [sibling for sibling in self.siblings if sibling.gender == GENDER_MALE]
def get_sisters(self):
return [sibling for sibling in self.siblings if sibling.gender == GENDER_FEMALE]
|
# -*- coding:utf-8 -*-
# __author__ :kusy
# __content__:文件说明
# __date__:2018/9/30 17:28
class MyStack(object):
def __init__(self, alist=None):
if alist == None:
self.stack_list = []
self.count = 0
else:
self.stack_list = alist
self.count = len(alist)
# 栈中添加值
def push(self, value):
self.stack_list.insert(0,value)
self.count += 1
#返回栈顶元素值
def peek(self):
if self.count:
return self.stack_list[0]
return None
# 删除栈顶元素
def pop(self):
self.stack_list.pop(0)
self.count -= 1
# 返回栈是否为空
def is_empty(self):
if self.count == 0:
return True
else:
return False
#打印栈内容
def print_all(self):
for sl in self.stack_list:
print(sl) |
str = ''
length = 0
while (length < 1):
str = input("Enter any valid string\n")
length = str.replace(" ","").__len__()
if length == 0:
print("Entered String length is zero\n")
print("Length of '",str,"' is (excluding spaces):",length) |
import json
print(json.dumps([1, 'simple', 'list']))
with open('file1') as f:
json.dump(x, f)
#To decode the object again, if f is a text file object which has been opened for reading:
x = json.load(f)
print(x) |
strs = ["flower","flow","flight"]
# First approach: 36 ms, 14.2 mb
common_word = ''
def LCP(strs):
if strs == None or len(strs) == 0:
return ''
for letter in range(len(strs[0])): # For each letter in the first word (strs[0])
current_letter = strs[0][letter] # First word, current letter
for word in range(1, len(strs)):
if letter == len(strs[word]) or strs[word][letter] != current_letter:
common_word = strs[0][:letter]
return common_word
return strs[0] # If all words are equal or there is only 1 word, return it
# Second approach - Pythonic: 36 ms, 14.4 mb
def LCP2(strs):
if strs == None or len(strs) == 0:
return ''
for letter in range(len(strs[0])+1):
common_word = strs[0][0:letter+1]
for word in strs[1:]:
if not word.startswith(common_word):
return strs[0][:letter]
return strs[0][:letter]
print(LCP(strs))
print(LCP2(strs))
|
# Ejercicio 1: Mision TIC Colombia
calificaciones = list()
# Ingresar 10 calificaciones:
for i in range(10):
while True:
try: # Verifica que el input sea correcto
calificacion = int(input(f'Ingrese la calificacion {i}: '))
break
except:
print('Ingrese un valor correcto...')
calificaciones.append(calificacion)
# Imprime todas las calificaciones
print(calificaciones)
# List comprehension (LC): Genera una lista que cumplan la condición: calificacion >= 7 a partir de la lista calificaciones
mayores_o_iguales_a_7 = [calificacion for calificacion in calificaciones if calificacion >= 7]
# Imprime la lista mayores_o_iguales_a_7
print(f'Calificaciones mayores o iguales a 7: {mayores_o_iguales_a_7}')
# Imprime la cantidad de elementos en la lista mayores_o_iguales_a_7
print(f'Hay {len(mayores_o_iguales_a_7)} mayores o iguales a 7')
print(f'Hay {len(calificaciones) - len(mayores_o_iguales_a_7)} menores a 7')
## Adicional
# En caso se desee guardar el índice de las calificaciones: key,value = index,calificacion
dict_index_calificacion = dict()
for index in range(len(calificaciones)):
if calificaciones[index] >= 7:
dict_index_calificacion[index] = calificaciones[index]
print(dict_index_calificacion) |
from vartree import *
from linkedlist import *
def eval_postfix(tree, iterator):
vartree = tree
stack = LinkedList()
current = (next(iterator))
while current is not None:
current = str(current)
if current.isdigit():
stack.push((current))
try:
current = next(iterator)
except StopIteration:
break
elif current.isalnum():
stack.push((vartree.lookup(current)))
try:
current = next(iterator)
except StopIteration:
break
else:
operator = str(current)
right = str(stack.pop()._value)
left = str(stack.pop()._value)
if(operator is '='):
vartree.assign(left,right)
stack.push(left)
else:
if not is_number(left):
left = vartree.lookup(left)
if not is_number(right):
right = vartree.lookup(right)
ans = eval(str(left) + operator + str(right))
stack.push(ans)
try:
current = next(iterator)
except StopIteration:
break
ans = str(stack.pop()._value)
if ans.isalpha():
return vartree.lookup(ans)
else:
return ans
def is_number(s):
try:
float(s)
return True
except ValueError:
return False |
from random import choice
score=[0,0]
direction=['left','center','right']
def kick():
print'======YOU KICK====='
print'CHOOSE ONE SIDE TO SHOOT'
you=raw_input()
print'YOU KICKED'+you
com=choice(direction)
print'COMPUTER SAVED'+com
if you!=com:
print'GOAL'
score[0]+=1
else:
print'OPPS'
print'SCORE:%d(YOU)--%d(COMPUTER)'%(score[0],score[1])
print'======COMPUTER KICK====='
print'CHOOSE A SDIE TO SAVE'
you=raw_input()
print'YOU SAVED'+you
com=choice(direction)
print'COMPUTER KICKD'+com
if you!=com:
print'YOU MISSED'
score[1]+=1
else:
print'NICE!!!'
print'SCORE:%d(YOU)--%d(COMPUTER)'%(score[0],score[1])
for i in range(5):
print'=====ROUND %d======'%(i+1)
kick()
if score[0]>score[1]:
print'YOU WIN'
else:
print'YOU Lose'
|
from heapq import heappush, heappop
import enum
class Node():
def __init__(self, id=None):
self.id = id
self.neighbors = {}
def __repr__(self):
return str(self.id)
def __lt__(self, other):
# this is only implemented so that heappop can run
# the actual implementation shouldn't affect the answer
return self.id < other.id
class Edge():
def __init__(self, turn, distance, speed=10):
self.distance = distance
self.turn = turn
self.speed = speed
def __repr__(self):
return "({}, {}, {})".format(self.turn, self.distance, self.speed)
class Turn(enum.Enum):
left = 0
right = 1
straight = 2
def __lt__(self, other):
# heappop needs this to be defined
# the implementation doesn't matter
return False
''''
Returns a list of all the duckietown nodes in order
with correctly arranged edges. Note that the array is
0-indexed while the duckietown representation is
1-indexed so nodes are off by one, i.e. "node 8" is at
position 7 in the list
'''
def get_duckietown():
nodes = [Node(i+1) for i in range(12)]
# construct the graph
nodes[0].neighbors[nodes[11]] = \
Edge(Turn.straight, 2)
nodes[0].neighbors[nodes[3]] = \
Edge(Turn.left, 2)
nodes[1].neighbors[nodes[3]] = \
Edge(Turn.right, 2)
nodes[1].neighbors[nodes[7]] = \
Edge(Turn.straight, 2)
nodes[2].neighbors[nodes[7]] = \
Edge(Turn.right, 2)
nodes[2].neighbors[nodes[11]] = \
Edge(Turn.left, 2)
nodes[3].neighbors[nodes[6]] = \
Edge(Turn.left, 4)
nodes[3].neighbors[nodes[10]] = \
Edge(Turn.right, 3)
nodes[4].neighbors[nodes[2]] = \
Edge(Turn.left, 2)
nodes[4].neighbors[nodes[6]] = \
Edge(Turn.straight, 4)
nodes[5].neighbors[nodes[2]] = \
Edge(Turn.right, 2)
nodes[5].neighbors[nodes[10]] = \
Edge(Turn.straight, 4)
nodes[6].neighbors[nodes[0]] = \
Edge(Turn.left, 2)
nodes[6].neighbors[nodes[9]] = \
Edge(Turn.straight, 8, speed=15)
nodes[7].neighbors[nodes[5]] = \
Edge(Turn.right, 4)
nodes[7].neighbors[nodes[9]] = \
Edge(Turn.left, 8, speed=15)
nodes[8].neighbors[nodes[0]] = \
Edge(Turn.right, 2)
nodes[8].neighbors[nodes[5]] = \
Edge(Turn.straight, 4)
nodes[9].neighbors[nodes[1]] = \
Edge(Turn.left, 2)
nodes[9].neighbors[nodes[4]] = \
Edge(Turn.straight, 4)
nodes[10].neighbors[nodes[1]] = \
Edge(Turn.right, 2)
nodes[10].neighbors[nodes[8]] = \
Edge(Turn.straight, 8, speed=15)
nodes[11].neighbors[nodes[4]] = \
Edge(Turn.left, 4)
nodes[11].neighbors[nodes[8]] = \
Edge(Turn.right, 8, speed=15)
return nodes
def get_path(start_node, end_node):
# BFS
q = [ (0, start_node, [], []) ] # queue of (distance, node, [(turn, speed)], [nodes]) tuples
while len(q) > 0:
dist, node, directions, sequence = heappop(q)
if node == end_node:
return directions, sequence
for nnode in node.neighbors:
edge = node.neighbors[nnode]
new_dist = dist + edge.distance
new_directions = directions[:] + [(edge.turn, edge.speed)]
new_sequence = sequence[:] + [nnode.id]
q.append( (new_dist, nnode, new_directions, new_sequence) )
'''
starting at node_list[0], this function returns a
list of instructions to hit all the nodes in order
'''
def get_tour(node_list):
directions, sequence = [], [node_list[0].id]
for i in range(len(node_list) - 1):
new_directions, new_sequence = get_path(node_list[i], node_list[i + 1])
directions += new_directions
sequence += new_sequence
return directions, sequence
'''
Convinient, human freindly version of get_tour that
takes a list of integers that are interpreted as the
1-indexed duckietown node sequence
'''
def get_duckietown_tour(int_list):
graph = get_duckietown()
sequence = [graph[i - 1] for i in int_list]
directions, full_sequence = get_tour(sequence)
return iter(directions), full_sequence
# for testing things
if __name__ == "__main__":
# graph = get_duckietown()
# print(get_path(graph[8], graph[9]))
# sequence = [graph[8], graph[9], graph[11]]
# print(get_tour(sequence))
# print(get_duckietown_tour([9, 10, 12]))
sequence = [2, 6, 3, 1, 10, 7, 6, 4, 9, 1, 3]
# sequence = [4, 2]
directions, full_sequence = get_duckietown_tour(sequence)
print(list(directions))
print(full_sequence)
|
# def convert(hex_number):
#
# result = int(hex_number, 16)
#
# return result
#
#
# hex_number1 = input("Please enter a hex number.")
# hex_number2 = input("Please enter a hex number.")
# #print(convert(hex_number))
# print(convert(hex_number1) + convert(hex_number2))
# score = 10
# answer = 9
# if answer == 10:
# score = score + 1
# else:
# score = score + 5
# print(score)
def decimal(hex_number):
# STEP ONE: take the first digit
first_digit = hex_number[0]
if first_digit == 'A':
first_digit = 10
elif first_digit == 'B':
first_digit = 11
elif first_digit == 'C':
first_digit = 12
#etc
first_digit = int(first_digit)
#print(first_digit)
# STEP TWO: times by 16
total = first_digit * 16
#print(total)
# STEP THREE: add the second digit
second_digit = hex_number[1]
if second_digit == 'A':
second_digit = 10
elif second_digit == 'B':
second_digit = 11
elif second_digit == 'C':
second_digit = 12
# etc
second_digit = int(second_digit)
total = total + second_digit
print(total)
decimal('3A') |
from tkinter import *
import tkinter as tk
def hello(e=None):
print('Hello')
tk.Button(root, text='say hello', command=hello).pack()
root.bind('<Escape>', lambda e: root.quit())
root.bind('h', hello)
root.mainloop() |
# CODE for EXERCISE 1
# -------------------
#
# Import the Tkinter package
# Note in Python 3 it is all lowercase
import tkinter as tk
from tkinter import *
# This method is called when the button is pressed
def clicked():
print("Clicked")
# Create a main frame with
# - a title
# - size 200 by 200 pixels
app = Tk()
app.title("GUI Example 1")
app.geometry('200x200')
# Create the button
# - with suitable text
# - a command to call when the button is pressed
button1 = Button(app, text="Click Here", command=clicked)
# Make the button visible at the bottom of the frame
button1.pack(side='bottom')
# Start the application running
app.mainloop()
|
# CODE for EXERCISE 6
# -------------------
# This exercise introduces
# * The radio button widget
#
# MAKE THE FOLLOWING CHANGES
# * change the text of the radio buttons to colours
# * when the selection is made, change th background colour of the label
#
from tkinter import *
root = Tk()
# Method handles radio button selection
# * Create a string showing which choice selected
# * Use this in the label
def sel():
selection = "You selected the option " + str(var.get())
label["text"] = selection
# Integer control variable
# Holds the selection of the radio button
var = IntVar()
# Create 2 radio buttons. Each has the same control variable
#
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text="Option 2", variable=var, value=2,
command=sel)
R2.pack( anchor = W )
# Create a label. Intially blank
label = Label(root)
label.pack()
# Start the main loop
root.mainloop()
|
## validate tutor group name function
def check_tutor_group_name(tutor_group_name):
validated = True
## it has to have 2 or 3 characters
if len(tutor_group_name) < 2 or len(tutor_group_name) > 3:
validated = False
print("The length of the tutor group name is incorrect.")
## it has to have a number between 7 and 11 in the beginning
if len(tutor_group_name) == 3:
# TESTING SPLITTING STRINGS IN PYTHON
# my_string = "01234"
# print(my_string[:2])
if tutor_group_name[:2] not in ["10", "11"]:
validated = False
print("The year group should be 10 or 11.")
if tutor_group_name[2:] not in ["A", "B", "C", "D", "E", "F"]:
validated = False
print("The tutor group for Year 10 or 11, should be A to F.")
elif len(tutor_group_name) == 2:
### Debugging splitting the string
# my_string = "7A"
# print(my_string[:2])
# print(my_string[:1])
if tutor_group_name[:1] not in ["7", "8", "9"]:
validated = False
print("The year group should be 7, 8, or 9.")
if tutor_group_name[1:] not in ["A", "B", "C", "D", "E", "F"]:
validated = False
print("The tutor group for years 7 to 9 should be A to F.")
return validated
|
class Person:
department = 'School of Information' #a class variable
def set_name(self, new_name): #a method
self.name = new_name
def set_location(self, new_location):
self.location = new_location
person = Person()
person.set_name('Christopher Brooks')
person.set_location('Ann Arbor, MI, USA')
print('{} live in {} and works in the department {}'.format(person.name, person.location, person.department))
# maps
store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = map(min, store1, store2)
cheapest
for item in cheapest:
print(item) |
import time
import turtle
class Stack:
def __init__(self):
self.items = []
self.height = 50
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
def __draw_stack(self, pencil_color, filling_color):
drawing = turtle.Turtle()
drawing.color(pencil_color, filling_color)
drawing.speed(10)
for pos, item in enumerate(self.items):
self.__square(drawing)
# draw value in the middle of the square
drawing.penup()
drawing.right(90)
drawing.forward(self.height / 2)
drawing.right(90)
drawing.forward(self.height / 2)
drawing.write(item, False, align='center')
drawing.right(90)
drawing.forward(self.height / 2)
drawing.right(90)
drawing.forward(self.height / 2)
drawing.pendown()
# moves the pen to the next starting position
if pos + 1 != self.size():
drawing.forward(self.height)
drawing.right(90)
return drawing
def __square(self, drawing):
drawing.forward(self.height)
drawing.right(90)
drawing.forward(self.height)
drawing.right(90)
drawing.forward(self.height)
drawing.right(90)
drawing.forward(self.height)
def draw_peek(self, pencil_color='black', filling_color='red'):
drawing = self.__draw_stack(pencil_color, filling_color)
drawing.penup()
drawing.right(180)
drawing.forward(self.height / 2)
drawing.pendown()
drawing.circle(self.height/2)
time.sleep(5)
def draw(self, pencil_color='black', filling_color='red'):
self.__draw_stack(pencil_color, filling_color)
time.sleep(5)
test = Stack()
for _ in range(3):
test.push(_)
test.draw_peek()
|
import os # listing directory contents, determining files from directories
import argparse # CLI
import sys # get command-line arguments with sys.argv
from typing import List, Iterator # type hinting
argparser = argparse.ArgumentParser(description="pypree - A partial Python tree command implementation")
argparser.add_argument("-p",
"--path",
metavar="PATH",
nargs="+",
default=".",
help="Path(s) to one or more directories to build the tree(s) at." +
" Defaults to current directory.")
argparser.add_argument("-a",
"--all",
action="store_true",
help="Specify this option to also include hidden files and directories" +
" in the final output.")
def main(argv = sys.argv[1:]):
"""Runs the program."""
args = argparser.parse_args(argv)
show_hidden = args.all if args.all else False
for path in args.path:
print(create_tree(path=path, show_hidden=show_hidden))
class TreeItem(object):
"""Represents an item in the tree."""
name = None
fullpath = None
isdir = False
parent = None
children = []
# direct number of file and directory type
# TreeItem children
nfiles = ndirs = 0
def __init__(self, name: str, fullpath: str, isdir: bool, parent, children: List,
nfiles: int, ndirs: int):
self.name = name
self.fullpath = fullpath
self.isdir = isdir
self.parent = parent
self.children = children
self.nfiles = nfiles
self.ndirs = ndirs
def __str__(self):
dir_count = count_dirs(self)
file_count = count_files(self)
dir_string = "directory"
if dir_count > 1:
dir_string = "directories"
return tree_to_string(self, indent=0) + \
"\n{} {}, {} files".format(dir_count, dir_string, file_count)
def create_tree(path: str, parent=None, show_hidden=False) -> TreeItem:
"""Creates a tree-like representation of the directory at `path`."""
rpath = os.path.realpath(path)
name = os.path.split(rpath)[1]
# root Tree item
if parent == None:
if path == ".":
rpath = path
# Base Cases: we have a file and not a directory, or we have an
# empty directory
if not os.path.isdir(rpath):
ti = TreeItem(name=name, fullpath=rpath, isdir=False, parent=parent, children=[],
nfiles=0, ndirs=0)
return ti
elif not os.listdir(rpath):
ti = TreeItem(name=name, fullpath=rpath, isdir=True, parent=parent, children=[],
nfiles=0, ndirs=0)
return ti
# Recursive case: directory with one or more children
w = os.walk(rpath)
# children = []
_, dirnames, filenames = get_next(w)
# Form the new parent
new_parent = TreeItem(name=name, fullpath=rpath, isdir=True, parent=parent, children=[],
nfiles=0, ndirs=0)
# process file and directory children simultaneously
# so output will match tree
items = dirnames + filenames
# count of hidden files and dirs, respectively
fc_hidden = dc_hidden = 0
for item in sorted(items):
item_path = os.path.join(rpath, item)
if os.path.isdir(item_path):
if not show_hidden and item.startswith("."):
dc_hidden += 1
continue
dc = create_tree(item_path, show_hidden=show_hidden)
# need this to keep dc from setting it's parent field to None
dc.parent = new_parent
new_parent.children.append(dc)
else:
if not show_hidden and item.startswith("."):
fc_hidden +=1
continue
fc = TreeItem(name=item, fullpath = item_path, isdir=False, parent=new_parent, children=[],
nfiles=0, ndirs=0)
new_parent.children.append(fc)
new_parent.nfiles = len(filenames) - fc_hidden
new_parent.ndirs = len(dirnames) - dc_hidden
return new_parent
def tree_to_string(ti: TreeItem, indent: int) -> str:
"""Creates a string representation of a TreeItem."""
tree_string = ""
indent_val = indent
# Case: I am the root/start TreeItem. I'll use my
# real path name
if indent_val == 0:
tree_string += ti.fullpath + "\n"
tree_string += tree_to_string(ti, indent=indent + 1)
# Case: also the root/start TreeItem. Here, I iterate
# over my children by adding their string representations
# to mine
elif indent_val == 1:
for _, child in enumerate(ti.children):
tree_string += tree_to_string(ti=child, indent=indent + 1)
else:
# Case: I am not a direct child of the root TreeItem. I need
# to traverse upwards in my lineage to determine how many of
# my parents are the last children of their parents.
skip_lines = []
saved_ti = ti
# go all the way back up to the root
while(ti.parent is not None):
if ti.parent.parent is not None:
ti_gp = ti.parent.parent
names = [c.name for c in ti_gp.children]
# Idea: the child's parent is the last child of grandparent,
# so we skip the line that would be directly under the
# grandparent. Since we're traversing upwards (i.e. right
# to left in final output), we insert bars or spaces in
# reverse order (i.e. insert at index 0)
if sorted(names)[-1] == ti.parent.name:
skip_lines.insert(0, " ")
else:
skip_lines.insert(0, "│ ")
# go up one level for the next iteration
ti = ti.parent
# restore original TreeItem after iteration completes
ti = saved_ti
bars = "".join(skip_lines)
names = [c.name for c in ti.parent.children]
# last child has "└──"
if sorted(names)[-1] == ti.name:
ts = bars + "└── " + ti.name + "\n"
tree_string += ts
else:
# other children have "├──"
tree_string += bars + "├── " + ti.name + "\n"
# I recurse on my children so they can do the same
# thing as me
for _, child in enumerate(ti.children):
tree_string += tree_to_string(ti=child, indent=indent + 1)
return tree_string
def count_files(ti: TreeItem) -> int:
"""Counts the number of TreeItems of file type below this one."""
if not ti.children:
return 0
else:
return ti.nfiles + sum([count_files(c) for c in ti.children])
def count_dirs(ti: TreeItem) -> int:
"""Counts the number of TreeItems of directory type below this one."""
if not ti.children:
return 0
else:
return ti.ndirs + sum([count_dirs(c) for c in ti.children])
def get_next(it: Iterator):
"""Wrapper on walk iterator __next__ method."""
return it.__next__()
|
from operator import itemgetter
from collections import Counter
import random
class NoMoveSet(Exception):
pass
class Player(object):
"""
Default type of player, is human.
Needs input
"""
next_move = None
def __init__(self, symbol, opponent_symbol, player_type="human"):
self.symbol = symbol
self.opponent_symbol = opponent_symbol
self.type = player_type
def make_move(self, board):
if self.next_move is not None:
position = self.next_move
self.next_move = None
return position
raise NoMoveSet("Player has Not made a decision")
def set_move(self, position):
self.next_move = position
class AIPlayer(Player):
"""
Automated player, that is quite frustrating to play against.
No real strategy. It evaluates potential fields makes a choice to maximize points
or random betwen equally scored cells
- center is always of high value
- the board may be given other biases
- assume board is made out of 9 cells
"""
winning_states = [
[1,2,3],
[4,5,6],
[7,8,9],
[1,4,7],
[2,5,8],
[3,6,9],
[1,5,9],
[3,5,7],
]
def __init__(self, symbol, opponent_symbol, player_type="AI"):
super(AIPlayer, self).__init__(symbol, opponent_symbol, player_type=player_type)
def get_potential_moves(self, board):
"""
Get a list of possible moves for a given board state
"""
scored_board = self.score_current_board(board)
max_score = max(scored_board)
valid_moves = []
for i, value in enumerate(scored_board):
if max_score and value == max_score:
valid_moves.append(i)
return valid_moves
def make_move(self, board):
"""
Strategy to choose from valid moves
this is what will be played on the board
"""
valid_moves = self.get_potential_moves( board)
if not valid_moves:
return valid_moves
elif len(valid_moves) == 1:
return valid_moves.pop()
else:
index = random.randrange(len(valid_moves))
return valid_moves[index]
def calculate_state_score_weight(self, state):
"""
Given a row score it base on what it contains
# 0: if the row is full
# 2: if it contains a single symbol
# 4: if it contains two of the same symbols
# 5: if it contains two of the same symbols that are the player's
"""
row_tally = Counter(state)
bonus = 0
weight = 0
# filter out the Nones so we don't count them
row_tally = dict([
(symbol, count) for symbol,count in row_tally.items() \
if symbol is not None
])
checksum = sum(row_tally.values())
if checksum == 3: # if the row is full
return 0
if checksum == 2 and len(row_tally.values()) == 1: # the row is almost full with one symbol
bonus = 5
if self.symbol in row_tally: # it's the AI's symbol so ad bonus for that
bonus += 3
if checksum == 1: # if there is a single sybol in this row score itas one
bonus = 1
weight = 1 + bonus
return weight
def score_current_board(self, board):
scored_board = [0 for i in range(9)]
# add bias
# score the center cell at 3 to start with
scored_board[4] = 3
# add bias for second and third moves
# we want to score the cross higher surrounding the center
# higher
if board.count(None) in [6,7]:
scored_board[1] = 3
scored_board[3] = 3
scored_board[5] = 3
scored_board[7] = 3
for state in self.winning_states:
# align indexes to 0
zeroed_index = map(lambda x: x-1, state)
# get row
board_values = itemgetter(*zeroed_index)(board)
# calculate the score for that row
score = self.calculate_state_score_weight(board_values)
# apply score to each cell
for i in zeroed_index:
if board[i] is None:
scored_board[i] += score
else:
scored_board[i] = None
return scored_board
|
#!/usr/bin/python3
a = 1
b = 2.0
c = 10000000000000000000000000000000000000000
d = "what's your problem"
e = " There is a space "
print("Hello world")
print (a)
print ("a = %d" % a)
print (b)
print ("\tb^3 = %f" % b**3)
print (c+1)
print (d + " fuck off")
print (d.upper())
print (d.title())
print (e.rstrip())
print (e.lstrip())
print ("wow %f" % (b/2))
|
# BlueOrange -- Tania Cao, Jack Lu
# SoftDev1 pd8
# K06 -- StI/O: Divine your Destiny!
# 2018-09-13
import csv
import random
# Chooses random occupation based on percentage of US workforce comprised of it.
def choose(fileName):
# Builds a dictionary of careers occupations and percentage of US workforce.
dict = {}
with open(fileName, 'rt') as csvfile:
reader = csv.reader(csvfile)
heading = reader.__next__() # skips column labels Job Class, Percentage
for i in reader:
dict[ i[0] ] = float( i[1])
del dict['Total'] # Deletes total percentage
jobs = list(dict.keys()) # Created a list of keys to support indexing.
# Chooses a job using corresponding values as relative weights. [0] because random.choices returns a list.
fate = random.choices(jobs, dict.values())[0]
return fate
print("You shall work in " + choose('occupations.csv') + " for the rest of your life.")
|
def findNonRepeatedChar (string):
stringList = list(string)
charMap = {}
for char in stringList:
if char not in charMap:
charMap[char] = 1
else:
charMap[char] += 1
for char in stringList:
if charMap[char] == 1:
return char
print(findNonRepeatedChar(input("String to analyze: "))) |
import random
def hangMan(guessCount):
if guessCount == 0:
print("|----|")
print("| ")
print("|")
print("|")
print("|______")
print("|______|")
elif guessCount == 1:
print("|----|")
print("| O")
print("|")
print("|")
print("|______")
print("|______|")
elif guessCount == 2:
print("|----|")
print("| O")
print("| |")
print("|")
print("|______")
print("|______|")
elif guessCount == 3:
print("|----|")
print("| O")
print("| /|")
print("|")
print("|______")
print("|______|")
elif guessCount == 4:
print("|----|")
print("| O")
print("| /|l")
print("|")
print("|______")
print("|______|")
elif guessCount == 5:
print("|----|")
print("| O")
print("| /|l")
print("| / ")
print("|______")
print("|______|")
elif guessCount == 6:
print("|----|")
print("| O")
print("| /|l")
print("| / \ ")
print("|______")
print("|______|")
def randWord():
fileArr = []
for line in open('SOWPODS.txt', 'r'): #this code is faster than the while alternative.
fileArr.append(line.strip().lower())
return random.choice(fileArr)
def gameLogic(word):
guessCount = 0
guessLog = []
guessWord = ["_" for elem in word]
print("------------------------------------------------------------------------")
print("Welcome to Hangman. Here is your word to guess: ", " ".join(guessWord))
while "".join(guessWord) != word and guessCount < 6: #loop breaks if user guesses word, or if guess count is reached.
print("----------------------------")
userGuess = input("Guess a letter: ")
if userGuess not in guessWord and len(userGuess) == 1 and userGuess not in guessLog: #checks to see if user already guessed.. if false see else below.
if userGuess not in word:
print("Uh oh. Wrong letter.")
guessCount += 1
hangMan(guessCount)
else:
hangMan(guessCount)
for i in range(0, len(word)):
if userGuess == word[i] and len(userGuess) == 1:
guessWord[i] = userGuess
guessLog.append(userGuess)
print("Heres the word: ", " ".join(guessWord))
print("Your guesses are: ", ",".join(guessLog))
elif len(userGuess) != 1:
print("Try a guess with one letter please.")
elif userGuess in guessLog:
print("Oops! You already guessed that, try a different letter!")
if guessCount == 6:
print("Ah. Too bad, this man got hanged.")
return "loss"
else:
print("You won!! Congrats")
return "win"
if __name__=="__main__":
winCount = 0
loseCount = 0
playAgain = "yes"
while playAgain == "yes":
word = randWord()
winOrLose = gameLogic(word)
print("The word was: ", word)
if winOrLose == "win":
winCount += 1
else:
loseCount += 1
playAgain = input("Play Again (yes/no)? ")
print("Thanks for playing. You won {} times and lost {} times.".format(winCount, loseCount))
|
def add(a):
anssign=""
num1=""
num2=""
num1sign="+"
num2sign="+"
sum=0
if a.startswith("-"):
num1sign="-"
a=a[1:]
d=a.split("-")
e=a.split("+")
if len(d)>1:
num2sign="-"
num1=d[0]
num2=d[1]
elif len(e)>1:
num1=e[0]
num2=e[1]
if num1sign=="-" and num2sign=="-":
anssign="-"
sum=anssign+addition(num1,num2)
elif num1sign=="+" and num2sign=="+":
sum=addition(num1,num2)
elif num1sign=="-" or num2sign=="-":
asize=len(num1)
bsize=len(num2)
if asize<bsize:
temp=num1
num1=num2
num2=temp
if num2sign=="-":
anssign="-"
elif asize==bsize:
for i in range(0,asize):
if(num2[i]>num1[i]):
temp=num1
num1=num2
num2=temp
if num2sign=="-":
anssign="-"
break
if asize==1:
if num2[0]>num1[0]:
temp=num1
num1=num2
num2=num1
if num2sign=="-":
anssign="-"
else:
if num1sign=="-":
anssign="-"
if asize>bsize:
if num1sign=="-":
anssign="-"
sum=anssign+diffrence(num1,num2)
return sum
def diffrence(a,b):
i=len(b)-1
j=len(a)-1
sum=""
borrow=0
while i>=0:
if a[j]>b[i]:
c=int(a[j])-int(b[i])-borrow
sum=str(c)+sum
borrow=0
elif a[j]<b[i]:
c=(10+int(a[j]))-int(b[i])-borrow
sum=str (c)+sum
borrow=1
elif a[j]==b[i]:
c=0-borrow
borrow=0
sum=str(c)+sum
i-=1
j-=1
while j>=0:
c = int(a[j]) -borrow
if(c!=0):
sum=str (c)+sum
j-=1
while sum.startswith("0"):
sum=sum[1:]
if sum=="":
sum="0"
return sum
def addition(a,b):
asize=len(a)
bsize=len(b)
sum=""
carry=0
if asize<bsize:
temp=a
a=b
b=temp
i=min(asize,bsize)-1
j=max(asize,bsize)-1
while i>=0:
c = int(a[j]) +int(b[i])+carry
carry = c//10
sum=str (c%10)+sum
i-=1
j-=1
while j>=0:
c = int(a[j]) +carry
carry = c//10
sum=str (c%10)+sum
j-=1
return sum
#print(addition("1235767","321"))
#print(diffrence("0","1"))
print(add("123+1256783")) |
age = 69
if age < 2:
print('You are kinder!')
elif age >= 2 and age < 4:
print('You are baby!')
elif age >= 4 and age < 13:
print('You are child!')
elif age >= 13 and age < 20:
print('You are teenager!')
elif age >= 20 and age < 65:
print('You are adult!')
else:
print("You are too old!") |
def country_city(country, city, population=''):
"""Получаем страну и город"""
if population:
formatted_name = f'"{city.title()}, {country.title()} - population {population}"'
else:
formatted_name = f'"{city.title()}, {country.title()}"'
return formatted_name |
import unittest
from survey import AnnonymousSurvey
class TestAnnonymousSurvey(unittest.TestCase):
"""Тесты для класса AnnonymousSurvey"""
def setUp(self):
"""
Создание опроса и наборов ответов для всех тестовых методов.
"""
question = "What language did you first learn to speak?"
self.my_survey = AnnonymousSurvey(question)
self.responses = ['English', 'Russian', 'Belarussian']
def test_store_single_response(self):
"""Проверяет, что один ответ сохранен правильно."""
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
"""Проверяет, что три ответа были сохранены правильно."""
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
if __name__ == '__main__':
unittest.main() |
cities = {
'Minsk': {
'country': 'Belarus',
'population': '2 million',
'fact': '1067',
},
'Moscow': {
'country': 'Russia',
'population': '12 million',
'fact': '1147',
},
'Warsaw': {
'country': 'Poland',
'population': '1.8 million',
'fact': '1300',
},
}
for city, city_info in cities.items():
print(f"{city} is located in {city_info['country']} \
and has population {city_info['population']} people. \
\n{city} was founded in {city_info['fact']} year.\n") |
for value in range(1, 6):
print(value)
numbers = list(range(6))
print(numbers)
even_numbers = list(range(2, 12, 2))
print(even_numbers) |
responces = {}
polling_continue = True
while polling_continue:
name = input("\nWhat's your name?\n")
responce = input("\nWhat country would you like to visit in vacation?\n")
responces[name] = responce
new_name = input("\nWould like to get new answer from another person? (yes/no)\n")
if new_name == 'no':
polling_continue = False
print("\n--- Poll Results ---")
for name, country in responces.items():
print(f"{name} is want to visit {country} in near future.") |
import unittest
from city_functions import country_city
# country_city('belarus', 'minsk')
class CountryCity(unittest.TestCase):
"""Тесты для 'city_functions.py'."""
def test_city_country(self):
"""Страна и город отображаются правильно?"""
formatted_name = country_city('chile', 'santiago')
self.assertEqual(formatted_name, '"Santiago, Chile"')
def test_city_country_population(self):
"""Страна, город, население отображаются правильно?"""
formatted_name = country_city('chile', 'santiago', 'population=50000')
self.assertEqual(formatted_name, '"Santiago, Chile - population population=50000"')
if __name__ == '__main__':
unittest.main()
|
menu = ('sushi', 'pasta', 'pizza', 'pancakes', 'burger')
for meal in menu:
print(meal)
print('*' * 10)
menu = ('cruton', 'hot dog', 'pizza', 'pancakes', 'burger')
for meal in menu:
print(meal) |
filename = 'guest.txt'
name = input('Enter your name:\n')
with open(filename, 'a') as file_object:
file_object.write(f"Your name is {name}.\n") |
tupleList = (1, 2, 3)
print(tupleList)
# Dictionary with tuples insite
day_temperatures = {'morning': (1.0, 2.0, 3.0), 'noon': (
3.0, 4.0, 5.0), 'evening': (6.0, 7.0, 8.0)}
print(day_temperatures)
|
mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3
# prints out 1,2,3
for x in mylist:
print(x)
numbers = [1, 2, 3]
strings = ["hello", "world"]
names = ["John", "Eric", "Jessica"]
# write your code here
second_name = "Eric"
# this code should write out the filled arrays and the second name in the names list (Eric).
print(numbers)
print(strings)
print("The second name on the names list is %s" % second_name)
print(list(range(1, 10)))
print(list(range(1, 10, 2)))
alist = [1, 2, 3]
print(alist[10])
|
import random
import time
def OneDie(trials):
c1=time.clock()
print("====================")
print("One die with 6 sides")
print("Number of trials = ", trials)
sides = 6
histogram = [0, 0, 0, 0, 0, 0]
print(histogram)
j = 0
r = 0
while j < trials :
r = int(random.random()*sides) # Faster
# r = random.randint(0,5) # Slower. Return random integer in range [a, b], including both end points.
histogram[r] = histogram[r] + 1
j = j + 1
print("s, N_s, N_s-N/6, N_s/N, N_s/N-1/6")
j = 0
while j < sides:
print(j+1, histogram[j], histogram[j]-trials/sides, histogram[j]/trials, histogram[j]/trials-1/6)
j = j + 1
c2=time.clock()
print("Elapsed time =", c2-c1)
def run():
OneDie(1)
OneDie(10)
OneDie(100)
OneDie(1000)
OneDie(10000)
OneDie(100000)
OneDie(1000000)
run()
|
# To calculate the square root
num = 9
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) |
import numpy as np
import matplotlib.pyplot as plt
def display_image(img):
""" Show an image with matplotlib:
Args:
Image as numpy array (H,W,3)
"""
plt.figure()
plt.imshow(img)
plt.title("Image")
plt.show()
def save_as_npy(path, img):
""" Save the image array as a .npy file:
Args:
Image as numpy array (H,W,3)
"""
np.save(path,img)
def load_npy(path):
""" Load and return the .npy file:
Args:
Path of the .npy file
Returns:
Image as numpy array (H,W,3)
"""
return np.load(path)
def mirror_horizontal(img):
""" Create and return a horizontally mirrored image:
Args:
Loaded image as numpy array (H,W,3)
Returns:
A horizontally mirrored numpy array (H,W,3).
"""
flt=np.fliplr(img)
return flt
def display_images(img1, img2):
""" display the normal and the mirrored image in one plot:
Args:
Two image numpy arrays
"""
fig=plt.figure()
ax1 = fig.add_subplot(121)
ax1.imshow(img1)
ax1.set_title("normal image")
ax1.axis("off")
ax2 = plt.subplot(122)
ax2.imshow(img2)
ax2.set_title("mirrored image")
ax2.axis("off")
plt.show()
|
f = open('MyData.txt','r')
# to open file for reading as r
#print(f.readline(), end='') # for reading
#print(f.readline())
f1 = open('abc','w') # for writing w and appending a for reading r ,
#f1.write('Laptop')
# copying one file to another
for data in f:
f1.write(data)
|
from random import randint
import random as rand
from pythonds.basic.stack import Stack
import numpy
import sys
import signal
def handler(signum, frame):
print 'Time\'s up!!'
exit(0)
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
def Xor(x):
sum=0
i=0
s=""
bin=Stack()
while x >= 1:
bin_num=x%2
x=int(x/2)
bin.push(str(bin_num))
while bin.isEmpty()==False:
s=s+str(bin.peek())
bin.pop()
while i<len(s):
if s[i]=="0":
sum=sum+(2**(len(s)-i-1))
i=i+1
return sum
print """
Question:
Given x , we need to find the numbers less than x such that (p xor x) > x where 1<=p<x
Constrict time as much as possible as the solution given here takes (t * log n) time , where t is the number of test cases.
Input Format:
Line 1 : No of test cases (t)
Next t lines are the values of x
Output Format:
Single line stating the count of numbers where than p xor x > x
"""
r=randint(1000,100000)
print r
for i in range(r):
x=randint(1000,100000)
print x
k=Xor(x)
sys.stdout.flush()
num=raw_input()
num=int(num)
if num!=k:
print 'Wrong answer,no flag for you!'
exit(0)
print 'Success, the flag is xiomara{link_lists_are_cool_btw}'
|
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
from hashlib import sha256
from hmac import HMAC
def encrypt_password(password, salt=None):
"""Hash password on the fly."""
if salt is None:
salt = os.urandom(8)
for i in range(10):
try:
password = HMAC(password, salt, sha256).hexdigest().encode('utf-8') # python3 的返回值是 unicode
except TypeError:
password = HMAC(password, salt, sha256).hexdigest()
return salt + password # 保存每个账号的 salt
def get_password():
try:
password = raw_input('Input password: ').decode(sys.stdin.encoding)
password = password.encode('utf-8')
except NameError:
password = input('Input password: ').encode('utf-8')
return password
if __name__ == '__main__':
print(encrypt_password(get_password()))
|
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
def get_filtered_words(file_name='filtered_words.txt'):
with open(file_name, 'r') as fp:
filtered_words = [word.strip() for word in fp]
return filtered_words
def get_user_input():
return raw_input('Input: ').decode(sys.stdin.encoding).encode('utf-8')
def prog_output(user_input, filtered_words):
for word in filtered_words:
user_input = user_input.replace(word, '*' * len(word.decode('utf-8'))) # decode('utf-8') 解决中文长度问题
print(user_input.decode('utf-8').encode(sys.stdout.encoding))
if __name__ == '__main__':
filtered_words = get_filtered_words()
prog_output(get_user_input(), filtered_words)
|
from battleships import *
from random_guessing import *
from search_guessing import *
from probabilistic_guessing import *
from statistics import mean, stdev
def simulate_battleships():
while True:
method = input("Select guessing method: random (r), search (s), probabilistic (p): ").lower()
if method == "r":
guess_function = random_guessing
break
elif method == "s":
guess_function = search_target_guessing
break
elif method == "p":
guess_function = probabilistic_guessing
break
else:
print("Invalid input, try again.")
while True:
num_of_sims = input("Enter number of simulations: ")
if num_of_sims.isdigit() and int(num_of_sims) > 0:
num_of_sims = int(num_of_sims)
break
else:
print("Invalid input, try again.")
while True:
csv_out = input("Output to csv? (y/n): ").lower()
if csv_out in ("y", "n"):
break
else:
print("Invalid input, try again.")
print("Starting simulation...")
guesses = []
for sim in range(num_of_sims):
guesses.append(guess_function(10, STD_SHIPS, False))
print("Complete!")
print("Mean: %d, StDev: %f, Min: %d, Max %d" % (mean(guesses), stdev(guesses), min(guesses), max(guesses)))
# Generate CSV file
if csv_out == "y":
csv_file = open("battleships_CSV.csv", "w")
for guess in guesses:
csv_file.write("%d\n" % guess)
csv_file.close()
print("Data saved as 'battleships_CSV.csv'")
if __name__ == '__main__':
simulate_battleships() |
import numpy as np
# numpy arange fumction similar to range available in the python
arr = np.arange(10)
# numpy reshape function
reshape_arr = np.reshape(arr, (2, 5))
print(repr(arr))
print("arr shape: {}".format(arr))
print(repr(reshape_arr))
print("reshape_arr : {}".format(reshape_arr.shape))
areshape = np.reshape(reshape_arr, (5, 2))
print(repr(areshape))
# Numpy Flatten Function
flatten = areshape.flatten()
print(repr(flatten))
# numpy transpose function row to columns and columns to rows
tran = np.transpose(reshape_arr)
print(repr(tran))
tran = np.transpose(reshape_arr, axes=[0, 1])
print("New Shape: {}".format(tran.shape))
linspaced_arr = np.linspace(1.9, 50.1, num=100)
print(repr(linspaced_arr))
print("Linespace array: {}".format(linspaced_arr.size))
line_reshape = np.reshape(linspaced_arr, (5, 4, 5))
|
from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Arial", 24, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score = 0 # initialize score to 0
# self.high_score = 0
with open("data.txt") as data:
self.high_score = int(data.read()) # read only give you string, so we need to convert string to integer
self.color("white")
self.hideturtle() # arrow will disappear
self.penup()
self.goto(0, 270) # move scoreboard to the top
self.update_scoreboard() # self.write(f"Score: {self.score}", False, align="center", font=("Arial", 24, "normal"))
def update_scoreboard(self): # this function is created because it's used frequently
self.clear()
self.write(f"Score: {self.score} high Score: {self.high_score}", False, align=ALIGNMENT, font=FONT)
def increase_score(self):
self.score = self.score + 1
# before incease score on scoreboard, we need to delete previous score, or the previous score and updated score will be overlapping.
# self.clear() # clear previous text that is written
self.update_scoreboard() # self.write(f"Score: {self.score}", False, align="center", font=("Arial", 24, "normal"))
# def game_over(self):
# self.goto(0,0) # instead of going to default top(from __init__ setting), "Game Over" is going to show in the center(0, 0)
# self.write("Game Over !!", align=ALIGNMENT, font=FONT)
def reset(self):
if self.score > self.high_score:
self.high_score = self.score
with open("data.txt", mode="w") as data: # open with write mode, default is read mode
data.write(f"{self.high_score}")
self.score = 0
self.update_scoreboard()
|
"""
You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to
the left, 1 position to the right in the array or stay in the same place (The pointer should not be
placed outside the array at any time).
Given two integers steps and arrLen, return the number of ways such that your pointer still at
index 0 after exactly steps steps.
Since the answer may be too large, return it modulo 10^9 + 7.
"""
class Solution:
def __init__(self):
self.mnem = {}
def numWays(self, steps: int, arrLen: int) -> int:
def dp(pos, steps):
if (pos, steps) in self.mnem:
return self.mnem[(pos, steps)]
if steps == 0:
return 1 if pos == 0 else 0
if pos < 0:
return 0
if pos >= arrLen:
return 0
result = dp(pos + 1, steps - 1) + dp(pos - 1, steps - 1) + dp(pos, steps - 1)
self.mnem[(pos, steps)] = result
return result
return dp(0, steps) % (10 ** 9 + 7)
assert Solution().numWays(3, 2) == 4
assert Solution().numWays(10, 5) == 2187
|
dogs = ['border collie', 'australian cattle dog','labrador retriever']
name = input('What is your favourite type of dog? ')
number = ''
while not number in ('0','1','2'):
number = input('pick a number between 0 and 2 ')
number = int(number)
dogs[number] = name
print(dogs) |
def main():
import os
print('List_Hard')
menu = ('{:>30}'.format('Shark Regatta'),
'1...add a boat to list',
'2...remove a boat from lit',
'3...print a list of boats by sign up order',
'4...print a list of boats sorted alphabetically',
'5...print a list of boats sorted alphabetivally and numbered',
'6...how many boats are in the regatta',
'9...exit',
'')
boat_list = []
choice = 0
while choice != 9:
os.system('cls')
for n in menu:
print(n)
go = True
while go:
try:
choice = int(input('What is your choice? '))
except:
pass
else:
if choice in range(1,7) or choice == 9:
go = False
print()
if choice == 1:
go_in = ''
while len(go_in) == 0:
go_in = input('What is the name of the boat? ').title()
try:
boat_list.append(go_in)
except:
print('Error')
else:
print(go_in,'has been added to the list.')
if choice == 2:
r = ''
while len(r) == 0:
r = input('What is the name of the boat? ').title()
try:
boat_list.remove(r)
except:
print(r,'not in the list')
else:
print(r,'has been remove from the list ')
if choice == 3:
print('List of Boats')
print()
for n in boat_list:
print(n)
if choice == 4:
sorted_boat_list = boat_list.copy()
sorted_boat_list.sort()
print('Sorted Boats')
print()
for n in sorted_boat_list:
print(n)
if choice == 5:
sorted_boat_list = boat_list.copy()
sorted_boat_list.sort()
print('Sorted and Numbered Boats')
print()
for n,k in enumerate(sorted_boat_list):
print('{:<30}'.format(k),n+1)
if choice == 6:
print(len(boat_list))
print()
input('Pree enter to fo back to menu.') |
num = []
for n in range(4):
inpu = int(input('What is thr No.'+str(n+1)+' number. '))
num.append(inpu)
num = sorted(num)
print(num) |
n1 = ''
n2 = ''
while not n1.isdigit() and not n2.isdigit():
n1 = input('What is your first natural number? ')
n2 = input('What is your second natural number? ')
n1 = int(n1)
n2 = int(n2)
print('The first number is',n1)
print('The second number is',n2)
if n2 > n1:
change = n2
n2 = n1
n1 = change
sum = n1+n2
print('The sum of',n1,'and',n2,'is',sum)
product = n1 * n2
print('The product of',n1,'and',n2,'is',product)
difference = n1 - n2
print('Subtacting',n1,'by',n2,'gives',difference)
quotient = n1/n2
print('Diciding',n1,'by',n2,'gives',quotient)
remainder = n1%n2
print('The remain of',n1,'divided by',n2,'is',remainder)
dividend = n1//n2
print('The number of times',n1,'goes evenly into',n2,'is',dividend) |
print('x','y')
for x in range(-10,11):
y = 5*x +3
print(x,y) |
n1 = int(input('What is your first natural number? '))
n2 = int(input('What is your second natural number? '))
print('The first number is',n1)
print('The second number is',n2)
sum = n1+n2
print('The sum of',n1,'and',n2,'is',sum)
product = n1 * n2
print('The product of',n1,'and',n2,'is',product)
difference = n1 - n2
if difference<0:
print('Subtacting',n2,'by',n1,'gives',-difference)
else:
print('Subtacting',n1,'by',n2,'gives',difference)
quotient = n1/n2
if quotient<1:
print('Diciding',n2,'by',n1,'gives',1/quotient)
else:
print('Diciding',n1,'by',n2,'gives',quotient)
if quotient<1:
remainder = n2%n1
print('The remain of',n2,'divided by',n1,'is',remainder)
else:
remainder = n1%n2
print('The remain of',n1,'divided by',n2,'is',remainder)
if quotient<1:
dividend = n2//n1
print('The number of times',n2,'goes evenly into',n1,'is',dividend)
else:
dividend = n1//n2
print('The number of times',n1,'goes evenly into',n2,'is',dividend) |
c = 3
while c>=1:
print(c)
c -= 1
for n in range(3,0,-1):
print(n) |
dog_name = input("What is youe dog's name? ")
dog_age = int(input("Whai is your dog's age? "))
human_age = dog_age * 7
print('Your dog',dog_name,'is', human_age,'years old0 in human years ') |
dogs = ['border collie', 'australian cattle dog','labrador retriever']
dogs.append('poodle')
dogs.append('dog A')
dogs.append('dog B')
for dog in dogs:
print(dog.title() + 's are cool.') |
def main():
import time
print('Getting Old Hard')
print()
go = True
while go:
try:
age = int(input('How old you you? '))
except:
pass
else:
if age >= 0:
go = False
gender = ''
while not (gender == 'f' or gender == 'm'):
gender = input('What is your gender(m/f)? ').lower()
print()
#------------------------------------------------------------------
if age in range(0,9):
name = 'child'
elif age in range(9,13):
name = 'tweeny'
elif age in range(13,20):
name = 'teenager'
elif age >=20:
name = 'old timer'
if gender == 'f':
print('You are a girl',name+'.')
elif gender == 'm':
print('You are a boy',name+'.')
print('You were born in the year %.d.'%(2018-age))
if age//2 == 0:
print('You age is an even number.')
else:
print('You age is an odd number.')
|
from typing import Tuple
def should_board_front(seat: Tuple[int, str]) -> bool:
return seat[0] < 13
def upgrade_passenger(name: str, current_seat: Tuple[int, str]) -> Tuple[int, str]:
if name == "Sander G. van Dijk":
return 1, "A"
else:
print("Nice try")
return current_seat
|
class EmptyCollection(Exception):
pass
class EmptyTree(Exception):
pass
class LinkedBinaryTree:
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
if (self.left is not None):
self.left.parent = self
self.right = right
if (self.right is not None):
self.right.parent = self
self.parent = None
def __init__(self, root=None):
self.root = root
self.size = self.subtree_count(self.root)
def __len__(self):
return self.size
def is_empty(self):
return (len(self) == 0)
def subtree_count(self, subtree_root):
if(subtree_root is None):
return 0
else:
left_count = self.subtree_count(subtree_root.left)
right_count = self.subtree_count(subtree_root.right)
return left_count + right_count + 1
def sum_tree(self):
return self.subtree_sum(self.root)
def subtree_sum(self, subtree_root):
if(subtree_root is None):
return 0
else:
left_sum = self.subtree_sum(subtree_root.left)
right_sum = self.subtree_sum(subtree_root.right)
return left_sum + right_sum + subtree_root.data
def height(self):
if (self.is_empty()):
raise EmptyCollection("Height is not defined for an empty tree")
return self.subtree_height(self.root)
def subtree_height(self, subtree_root):
if((subtree_root.left is None) and (subtree_root.right is None)):
return 0
elif(subtree_root.left is None):
return 1 + self.subtree_height(subtree_root.right)
elif(subtree_root.right is None):
return 1 + self.subtree_height(subtree_root.left)
else:
left_height = self.subtree_height(subtree_root.left)
right_height = self.subtree_height(subtree_root.right)
return 1 + max(left_height, right_height)
def iterative_inorder(self):
current=self.root
while current is not None:
if current.left is None:
yield current.data
current=current.right
else:
pre=current.left
while pre.right!=None and pre.right!=current:
pre=pre.right
if pre.right is None:
pre.right=current
current=current.left
else:
pre.right=None
yield current.data
current=current.right
# Question 2
def leaves_list(self):
answer=[]
node=self.root
if node is None:
return answer
def leaves(node):
if node.left is None and node.right is None:
answer.append(node.data)
if node.left is not None:
leaves(node.left)
if node.right is not None:
leaves(node.right)
leaves(node)
return answer
# Question 1
def min_and_max(bin_tree):
if bin_tree.root is None:
raise EmptyTree("tree is empty")
return subtree_min_and_max(bin_tree,bin_tree.root)
def subtree_min_and_max(bin_tree,subtree_root):
if subtree_root.left is None and subtree_root.right is None:
return (subtree_root.data,subtree_root.data)
e1=subtree_root.data
if subtree_root.left is None:
e2=subtree_min_and_max(bin_tree,subtree_root.right)
return (min(e1,e2[0]),max(e1,e2[1]))
elif subtree_root.right is None:
e3=subtree_min_and_max(bin_tree,subtree_root.left)
return (min(e1,e3[0]),max(e1,e3[1]))
else:
e2=subtree_min_and_max(bin_tree,subtree_root.right)
e3=subtree_min_and_max(bin_tree,subtree_root.left)
return (min(e1, e3[0],e2[0]),max(e1,e3[1],e2[1]))
#Question 3
def is_height_balanced(bin_tree):
return helper(bin_tree.root)[1]
def helper(root):
if root == None:
return (0,True)
else:
root_left=helper(root.left)
root_right=helper(root.right)
balanced=root_left[1] and root_right[1] and abs(root_left[0]-root_right[1])<=1
return (1+max(root_left[0],root_right[0]),balanced)
#Question 5
def create_expression_tree(prefix_exp_str):
prefix=prefix_exp_str.split()
L=['+','-','*','/']
def helper(prefix,index):
if prefix[index].isdigit():
return (LinkedBinaryTree.Node(int(prefix[index])),index)
elif prefix[index] in L:
node = LinkedBinaryTree.Node(prefix[index])
left=helper(prefix,index+1)
node.left=left[0]
right=helper(prefix,left[1]+1)
node.right=right[0]
return (node,right[1])
return LinkedBinaryTree(helper(prefix,0)[0])
def prefix_to_postfix(prefix_exp_str):
tree=create_expression_tree(prefix_exp_str)
L=[]
def helper(root):
if isinstance(root.data,int):
L.append(str(root.data))
else:
helper(root.left)
helper(root.right)
L.append(root.data)
helper(tree.root)
return ' '.join(L)
l_ch1 = LinkedBinaryTree.Node(5)
r_ch1 = LinkedBinaryTree.Node(1)
l_ch2 = LinkedBinaryTree.Node(9, l_ch1, r_ch1)
l_ch3 = LinkedBinaryTree.Node(2,l_ch2)
l_ch4 = LinkedBinaryTree.Node(8)
r_ch2 = LinkedBinaryTree.Node(4)
r_ch3 = LinkedBinaryTree.Node(7, l_ch4, r_ch2)
root = LinkedBinaryTree.Node(3, l_ch3, r_ch3)
tree = LinkedBinaryTree(root)
tree2=LinkedBinaryTree(l_ch2)
print(is_height_balanced(tree))
print(is_height_balanced(tree2))
print(min_and_max(tree))
l1=LinkedBinaryTree.Node(5)
l2=LinkedBinaryTree.Node(1)
l3=LinkedBinaryTree.Node(8,l1,l2)
l4=LinkedBinaryTree.Node(9)
l5=LinkedBinaryTree.Node(2,l4)
l6=LinkedBinaryTree.Node(4)
l7=LinkedBinaryTree.Node(7,l3,l6)
l8=LinkedBinaryTree.Node(3,l5,l7)
tree3=LinkedBinaryTree(l8)
print(is_height_balanced(tree3))
print(min_and_max(tree3))
l1=LinkedBinaryTree.Node(5)
l2=LinkedBinaryTree.Node(1)
l3=LinkedBinaryTree.Node(8)
l4=LinkedBinaryTree.Node(9,l1,l2)
l5=LinkedBinaryTree.Node(2,l4)
l6=LinkedBinaryTree.Node(4)
l7=LinkedBinaryTree.Node(7,l3,l6)
l8=LinkedBinaryTree.Node(3,l5,l7)
tree4=LinkedBinaryTree(l8)
print(is_height_balanced(tree4))
print(min_and_max(tree4))
for item in tree.iterative_inorder():
print(item, end=' ')
print('')
print(prefix_to_postfix('* + - 2 15 6 4'))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 20 19:41:18 2017
@author: Zhoukx.joseph
"""
def fibs(n):
i = 0
q = 1
count = 0
while count < n:
c = i+q
i = q
q = c
count+=1
yield i
for i in fibs(9):
print(i) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 23 09:21:51 2017
@author: Zhoukx.joseph
"""
class Empty(Exception):
pass
class ArrayStack:
def __init__(self):
self.data = []
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self) == 0
def push(self, val):
self.data.append(val)
def top(self):
if (self.is_empty()):
raise Empty("Stack is empty")
return self.data[-1]
def pop(self):
if (self.is_empty()):
raise Empty("Stack is empty")
return self.data.pop()
class Queue:
def __init__ (self):#two ArrayStack objects
self.s=ArrayStack()
self.p=ArrayStack()
def enqueue(self,elem):
self.s.push(elem)
def __len__(self):
return len(self.s)+len(self.p)
def dequeue(self):
if len(self)==0:
raise Empty("Queue is empty")
if self.p.is_empty():#only when p is empty, pop element from s to p.
while self.s.is_empty()==False:
self.p.push(self.s.pop())
return self.p.pop()#first in first out.
def first(self):
if len(self)==0:
raise Empty("Queue is empty")
if self.p.is_empty():
while self.s.is_empty()==False:
return self.s.top()
return self.p.top()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 19 20:47:04 2017
@author: Zhoukx.joseph
"""
class BinarySearchTreeMap:
class Item:
def __init__(self, key, value=None):
self.key = key
self.value = value
class Node:
def __init__(self, item):
self.item = item
self.parent = None
self.left = None
self.right = None
self.leftnum = 0
def num_children(self):
count = 0
if (self.left is not None):
count += 1
if (self.right is not None):
count += 1
return count
def disconnect(self):
self.item = None
self.parent = None
self.left = None
self.right = None
def __init__(self):
self.root = None
self.size = 0
def __len__(self):
return self.size
def is_empty(self):
return len(self) == 0
# raises exception if not found
def __getitem__(self, key):
node = self.subtree_find(self.root, key)
if (node is None):
raise KeyError(str(key) + " not found")
else:
return node.item.value
# returns None if not found
def subtree_find(self, subtree_root, key):
curr = subtree_root
while (curr is not None):
if (curr.item.key == key):
return curr
elif (curr.item.key > key):
curr = curr.left
else: # (curr.item.key < key)
curr = curr.right
return None
# updates value if key already exists
def __setitem__(self, key, value):
node = self.subtree_find(self.root, key)
if (node is None):
self.subtree_insert(key, value)
else:
node.item.value = value
# assumes key not in tree
def subtree_insert(self, key, value=None):
item = BinarySearchTreeMap.Item(key, value)
new_node = BinarySearchTreeMap.Node(item)
if (self.is_empty()):
self.root = new_node
self.size = 1
else:
parent = self.root
if(key < self.root.item.key):
curr = self.root.left
else:
curr = self.root.right
while (curr is not None):
parent = curr
if (key < curr.item.key):
curr = curr.left
else:
curr = curr.right
if (key < parent.item.key):
parent.left = new_node
else:
parent.right = new_node
new_node.parent = parent
self.size += 1
curr=new_node
while curr is not self.root:
if curr.parent.left is curr:
curr.parent.leftnum+=1
curr=curr.parent
#raises exception if key not in tree
def __delitem__(self, key):
if (self.subtree_find(self.root, key) is None):
raise KeyError(str(key) + " is not found")
else:
self.subtree_delete(self.root, key)
#assumes key is in tree + returns value assosiated
def subtree_delete(self, node, key):
node_to_delete = self.subtree_find(node, key)
value = node_to_delete.item.value
num_children = node_to_delete.num_children()
curr=node_to_delete
while curr is not self.root:
if curr.parent.left==curr:
curr.parent.leftnum-=1
curr=curr.parent
if (node_to_delete is self.root):
if (num_children == 0):
self.root = None
node_to_delete.disconnect()
self.size -= 1
elif (num_children == 1):
if (self.root.left is not None):
self.root = self.root.left
else:
self.root = self.root.right
self.root.parent = None
node_to_delete.disconnect()
self.size -= 1
else: #num_children == 2
max_of_left = self.subtree_max(node_to_delete.left)
node_to_delete.item = max_of_left.item
self.subtree_delete(node_to_delete.left, max_of_left.item.key)
else:
if (num_children == 0):
parent = node_to_delete.parent
if (node_to_delete is parent.left):
parent.left = None
else:
parent.right = None
node_to_delete.disconnect()
self.size -= 1
elif (num_children == 1):
parent = node_to_delete.parent
if(node_to_delete.left is not None):
child = node_to_delete.left
else:
child = node_to_delete.right
child.parent = parent
if (node_to_delete is parent.left):
parent.left = child
else:
parent.right = child
node_to_delete.disconnect()
self.size -= 1
else: #num_children == 2
max_of_left = self.subtree_max(node_to_delete.left)
node_to_delete.item = max_of_left.item
self.subtree_delete(node_to_delete.left, max_of_left.item.key)
return value
# assumes non empty subtree
def subtree_max(self, curr_root):
node = curr_root
while (node.right is not None):
node = node.right
return node
def inorder(self):
for node in self.subtree_inorder(self.root):
yield node
def preorder(self):
for node in self.subtree_preorder(self.root):
yield node
def subtree_preorder(self, curr_root):
if(curr_root is None):
pass
else:
yield curr_root
yield from self.subtree_preorder(curr_root.left)
yield from self.subtree_preorder(curr_root.right)
def subtree_inorder(self, curr_root):
if(curr_root is None):
pass
else:
yield from self.subtree_inorder(curr_root.left)
yield curr_root
yield from self.subtree_inorder(curr_root.right)
def __iter__(self):
for node in self.inorder():
yield (node.item.key, node.item.value)
def get_ith_smallest(self,i):
if i > self.size:
raise IndexError('List Index OutOfRange')
def helper(curr,i):
if curr.leftnum + 1==i:
return curr.item.key
elif i < curr.leftnum + 1:
return helper(curr.left,i)
elif i> curr.leftnum+1:
return helper(curr.right,i-curr.leftnum-1)
return helper(self.root,i)
def create_chain_bst(n):
tree=BinarySearchTreeMap()
for i in range(n):
tree.subtree_insert(i+1)
return tree
def create_complete_bst(n):
bst=BinarySearchTreeMap()
add_items(bst,1,n)
return bst
def add_items(bst,low,high):
if low <= high:
bst.subtree_insert((low+high)//2)
add_items(bst,low,(low+high)//2-1)
add_items(bst,(low+high)//2+1,high)
def find_min_abs_difference(bst):
L=[]
for i in bst.inorder():
L.append(i.item.key)
return min(abs(L[i+1]-L[i]) for i in range(len(L)-1))
def restore_bst(prefix_lst):
tree = BinarySearchTreeMap()
if len(prefix_lst)==0:
return tree
NodeList = [BinarySearchTreeMap.Node(BinarySearchTreeMap.Item(i)) for i in prefix_lst]
tree.root=NodeList[0]
maxi=0
for i in range(1,len(prefix_lst)):
if prefix_lst[i] < prefix_lst[i-1]:
NodeList[i].parent = NodeList[i-1]
NodeList[i-1].left=NodeList[i]
elif prefix_lst[i]>prefix_lst[maxi]:
NodeList[maxi].right=NodeList[i]
NodeList[i].parent=NodeList[maxi]
maxi=i
else:
p=i
while prefix_lst[i]>prefix_lst[p-1]:p-=1
NodeList[p].right=NodeList[i]
NodeList[i].parent=NodeList[p]
return tree
import math
def is_bst(bst):
maxi=math.inf
mini=-math.inf
def helper(bst,root,maxi,mini):
if root==None:
return True
if root.left.item.key>maxi or root.right.item.key<mini:
return False
else:
return (helper(bst,root.left,root.data,mini)
and helper(bst,root.right,maxi,root.data))
return helper(bst,bst.root,maxi,mini)
|
import sys
import pandas as pd
from sklearn.model_selection import train_test_split
def filter_df(df):
"""
Remove the unwanted samples from the dataframe
"""
df = df[(df.native_language == 'english') | (df.length_of_english_residence < 10)]
return df
def split_data(df, test_split=0.2):
"""
Creates a train/test split of the data
"""
return train_test_split(df['language_num'], df['native_language'],
test_size=test_split, train_size=(1.0 - test_split),
random_state=2840305)
|
# Helpful functions for interacting with the Twitter API using Python
def tweet_to_string(tweet):
"""
Takes Tweet text in JSON format (dictionary) and converts it to a useful string output.
Parameters
---------
tweet: dictionary
Tweet in JSON format as returned by requests.get(...).json()
Returns
-------
structured string output
Useful information extracted from the Tweet text
"""
s = """
Text: {text}
Hashtags: {hashtags}
Name: {name}
Username: {screenname}
User Description: {description}
Social Status: {friends} friends, {followers} followers, {favorites} favorites
Location: {location}
Geocode: {geo}
Date: {date}
""".format(text = tweet['text'],
hashtags = tweet['entities']['hashtags'],
name = tweet['user']['name'],
screenname = tweet['user']['screen_name'],
description = tweet['user']['description'],
friends = tweet['user']['friends_count'],
followers = tweet['user']['followers_count'],
favorites = tweet['user']['favourites_count'],
location = tweet['user']['location'],
geo = tweet['geo'],
date = tweet['created_at'])
return s
def tweets_to_df(tweets):
"""
Takes list of Tweets in JSON format (dictionaries) and converts it to a Pandas DataFrame.
Parameters
---------
tweets: list of dictionaries
Tweets in JSON format as returned by requests.get(...).json()
Returns
-------
DataFrame
Useful information extracted from each Tweet and compiled in a Pandas DataFrame
"""
import numpy as np
import pandas as pd
df = pd.DataFrame()
df['id'] = [tweet['id'] for tweet in tweets]
df['user_name'] = [tweet['user']['name'] for tweet in tweets]
df['user_screenname'] = [tweet['user']['screen_name'] for tweet in tweets]
df['user_description'] = [tweet['user']['description'] for tweet in tweets]
df['user_friends'] = [tweet['user']['friends_count'] for tweet in tweets]
df['user_followers'] = [tweet['user']['followers_count'] for tweet in tweets]
df['user_favorites'] = [tweet['user']['favourites_count'] for tweet in tweets]
df['retweets'] = [tweet['retweet_count'] for tweet in tweets]
df['date'] = [tweet['created_at'] for tweet in tweets]
df['location'] = [tweet['user']['location'] if tweet['user']['location'] != '' \
else np.nan for tweet in tweets]
df['geocode'] = [tweet['geo'] for tweet in tweets]
df['hashtags'] = [[inner_dict['text'] for inner_dict in tweet['entities']['hashtags']] \
if tweet['entities']['hashtags'] != [] else np.nan for tweet in tweets]
df['tweet'] = [tweet['text'].strip() for tweet in tweets]
return df
def get_tweets_premium(api_connection, num_pages, product, label, query, fromDate, toDate, maxResults):
"""
Queries tweets from the Twitter Premium APIs ('30-Day' and 'Full Archive') without exceeding the
Sandbox rate limits. Pages through the search results to avoid repeated queries and returns tweets
as a list of dictionaries (JSON format). Fails on error with status code output.
Parameters
---------
api_connection: TwitterAPI object
authenticated TwitterAPI connection for REST API or Streaming API access
num_pages: int
the number of search result pages to return (i.e. number of requests), subject to request limits
total number of tweets returned will be approximately maxResults * num_pages
product: string: '30day' or 'fullarchive'
the Premium API to be accessed
'30day' accesses tweets from the prior 30 days; 'fullarchive' accesses tweets from all years
request limits apply: see https://developer.twitter.com/en/docs/tweets/search/overview/premium
label: string
the label of the 'dev environment' setup for Premium API access
query: string
the search query
see https://developer.twitter.com/en/docs/tweets/search/api-reference/premium-search for details
fromDate: string
oldest UTC timestamp to consider in search query (subject to API limitations)
applies minute-level granularity (e.g. '201201010000')
toDate: string
most recent UTC timestamp to consider in search query (subject to API limitations)
applies minute-level granularity
maxResults: int
maximum number of tweets returned per request/page
total number of tweets returned will be approximately maxResults * num_pages
request limits apply: Sandbox access grants maxResults of at most 100 tweets
Returns
-------
list of dictionaries (or error status code)
Queried tweets in JSON format
"""
import time
r = api_connection.request('tweets/search/{}/:{}'.format(product, label),
{'query': query,
'fromDate': fromDate,
'toDate': toDate,
'maxResults': maxResults})
if r.status_code != 200:
print('status code: ' + str(r.status_code))
# see https://developer.twitter.com/en/docs/basics/response-codes.html for details
return
json = r.json()
tweets = json['results']
next_key = json['next'] # next key provided only if additional pages available
page = 2
while page <= num_pages:
r = api_connection.request('tweets/search/{}/:{}'.format(product, label),
{'query': query,
'fromDate': fromDate,
'toDate': toDate,
'maxResults': maxResults,
'next': next_key}) # requests tweets from the next page
if r.status_code != 200:
print('status code: ' + str(r.status_code))
break
json = r.json()
tweets += json['results'] # combine with previous results
if 'next' not in json: # stop if no next_key provided (no further pages)
break
time.sleep(3) # ensures compatibility with Sandbox rate limits
next_key = json['next']
page += 1
return tweets
def tweets_db_to_df(collection, filters = {}):
"""
Pull tweets from MongoDB database and compile them in Pandas DataFrame.
Parameters
---------
collection: pymongo.collection.Collection
MongoDB collection containing tweets
filters: dictionary, default: {}
filters applied for tweet querying
Returns
-------
DataFrame
extracts ID, full tweet text, year, and location for each tweet and returns as row of DataFrame
"""
import numpy as np
import pandas as pd
cursor = collection.find(filters, {'_id': 0}) # query the database
new_list = []
for tweet in cursor:
new_dict = {}
new_dict['ID'] = tweet['id']
try:
# get full tweet text if truncated
new_dict['text'] = tweet['retweeted_status']['extended_tweet']['full_text']
except:
new_dict['text'] = tweet['text']
new_dict['year'] = tweet['year']
new_dict['location'] = tweet['user']['location']
new_list.append(new_dict)
df = pd.DataFrame(new_list)
df['location'] = df['location'].replace({None: np.nan}) # handle missing locations
return df
|
import math
height = 10
def ReturnAngles(X, Y):
hypot = math.sqrt((X*X) + (Y*Y))
if X == 0:
degX = 0
else:
degX = math.degrees(math.atan(X / Y))
if Y <= 0:
degY = 0
else:
degY = math.degrees(math.atan(hypot / height))
return degX, degY
def CalcSteps(X, Y, curDegX, curDegY):
newDegX, newDegY = ReturnAngles(X, Y)
difX = newDegX - curDegX
difY = newDegY - curDegY
stepsX = (difX * 2038) / 360
stepsY = (difY * 2038) / 360
return stepsX, stepsY
print(ReturnAngles(10, 15))
print(ReturnAngles(-10, 10))
print(ReturnAngles(-5, 5))
print(ReturnAngles(0,0))
print(ReturnAngles(0, 10))
curX = 45
curY = 45
X = 5
Y = 5
print("Start")
for i in range(5):
curX, curY = ReturnAngles(X, Y)
print(curX, curY)
Y += 1
X += 1
print(CalcSteps(X, Y, curX, curY))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.