text
stringlengths 37
1.41M
|
---|
# ITP Week 4 Day 2 Exercise
#Today we will pull information from the Pokemon api, put it into a dictionary, and then put that info into a new Excel file. We will write the pseudocode as a group in class. Be sure to follow the pseudocode, break your problems down into smaller pieces, and consult the documentation whenever you get stuck: https://pokeapi.co/api/v2/pokemon
#PSEUDO-CODE:
#GET NAME AND ABILITY FROM API
#PUT INFO IN DICTIONARY
#ADD THE DICTIONARY TO A NEW EXCEL WORKBOOK
#imports:
#json
#openpyxl
import requests
import json
import openpyxl
import pandas as pd
#Input
#json file from pokemon api
#workbook
#Assign response to variable
response = requests.get('https://pokeapi.co/api/v2/pokemon')
# print(clean_data)
#Create workbook
#get workbook from openpy
#load workbook
#assign workbook to variable
#Create Worksheet
#assign sheet to variable
wb = openpyxl.load_workbook('week_four/day_2/output.xlsx')
sheet = wb['Sheet1']
sheet2 = wb['Sheet2']
#Create a dictionary, assign to variable
name_dict = {}
ab_dict = {}
#FUNCTION BODY
#Convert response to json file
#clean data(response)
#json.loads(response.text)
clean_data = json.loads(response.text)
result = clean_data["results"]
name_counter = 0
counter1 = 2
counter2 = 2
# ab_counter = 0
# url_counter = 0
#Iterate over response
#variable key = pokemon.name
#variable value = pokemon.abilites
#append {key/value} pair to dictionary
for char in result:
# add individul names to xl
sheet['A' + str(counter1)] = char['name']
# add individual names to dic
name_dict[str(name_counter) + " Name"] = char['name']
# begin cleaning data for ability url
url_result = clean_data['results']
pokemon_url = url_result[name_counter]['url']
response1 = requests.get(pokemon_url)
clean_url = json.loads(response1.text)
ab_result = clean_url['abilities']
# break the scaffolding down far enough that it reduces errors
single_ab = ab_result[0]["ability"]
# add individual ability to xl
sheet['B' + str(counter1)] = ab_dict[str(name_counter) + " Ability"] = single_ab["name"]
# add individual ability to dict
ab_dict[str(name_counter) + " Ability"] = single_ab["name"]
counter1 += 1
counter2 += 2
name_counter += 1
#Iterate over dictionary
#for each item in dictionary
#assign dictionary values to rows & cols
#Write Name to Cell
#Write Abilities to Cell
# df = pd.DataFrame(data=name_dict, index=[1])
# df = (df.T)
# print(df)
sheet['A1'] = 'Name'
sheet['B1'] = 'Ability'
#Output
#Workbook
wb.save('week_four/day_2/output.xlsx')
# pokemon = {
# bulbasour : {
# "name": "pokemon_name",
# "abilities": ["ability1", "ability2"]
# },
# pikachu : {
# "name": "pokemon_name",
# "abilities": ["ability1", "ability2"]
# }
# }
|
#Write your code below this line 👇
# [Interactive Coding Exercise] Printing
print("Day 1 - Python Print Function")
print("The function is declared like this:")
print("print('what to print')")
# String Manipulation and Code Intelligence
print("Hello world!\nHello Aisha\nHello Princess")
# String concatenation
print("Hello" + " " + "Aisha")
#Fix the code below 👇
# Debugging
print("Day 1 - String Manipulation")
print("String Concatenation is done with the '+' sign.")
print('e.g. print("Hello " + "world")')
print("New lines can be created with a backslash and n.")
# The Python Input function
print("Hello " + input("What is your name?"))
# Code Exercise - Input Function https://pythontutor.com/
print(len(input("What is your name? ")))
# Python Variables
name = input("What is your name? ")
length = len(name)
print(length)
|
#!/usr/bin/env python3
from random import sample, randint
# return list of common elements between two random lists of up to 50 numbers between 1 and 50
print([ num for num in sample(range(50),randint(1,50)) if num in sample(range(50),randint(1,50)) ])
|
'''
Util functions
'''
from math import sqrt
def distance(p1, p2):
'''
Distance between the point p1 and p2
Points are in the form (x,y)
'''
return sqrt(((p2[0] - p1[0]) ** 2) + ((p2[1] - p1[1]) ** 2))
|
"""
Controls:
see README
"""
from pynput import keyboard
import datetime
class Keyboard_Controller:
"""
Class for enabling keyboard input for the drone
Attributes
----------
drone : drone.Drone
The drone to control
keydown : bool
True if a key is pressed down, False if no keys are pressed
speed : float
Speed of the drone operations
"""
def __init__(self, drone, player, detector=None, testmode=None, recordmode=False):
"""
Initialization function
Parameters
----------
drone : drone.Drone
Drone object which should already have been initialized
"""
assert drone is not None
self.drone = drone
self.player = player
self.detector = detector
self.keydown = False
self.speed = 50.0
self.testmode = testmode
self.recordmode = recordmode
def on_press(self, keyname):
"""
Handler for keyboard listener. Called when a button is pressed down
Parameters
----------
keyname : pynput.keyboard.Key
name of the key pressed returned by the Listener
"""
if self.keydown: # If a key is already pressed down, return
return
try:
self.keydown = True
keyname = str(keyname).strip("u'") # strip these chars to isolate the button pressed
print('+' + keyname)
if keyname == 'Key.esc':
self.drone.quit()
return
elif keyname == 'o':
if self.detector != None:
self.detector.toggle()
return
elif keyname == 'l':
self.drone.toggle_logging()
return
elif keyname == 'p' or keyname == '1':
self.drone.reset_position()
return
elif keyname == 'h':
self.drone.return_home()
self.drone.set_logging(False)
return
elif keyname == '-':
self.player.toggle_hud()
elif keyname == 'Key.home' and self.testmode == 'avoid':
self.detector.write_to_log("OK\n")
self.drone.set_logging(False)
if self.recordmode:
self.drone.toggle_recording(False)
elif keyname == 'Key.end' and self.testmode == 'avoid':
self.detector.write_to_log("FAIL\n")
self.drone.set_logging(False)
if self.recordmode:
self.drone.toggle_recording(False)
elif keyname == '2':
self.drone.wp_avoid.disable()
self.drone.wp_controller.toggle_enabled()
return
elif keyname == '3':
if self.testmode == 'avoid':
path = './flight_logs/tello-%s.csv' % (datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S'))
self.detector.write_to_log(path + ",")
self.drone.set_logging(True, path)
if self.recordmode:
self.drone.toggle_recording(True)
if self.detector != None:
self.drone.reset_waypoint()
self.detector.enable()
self.detector.avoider.enable()
self.drone.wp_controller.enable()
return
elif keyname == 'm':
if self.detector is not None:
self.detector.add_ratio(0.025)
elif keyname == 'n':
if self.detector is not None:
self.detector.add_ratio(-0.025)
elif keyname == 'r':
self.drone.toggle_recording(not self.drone.record)
return
elif keyname in self.controls:
key_handler = self.controls[keyname]
key_handler(self.speed)
except AttributeError:
print('special key {0} pressed'.format(keyname))
def on_release(self, keyname):
"""
Handler for keyboard listener. Called when a button is released.
Stops the operation activated by the key by setting the speed to 0
Parameters
----------
keyname : pynput.keyboard.Key
name of the key pressed returned by the Listener
"""
self.keydown = False
keyname = str(keyname).strip("u'") # strip these chars to isolate the button pressed
print('-' + keyname)
if keyname in self.controls:
print("Found key in controls")
key_handler = self.controls[keyname]
key_handler(0)
def init_controls(self):
"""
Define keys and add listener
"""
self.controls = {
'w': lambda speed: self.drone.move(speed, "forward"),
's': lambda speed: self.drone.move(speed, "backward"),
'a': lambda speed: self.drone.move(speed, "left"),
'd': lambda speed: self.drone.move(speed, "right"),
'Key.up': lambda speed: self.drone.move(speed, "up"),
'Key.down': lambda speed: self.drone.move(speed, "down"),
'q': lambda speed: self.drone.move(speed, "counter_clockwise"),
'e': lambda speed: self.drone.move(speed, "clockwise"),
'Key.tab': lambda speed: self.drone.takeoff(),
'Key.backspace': lambda speed: self.drone.land(),
}
self.key_listener = keyboard.Listener(on_press=self.on_press,
on_release=self.on_release)
self.key_listener.start()
print("ENABLED KEYBOARD CONTROL")
|
import numpy
def cartesian_to_polar(u, v):
"""
Transforms U,V into r,theta, with theta being relative to north (instead of east, a.k.a. the x-axis).
Mainly for wind U,V to wind speed,direction transformations.
"""
c = u + v*1j
r = numpy.abs(c)
theta = numpy.angle(c, deg=True)
# Convert angle relative to the x-axis to a north-relative angle
theta -= 90
theta = -theta % 360
return r, theta
|
digits=[]
while True:
try:
digits_input = input('Please enter comma separated digits: ')
input_split_by_comma = digits_input.split(",")
for digit in input_split_by_comma:
digits.append(int(digit))
break
except ValueError:
print("There is something wrong with the list you entered!")
continue
sum_of_digits = sum(digits)
max_of_digits = max(digits)
min_of_digits = min(digits)
digits_2_to_4 = digits[1:4]
digits_count = len(digits)
values_greater_than_10 = [d for d in digits if d > 10]
ascending_digits = sorted(digits)
descending_digits = sorted(digits, reverse=True)
reversed_digits = list(reversed(digits))
print('Sum of digits: {}'.format(sum_of_digits))
print('Largest digit: {}'.format(max_of_digits))
print('Smallest digit: {}'.format(min_of_digits))
print('2nd to 4th digits: {}'.format(digits_2_to_4))
print('Digit count: {}'.format(digits_count))
print('Digits > 10: {}'.format(values_greater_than_10))
print('Ascending: {}'.format(ascending_digits))
print('Descending: {}'.format(descending_digits))
print('Reversed: {}'.format(reversed_digits))
|
def list_function(number, lst):
average = sum(lst) / len(lst)
min_value = min(lst)
max_value = max(lst)
less_count = len([i for i in lst if i < number])
more_count = len([i for i in lst if i > number])
return average, min_value, max_value, less_count, more_count
# testing
print(list_function(5, [4,8,2,10,3,6]))
|
import string
# se define la funcion check_char
def check_char(userin):
# se define la lista de caracteres
amay = string.ascii_uppercase
azmay = list(amay)
amin = string.ascii_lowercase
azmin = list(amin)
aztotal = azmay+azmin
# los errores se llamaran utilizando asserts en el codigo
# el primer assert corresponde al error del punto d
# se comprueba que se trate de caracteres del alfabeto unicamente
E3 = "Error 3: La entrada no corresponde a un caracter o string"
assert userin.isalpha(), E3
# el segundo assert corresponde al error del punto c
# se comprueba si al menos un caracter esta fuera del rango a-Z
# si un caracter esta fuera del rango, la variable rango toma el valor de 0
rango = 1
for k in userin:
if k not in aztotal:
rango = 0
E2 = "Error 2: La entrada presenta caracteres fuera del rango A-Z"
assert rango == 1, E2
# el tercer y ultimo assert corresponde al error del punto b
# se comprueba si la longitud del string es igual a 1
assert len(userin) == 1, "Error 1: La entrada contiene más de un caracter"
# si se pasan todas estas pruebas, la funcion retorna el valor de 0
return 0
# se define la función caps_switch
def caps_switch(userin):
# se llama la función check_char para comprobar entrada válida
if check_char(userin) == 0:
# se cambia de mayuscula a minuscula o vice versa
userin2 = userin.swapcase()
return userin2
userin = input("Entrada: ")
print(caps_switch(userin))
|
print(bool(1))
print(bool(0))
print(bool(0.01))
print(bool((1,2)))
print(bool((0,0)))
print(bool('string'))
print(bool('0'))
print(bool(''))
print(bool([0,0]))
print(bool({0}))
print(bool({}))
x = True
y = False
print(int(x))
print(int(y))
print(int(x and y))
print(int(x or y))
print(int(x + y))
print(int(x - y))
print(int(x * y))
x = eval(input())
y = eval(input())
print(int(x))
print(int(y))
print(int(x and y))
print(int(x or y))
print(int(x + y))
print(int(x - y))
print(int(x * y))
|
import random
ans = random.randrange(-100,100)
i = 1
while(True):
str1 = "第" + str(i) + "次猜測的數值: "
g = eval(input(str1))
if(g > ans):
print('答錯,數字太大')
elif(g < ans):
print('答錯,數字太小')
else:
print('恭喜猜對了!共猜了', i,'次。')
break;
i+=1
|
n = eval(input('計算A!:'))
sum = 1
for i in range(n):
sum *= i+1
print( n, '! = ', sum)
|
def main():
#take an input
toParse = sequence()
print("Please type in your note sequence with notes separated by spaces:")
inputbuffer = input()
toParse.setNotes(inputbuffer.split(" "))
if not toParse.checkvalid():
print("your sequence is invalid!")
return 1
print("the sequence is in " + toParse.parsekey())
class sequence:
#todo
def __init__(self):
self.notes = []
self.accidentalnum = 0
self.accidentals = []
self.majsharpkeysignature = ["F#", "C#", "G#", "D#", "A#", "E#", "B#"]
self.majflatkeysignature = ["Bb", "Eb", "Ab", "Db", "Gb", "Cb", "Fb"]
self.majkey = ["Cb", "Gb", "Db", "Ab", "Eb", "Bb", "F", "C", "G", "D", "A", "E", "B", "F#", "C#"]
self.key = ""
def parsekey(self):
#todo
self.accidentalnum = self.countingaccidentals()
if self.accidentalnum == 0:
self.key = "C Major"
return self.key
foundsharpmajor = True
foundflatmajor = True
for i in range(self.accidentalnum):
if not self.majsharpkeysignature[i] in self.accidentals:
foundsharpmajor = False
if not self.majflatkeysignature[i] in self.accidentals:
foundflatmajor = False
if foundflatmajor:
self.key = self.majkey[7 - self.accidentalnum] + " Major"
elif foundsharpmajor:
self.key = self.majkey[7 + self.accidentalnum] + " Major"
else:
self.key = "not yet able to parse the chord..."
return self.key
def setNotes(self, listofnotes): #set the notes
self.notes = listofnotes #in the sequence
for i in range(len(self.notes)):
self.notes[i] = self.notes[i].title()
def checkvalid(self): #check if the
validity = True #notes are valid
for note in self.notes:
namelength = len(note)
if namelength >= 4 or namelength <=0:
validity = False
else:
if note[0] >= "A" and note[0] <= "Z":
if namelength == 1:
continue
elif namelength == 2:
if note[1] != "#" and note[1] != "b":
validity = False
else:
continue
elif namelength == 3:
if (note[1] == "#" or note[1] == "b") and note[1] == note[2]:
continue
else:
validity = False
return validity
#return the number of acccidentals
def countingaccidentals(self):
counter = 0
for note in self.notes:
if len(note) >=2:
if not note in self.accidentals:
self.accidentals.append(note)
counter += 1
else:
continue
else:
continue
return counter
if __name__ == '__main__':
main()
|
#! /usr/bin/env python
# latlon_3.py - for use in Chapter 10 PCfB
# Read in each line of the example file, split it into
# separate components, and write certain output to a separate file
# Set the input file name
# (The program must be run from within the directory
# that contains this data file)
InFileName = 'Marrus_claudanielis.txt'
# Open the input file for reading
InFile = open(InFileName, 'r')
# Initialize the counter used to keep track of line numbers
LineNumber = 0
# Open the output file for writing
# Do this *before* the loop, not inside it
OutFileName=InFileName + ".kml"
OutFile=open(OutFileName,'w') # You can append instead with 'a'
# Loop through each line in the file
for Line in InFile:
# Skip the header, line # 0
if LineNumber > 0:
# Remove the line ending characters
Line=Line.strip('\n')
# Separate the line into a list of its tab-delimited components
ElementList=Line.split('\t')
# Use the % operator to generate a string
# We can use this for output both to the screen and to a file
OutputString = "Depth: %s\tLat: %s\t Lon:%s" % \
(ElementList[4], ElementList[2], ElementList[3])
# Can still print to the screen then write to a file
print OutputString
# Unlike print statements, .write needs a linefeed
OutFile.write(OutputString+"\n")
# Index the counter used to keep track of line numbers
LineNumber = LineNumber + 1
# After the loop is completed, close the files
InFile.close()
OutFile.close()
|
from typing import List, Union
class Stack:
"""
Stack Implementation based of python list (array)
values are kept in as string to suite the implementation needs
methods:
pop:
pops out the last element of the stack and returns it
push:
pushes an element to the top of the stack
to_base_string:
Helper function to convert the stack to a string
representing the results after computation of bases
"""
def __init__(self, content: List = None) -> None:
self._stack = content or []
def pop(self) -> Union[str, int]:
"""
pop: pops out the last element of the stack and returns it
"""
return self._stack.pop()
def push(self, value: Union[str, int]) -> bool:
"""
push: pushes an element to the top of the stack
"""
self._stack.append(str(value))
return True
def to_base_string(self):
"""
to_base_string: Helper function to convert the stack to a string
representing the results after computation of bases
"""
stack = self._stack[::-1]
return ''.join(stack)
|
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class Queue(object):
def __init__(self, value):
self.first = Node(value)
self.last = self.first
self.length = 1
def enqueue(self, value):
self.last.next = Node(value)
self.last = self.last.next
self.length += 1
def peek(self):
return self.first.value
def dequeue(self):
self.first = self.first.next
self.length -= 1
def __str__(self):
out = ''
if self.length < 1:
out = 'This list has no values.'
else:
i = 0
first_copy = self.first
while first_copy is not None:
if i == 0:
out = 'first: ' + str(first_copy.value)
elif i == self.length - 1:
out += '=> last: ' + str(first_copy.value)
else:
out += '=> ' + str(first_copy.value)
first_copy = first_copy.next
i += 1
return out
|
#PROGRAM TO FIND POWER OF ANY NUMBER IN FORM OF X^Y WHERE X AND Y ARE USER INPUTS.
x=int(input("ENTER VALUE FOR X "))
y=int(input("ENTER VALUE FOR Y"))
z=x**y
print("THE VALUE OF X^Y:",z)
|
# This program print a table discount for 5 prices
for i in range(5):
original = 5 * i + 4.95
discounted = original * 0.6
total = original - discounted
print("Original price: ${} \t Discounted: ${} \t Total: ${}".format(round(original, 2),
round(discounted, 2),
round(total, 2)))
|
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
#Dictionary above was copied from the learning platform per the assignment instructions
# Expected Output
# [("Speros", "(555) 555-5555"), ("Michael", "(999) 999-9999"), ("Jay", "(777) 777-7777")]
def tuplfy(tiona): #setting the function name
print tiona.items() #called the items() function that outputs the proper list of tuples
#tuplfy(my_dict) #called the defined function
def tuplfy2(tiona): #building the built-in function
tuplist = [] #initalizing the list of tuples
for i in range (0, len(tiona)): #looping through the dictionary
tuplist += [(tiona.keys()[i],tiona.values()[i])] #adding key, value pairs to the list as tuples
print tuplist #printing the built list
tuplfy2(my_dict) #calling the defined function
|
# variables (number, strings, booleans(i.e. True/False))
# if/else = control flow or basic if-else logic.
# functions, are reusable templates of code. Also somtimes called subroutines.
# for/while loops are loops/iterations of pieces of code.
# classes encapsolate variables (data) and functions
# variables in a class are called class members, or attributes
# functions in a class are called class methods
# variables
a = 1 # this is number assigned to a variable
b = 'string' #this is a string assigned to a variable
c = True # this is a boolean assigned to a variable
d = b # this is a variable assigned to another variable
listOfNumbers = [1,2,3,4,5] #this is a list of numbers assigned to a variable
# loops
# this is a 'for' loop
mylist = [1,2,3,4,5]
for column in mylist:
print(mylist)
# this is a 'while' loop
stopValue = 0
while (stopValue < 10):
print(stopValue)
stopValue = stopValue + 1
#functions & if/else statements
# function defintions
def add(a, p):
c = a + p
return c
def sub(a, b):
c = a - b
return c
#using the function definitions
b = add(1,2)
e = sub(8,5)
f = add(b,e)
g = sub(5,f)
# function definitions with if/else
def X(a):
t = a +1
b = t/3
#control flow
if b>5:
return True
if b<5:
return False
else:
return 'a and b are equal'
y = X(3)
print(y)
# recursive function
def fib(a,b):
print(a,b)
if(b > 2000):
return b
return fib(b, a+b)
print(fib(0, 1))
#classes
# class definitions
class Cat:
# members/attributes
fur = True
tail = True
legs = 4
ears = 'pointy'
#methods
def eats(self, meat):
return 'the cat ate ' + meat
def meow(self):
return 'meow!'
def sleep(self):
return 'zzzz'
def lick(self):
return 'slurp'
class MeatFreezer:
steak = 'steak'
ham = 'ham'
chicken = 'chik'
tuna = 'tuna'
def getSteak(self, a):
return self.steak + ' ' + a
def getChicken(self):
return self.chicken
def getHam(self):
return self.ham
def giveTuna(self):
return self.tuna
class Seasoning:
pepper = 'pepper'
salt = 'salt'
garlic = 'garlic'
def getPepper(self):
return self.pepper
def getSalt(self):
return self.salt
def getGarlic(self):
return self.garlic
# using classes
# this creates an object by instantiating a class
ronsCat = Cat()
kristensCat = Cat()
meatFreezer = MeatFreezer()
seasoning = Seasoning()
print(ronsCat.eats(meatFreezer.getSteak(seasoning.getSalt())))
|
## define statements
# variables
# data type (numbers, strings, boolean)
a = 10.876543
b = 10
c = 5
d = 3
print('HellowWorld')
## if else statments
# == equal to
# != not equal to
#if a == b:
# print("a is equal to b")
#elif c > a:
# print('a is equal to c')
#if a == d:
# print("a is equal to d")
#else:
# print('a is not equal to anything!')
## loop section
#for loop
#mylist = [9,8,3,4,5,6,7,8,9,10]
#for i in mylist:
# print(i)
#while loop
#x = x + 1
#x = x + 1
#print(x)
#x = 0
#while(x < 10):
# print(x)
# x = x + 1
|
"""
HeadHunter DEVSchool
Задача : Точки
Автор решения : Чиркин М.В.
Дата : 01.10.2015
"""
import math
class Point:
"""
x - координата точки по оси OX
y - координата точки по оси OY
radius - радиус точки (расстояние до ближайшей точки)
neighbors - список соседей на расстоянии не более 2ух радиусов точки
"""
def __init__(self, x, y,
radius=math.inf, neighbors=None):
self.x = x
self.y = y
self.radius = radius
if neighbors is None:
self.neighbors = list()
def distance_to_point(self, point):
"""
Нахождение Евклидового расстояния от точки до точки
"""
return math.sqrt((point.x - self.x)**2 + (point.y - self.y)**2)
def get_coordinate(self, coordinate):
"""
Получение заданной координаты точки
"""
return [self.x, self.y]['y' == coordinate]
class Node:
"""
center - центральная точка узла KD-дерева
sort_coord - координата, по которой сортируются точки
left - левое поддерево
right - правое поддерево
"""
def __init__(self, center, sort_coord=None, left=None, right=None):
self.center = center
self.left = left
self.right = right
self.sort_coord = sort_coord
def sort_x(point):
"""
Ключ для функции sorted() - cортировка по X-координате
"""
return point.x
def sort_y(point):
"""
Ключ для функции sorted() - cортировка по Y-координате
"""
return point.y
def build_tree(points, coordinate):
"""
Построение KD-дерева (k=2)
"""
if len(points) == 0:
return
sorted_points = [sorted(points, key=sort_x), sorted(points, key=sort_y)]['y' == coordinate]
middle = len(sorted_points)//2
# Центральная точка узла дерева
center = sorted_points[middle]
# Точки левого поддерева
left_points = sorted_points[0:middle]
# Точки правого поддерева
right_points = sorted_points[middle+1:]
# Координата, по которой будут сортироваться
# точки следующего уровня дерева
next_coordinate = ['x', 'y']['x' == coordinate]
node = Node(center, coordinate)
node.left = build_tree(left_points, next_coordinate)
node.right = build_tree(right_points, next_coordinate)
return node
def search_nn(node, point, search_range=None):
"""
Поиск ближайшего соседа и соседей в пределах search_range
"""
# "Дальнее" поддерево, в котором не производился поиск
far_tree = None
# Расстояние от точки до узла
dist = point.distance_to_point(node.center)
point.radius = [point.radius, dist][dist < point.radius and point != node.center]
sort_coord = node.sort_coord
point_coord = point.get_coordinate(sort_coord)
node_coord = node.center.get_coordinate(sort_coord)
# Если координата точки меньше координаты центра узла,
# то продолжаем поиск в левом поддереве, иначе - в правом
if point_coord < node_coord:
if node.left is not None:
search_nn(node.left, point, search_range)
if node.right is not None:
far_tree = node.right
else:
if node.right is not None:
search_nn(node.right, point, search_range)
if node.left is not None:
far_tree = node.left
# Радиус окружности, в которой могут находиться соседи/сосед
radius = [search_range, point.radius][search_range is None]
# Если ищем не одного ближайшего соседа,
# то проверяем точку узла на принадлежность области поиска
if search_range is not None and dist <= search_range and point != node.center:
point.neighbors.append(node.center)
# Если область поиска пересекает "дальнее" поддерево,
# то там могут быть точки-соседи
if node_coord - point_coord <= radius and far_tree is not None:
search_nn(far_tree, point, search_range)
points_number = int(input("Number of points: "))
points_list = list()
for i in range(1, points_number + 1):
print("#", i, " Enter point's coordinates")
x_coord = int(input("x = "))
y_coord = int(input("y = "))
points_list.append(Point(x_coord, y_coord))
# Строим KD-дерево и получаем его "корень"
root = build_tree(points_list, 'x')
for p in points_list:
# Поиск ближайшего соседа,
# расстояние до которого является радиусом точки
search_nn(root, p)
# Поиск соседей на расстоянии не более 2ух радиусов точки
search_nn(root, p, p.radius*2)
print("\nPoint:", (p.x, p.y))
print("Radius:", p.radius)
print("Number of neighbors:", len(p.neighbors))
|
class Node:
def __init__(self,value,n=None):
self.data=value
self.next_node=n
self.previous_node=None
def get_next(self):
return self.next_node
def get_previous(self):
return self.previous_node
def get_data(self):
return self.data
def set_next(self,value):
self.next_node=value
def set_previous(self,value):
self.previous_node=value
class Doublylinkedlist:
def __init__(self):
self.head=None
def insert(self,value):
new_node=Node(value,self.head)
if self.head:
self.head.set_previous(new_node)
self.head=new_node
def size(self):
current=self.head
count=0
while current:
count+=1
current=current.get_next()
return count
def remove(self,value):
current=self.head
while current:
if current.get_data()==value:
next_node=current.get_next()
previous_node=current.get_previous()
if next_node:
next_node.set_previous(previous_node)
if previous_node:
previous_node.set_next(next_node)
else:
self.head=current
return True
else:
current=current.get_next()
return ('Data not in the List')
def find(self,value):
current=self.head
while current:
if current.get_data==value:
return('The data is present')
else:
current=current.get_next()
return ('Data not in the list')
def contents(self):
current=self.head
while current:
print(current.get_data())
current=current.get_next()
|
def swap(arr, a, b):
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def partition(arr, start, end):
pivotIndex = start
pivotValue = arr[end]
while start <= end:
if arr[start] < pivotValue:
swap(arr, start, pivotIndex)
pivotIndex += 1
start += 1
swap(arr, pivotIndex, end)
return pivotIndex
def quickSort(arr, start, end):
if start >= end:
return
index = partition(arr, start, end)
quickSort(arr, start, index - 1)
quickSort(arr, index + 1, end)
|
"""
Perception of light.
"""
# pyright: reportMissingTypeStubs=false
from typing import Tuple
import cv2
from perception.image import ImageBGR
GAUSSIAN_RADIUS: int = 41
def locate_brightest(img: ImageBGR) -> Tuple[float, Tuple[int, int]]:
"""
Return the value and pixel coordinates of the brightest area in the given
image.
This function uses `cv2.minMaxLoc`, which searches for the brightest single
pixel in the input image. To search a greater area, the image is
pre-processed with a gaussian blur filter, averaging pixel brightness and
hopefully removing any noise that could otherwise be interpreted as the
brightest pixels in the image.
See: https://www.pyimagesearch.com/2014/09/29/finding-brightest-spot-image-using-python-opencv/
"""
grayscale = cv2.cvtColor(img.data, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(grayscale, (GAUSSIAN_RADIUS, GAUSSIAN_RADIUS), 0)
(_, val_max, _, loc_max) = cv2.minMaxLoc(blurred)
return (val_max, loc_max)
|
#for i in range (0,151):
# print(i)
#for i in range (0,1000005,5):
# print(i)
#for i in range (1,50):
# if i%5 == 0 and i%10 == 0:
# print("Coding Dojo")
# elif i%5 == 0:
# print("coding")
# else:
# print(i)
#x= 0
#for i in range(1,500000,2):
# x = x+i
#print(x)
#for i in range (2018,1,-4):
# print(i)
#list = [3,5,1,2]
#for i in list:
# print(i)
#list = [3,5,1,2]
#for i in range(list):
# print(i)
#list = [3,5,1,2]
#for i in range(len(list)):
# print(i)
#def countdown (lowNum, highNum,mul):
# for i in range (lowNum, highNum):
# if i%mul == 0:
# print(i)
#countdown(1,10,3)
|
#!/usr/bin/env python
import turtle
def draw_triangle(some_turtle):
for i in range (3):
some_turtle.forward(100)
some_turtle.right(120)
def draw_art():
window = turtle.Screen()
window.bgcolor('red')
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("green")
brad.speed(120)
for i in range (1,360):
draw_triangle(brad)
brad.right(10)
brad.right(100)
brad.forward(200)
window.exitonclick()
draw_art()
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 9
@author: ashu
"""
#Made by Ashutosh Gupta 101703118
import numpy as np #importing necessary libraries
import pandas as pd
import sys
def remove_outliers(infile, outfile):
dataset = pd.read_csv(infile) #reading dataset
data = dataset.iloc[:,1:]
threshold=1.5
for i, row in data.iterrows():
mean = np.mean(row) #calculating mean
std = np.std(row) #calculating standard deviation
for value in row:
z_score = (value-mean)/std #calculating z-score
if np.abs(z_score)>threshold:
dataset = dataset.drop(data.index[i]) #dropping record
break
dataset.to_csv(outfile, index=False) #output to csv
print ('The number of rows removed:',len(data) - len(dataset)) #printing no. of rows removed
argList=sys.argv # picking values from command line
infile=argList[1] #input file
outfile=argList[2] #output file
remove_outliers(infile,outfile) #calling function
|
import binascii
def str_to_hexStr(string):
str_bin = string.encode('utf-8')
return binascii.hexlify(str_bin).decode('utf-8')
def hexStr_to_str(hex_str):
hex = hex_str.encode('utf-8')
str_bin = binascii.unhexlify(hex)
return str_bin.decode('utf-8')
str1 = 0x1d6152ee93dd4122beb14c307e1779224f7e21b84aefc066549bd3847f15d5b699fd9570c5e7f1227e8c2a9f30cae335d4eb796dabe90d66e75fcea16000a1caf3295ac13ffa3f1b3a3b57377c18901f2f40d6bbaf5fb528100ead418648ed7ce57edaad8c
hex1 = hexStr_to_str(str1)
print(hex1)
print(type(hex1))
|
from xlrd import open_workbook, xldate_as_tuple
from xlutils.display import cell_display
from datetime import datetime, date
import sys
# CSV separator
SEP_CHAR = '|'
def convert(wb_name, sheet_name, start_row):
text = ''
wb = open_workbook(wb_name)
for s in wb.sheets():
if s.name == sheet_name:
for row in range(s.nrows):
if row >= start_row - 1:
values = []
for col in range(s.ncols):
data_type = cell_display(s.cell(row, col)).split(" ")[0]
if data_type == 'date':
# Convert Excel date (looks like a float)
the_date = xldate_as_tuple(s.cell(row,col).value, wb.datemode)
values.append(date.strftime(date(*the_date[:3]), "%m/%d/%Y"))
elif data_type == 'number':
values.append(str(int(s.cell(row,col).value)))
elif data_type == 'logical':
# 0 is false, 1 is true
if int(s.cell(row,col).value) == 0:
values.append('False')
else:
values.append('True')
else:
# Replace CR/LF within cells with a space
values.append(str(s.cell(row,col).value).replace("\n", " "))
text += SEP_CHAR.join(values) + '\n'
sys.stdout.write(text)
if __name__ == '__main__':
if len(sys.argv) <> 4:
print 'Usage: ' + sys.argv[0] + ' file_name.xls sheet_name start_row'
sys.exit(1)
wb_name = sys.argv[1]
sheet_name = sys.argv[2]
start_row = int(sys.argv[3])
convert(wb_name, sheet_name, start_row)
|
def solution(n, arr1, arr2):
answer = []
for i in range(n):
str1 = bin(arr1[i] | arr2[i])[2:]
# str1 = str1[2:]
#str1 = '0'*(n-len(str1))+str1
str1 = str1.rjust(n,'0')
# print(str1)
temp = str1.replace('1','#').replace('0',' ')
answer.append(temp)
return answer
# 오른쪽 정렬은 rjust 라는 함수를 사용하고, 왼쪽 정렬은 ljust 라는 함수를 사용하면 됩니다.
#
# a = "123"
# print a.rjust(10, '#')
# 결과 = '#######123'
# 출처: https://ngee.tistory.com/397 [ngee]
# print(solution(n=5, arr1=[9, 20, 28, 18, 11], arr2=[30, 1, 21, 17, 28]))
print(solution(n=6, arr1=[46, 33, 33, 22, 31, 50], arr2=[27, 56, 19, 14, 14, 10]))
|
parent = {}
rank = {}
def make_set(v):
parent[v] = v
rank[v] = 0
def findRoot(v):
if parent[v] != v:
parent[v] = findRoot(parent[v])
return parent[v]
def union(root1, root2):
if root1 != root2:
if rank[root1] > rank[root2]:
parent[root2] = root1
else:
parent[root1] = root2
if rank[root1] == rank[root2]:
rank[root2] += 1
def solution(n, costs):
for i in range(n):
make_set(i)
kruskal_weight = 0
costs = sorted(costs, key=lambda i: i[2])
print(costs)
for i in costs:
v, u, w = i
r1 = findRoot(v)
r2 = findRoot(u)
if r1 != r2:
union(r1, r2)
kruskal_weight += w
return kruskal_weight
print(solution(n=4, costs=[[0, 1, 1], [0, 2, 2], [1, 2, 5], [1, 3, 1], [2, 3, 8]]))
# 크루스칼 알고리즘
# parent={}#각 노드의 부모
# rank={}#트리의 노드 수
#
# def make_set(v):#각 노드를 집합으로 만들기
# parent[v]=v#일단 부모는 자기 자신
# rank[v]=0#
# def findRoot(v):
# if parent[v]!=v:#부모가 자기 자신이 아니면
# parent[v]=findRoot(parent[v])#최상위의 부모로 갱신
# return parent[v]#부모가 자기 자신이라면 최상위이므로 반환
# def union(r1,r2):
# if r1!=r2:#루트값이 서로 다르면 다른 집합임
# if rank[r1]>rank[r2]:#노드 수가 적은 집합의 루트가 노드 수가 많은 집합의 루트로 변경됨
# parent[r2]=r1
# else:
# parent[r1]=r2
# if rank[r1]==rank[r2]:#집합의 개수가 같다면
# rank[r2]+=1# r1이 속한 집합의 부모 루트가 r2로 변경되었으므로 r2의 개수를 더 많다고 해주기
# def solution(n,costs):
# for i in range(n):#모든 노드에 대해 집합화
# make_set(i)
# #mst=[]#최소 비용 신장(spanning) 트리
# s=0#최소 비용 누적을 위한 변수
# costs=sorted(costs,key=lambda costs:costs[2])#비용 기준으로 정렬
# for j in costs:
# v,u,w=j# v=노드1 u=노드2 w=비용
# r1=findRoot(v)#노드 v에 대한 루트
# r2=findRoot(u)
# if r1!=r2:#노드의 루트가 다르면
# union(r1,r2)#두 노드 중 하나의 집합 수가 많은 집합에 넣기
# s+=w
# #mst.append(j)
# return s #최단거리
# #return mst #최단거리를 만들기 위해 선택된 노드,간선,비용들
# #other kruskal
# def solution(n, costs):
# answer = 0
#
# V = set()
# for v1, v2, cost in costs:
# V.add(v1)
# V.add(v2)
# sortedCosts = sorted(costs, key = lambda x: x[2])
#
# visited = set()
#
# visited.add(V.pop())
# while V:
# for i in range(len(sortedCosts)):
# v1, v2, cost = sortedCosts[i]
# if v1 in visited and v2 in visited:
# sortedCosts.pop(i)
# break
# elif v1 in visited or v2 in visited:
# if v1 in V:
# V.remove(v1)
# if v2 in V:
# V.remove(v2)
# visited.add(v1)
# visited.add(v2)
# answer += cost
# sortedCosts.pop(i)
# break
#
# return answer
# #to greedy
# def greedy_search(start,dic,n, cost_dic):
# available = [i for i in range(n)]
# available.remove(start)
# queue = dic[start]
# costs = [0 for i in range(n)]
# answer = 0
# k = 0
# while available:
# queue.sort(key = lambda x: (x[2],abs(k-x[0])))
# print(queue)
# start, finish, cost = queue.pop(0)
# if finish in available:
# available.remove(finish)
# answer += cost_dic[(start,finish)]
# nextNode = dic[finish]
# queue = nextNode + queue
# k = finish
# return answer
#
# def solution(n, costs):
# answer = 0
# dic = {}
# cost_dic ={}
# for node in costs:
# cost_dic[(node[0], node[1])] = node[2]
# cost_dic[(node[1], node[0])] = node[2]
# if dic.get(node[0])==None:
# dic[node[0]] = [node]
# else:
# dic[node[0]].append(node)
# if dic.get(node[1])==None:
# dic[node[1]] = [[node[1],node[0],node[2]]]
# else:
# dic[node[1]].append([node[1],node[0],node[2]])
#
#
#
# return greedy_search(0, dic,n,cost_dic)
|
# 2020 카카오 인턴십1 키패드 누르기
# https://programmers.co.kr/learn/courses/30/lessons/67256?language=python3
def solution(numbers, hand):
left_hand = "*"
right_hand = "#"
left = ['1', '4', '7', '*']
right = ['3', '6', '9', '#']
mid = ['2', '5', '8', '0']
answer = ''
for number in numbers:
if str(number) in left:
answer += "L"
left_hand = str(number)
elif str(number) in right:
answer += "R"
right_hand = str(number)
else:
left_distance = 0
right_distance = 0
isLeftHandInMid = False
isRightHandInMid = False
if left_hand in left:
left_distance += 1
else:
isLeftHandInMid = True
if right_hand in right:
right_distance += 1
else:
isRightHandInMid = True
if isLeftHandInMid:
left_distance += abs(mid.index(str(number))-mid.index(left_hand))
else:
left_distance += abs(mid.index(str(number))-left.index(left_hand))
if isRightHandInMid:
right_distance += abs(mid.index(str(number))-mid.index(right_hand))
else:
right_distance += abs(mid.index(str(number))-right.index(right_hand))
if left_distance< right_distance:
answer +="L"
left_hand = str(number)
elif left_distance> right_distance:
answer +="R"
right_hand = str(number)
else:
if hand=="right":
answer += "R"
right_hand = str(number)
else:
answer += "L"
left_hand = str(number)
return answer
if __name__ == "__main__":
print(solution([1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5], "right")) # "LRLLLRLLRRL"
print(solution([7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2], "left")) # "LRLLRRLLLRR"
print(solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], "right")) # "LLRLLRLLRL"
|
nums = [3,1,2,3]
answer=0
s1 = set(nums)
half = len(nums)//2
if len(s1)>=half:
answer = half
else:
answer = len(s1)
# def solution(ls):
# return min(len(ls)/2, len(set(ls)))
|
# Ryan Lin , CSC 110, 10/1/19
# Task 1
base_hours = 40
ot_multiplier = 1.5
hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: '))
if hours > base_hours:
overtime_hours = hours - base_hours
overtime_pay = overtime_hours * pay_rate * ot_multiplier
gross_pay = base_hours * pay_rate + overtime_pay
else:
gross_pay = hours * pay_rate
if gross_pay > 100:
net_pay = gross_pay - 15
print('The gross pay is $', format(gross_pay, ',.2f'), sep='')
print('The net pay is $', format(net_pay,',.2f'))
# Task 2
base_hours = 40
ot_multiplier = 1.5
hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: '))
if hours > base_hours:
overtime_hours = hours - base_hours
overtime_pay = overtime_hours * pay_rate * ot_multiplier
gross_pay = base_hours * pay_rate + overtime_pay
else:
gross_pay = hours * pay_rate
medicareCost = gross_pay * .029
socialSecurityCost = gross_pay * .124
if gross_pay > 100:
net_pay = ((gross_pay - medicareCost) - socialSecurityCost - 15)
print('The gross pay is $', format(gross_pay, ',.2f'), sep='')
print('The net pay is $', format(net_pay,',.2f'))
# Task 3
x = int(input('Give me an integer'))
if x % 2 == 0:
print('Even number')
else:
print('Odd Number')
####################################
elif x % 2 != 0:
print('Odd number')
else:
print('Whole number pls')
elif x != int:
print('fake')
|
# Ryan Lin, CSC 110, 10/10/19, Prof Ali
#
# Assignment 1
x = 0
for x in range(1, 10, 2):
y = "*" * x
print('{:^10}'.format(y))
x += 1;
if x == 10:
for x in range(7, 0 , -2):
y = '*' * x
print('{:^10}'.format(y))
x -= - 1
##############################################
# Assignment 2
n = int(input('Give me a non negative integer to factorialize: '))
# n = 5
fac = 1
if n < 0 or isinstance(n, int) != True:
print('Give me a non negative integer...')
for i in range(1, n + 1):
fac *= i
print(fac)
##############################################
# Assignment 3
n = int(input('Give me an integer: '))
# n = 5
ans = 0
for i in range(1, n + 1):
# print(i)
ans += (i / n)
n -= 1
# n = 1
# ans += (i / n -1)
print('{0:.3f}'.format(ans))
|
# coding: utf-8
from __future__ import division
import re
def get_stat_eff(n ,m, t):
"""
This function will compute the :
- Worst;
- Best;
- Random.
Efficiencies according the input variables, as follow:
------------------------------------------------------
(1) n: # Nodes
(2) m: # Edges
(3) t: # Tests
"""
density = ((2*m)/(n*(n-1))) # Density that will be used in rand strategy
max_links = (n*(n-1))/2 # It will be used in worst strategy
best_eff = 0
worst_eff = 0
rand_eff = 0
shift = 1
cpt = 1
cpt_rand = 1
RAND_MAX_ITER = max_links - m
for i in range(0, t+1):
# Now we will accumulate our best, worst and rand strategies
if ( i <= t ):
# We are in the case that not all links have been discovered
# Accumulate the best_eff
if (i <= m): # cause we started at 0
# Not all links had been discovered
best_eff += i
else:
# All links have been discovered
best_eff += m
if ( i > (RAND_MAX_ITER)):
# Now we are in the case where the worst strategy operates and start
# to accumulate, Note the the maximum number of possible links is
# n*n-1/2 and the worst will discover the links at the
# end.
worst_eff += cpt
cpt += 1
else:
rand_eff += shift
# Random efficacity using linear equation
rand_eff = density*0.5*t*t
return best_eff, rand_eff, worst_eff
def get_max_eff(nTest, m):
"""
This function will try to get the max efficiency using the best strategy
formula and try to compute the surfaces
Variables:
----------
(1) nTest: Number of tests used !
(2) m : Number of the graph links!
"""
max_val = 0
if (nTest <= m):
for i in (0, nTest):
max_val += i
return max_val
else:
for i in range(0,m):
max_val += i
max_val += (nTest-m)*m
return max_val
def get_min_eff(nTest, m, n):
"""
This function will try to get the min efficiency using the worst strategy
formula and try to compute the surfaces
Variables:
----------
(1) nTest: Number of tests used !
(2) m : Number of the graph links !
(3) n : Number of nodes !
"""
MAX_LINKS = (n*(n-1))/2
min_val = 0
if (nTest < MAX_LINKS):
return 0
else:
MAX_ITER = nTest * ( ( n * ( n - 1 ) / 2 ) - m )
for i in range(1, int(MAX_ITER)):
min_val += i
return min_val
def get_rand_eff(nTest, m, n):
"""
This function will try to get the random efficiency using the pure random strategy
formula and try to compute the surfaces
Variables:
----------
(1) nTest: Number of tests used !
(2) m : Number of the graph links !
(3) n : Number of nodes !
"""
rand_val = 0
d = (2*m)/(n*(n-1))
return int(0.5*d*pow(nTest,2))
def extract_eff(fin, n, m):
"""
This function will compute the relative, absolute and normalized
efficiencies from a file given as an input of the function [1]
--------------------------------------
[1]: fin is the file given as an input
"""
file_in = open(fin, "r")
t = {}
abs_eff = 0
rel_eff = 0
norm_eff = 0
rand_eff = 0
tmp1 = 0
compteur = 0
shift = 1
tp = 0
fp = 0
density = ((2*m)/(n*(n-1))) * 100
for text in file_in:
text = text.replace('\n','')
tmp = re.split(' ', text)
if int(tmp[0]) in list(t.keys()):
# It mens that in this iteration another node has been discovered
t[int(tmp[0])] += 1
else:
t[int(tmp[0])] = 1
for i in range(0, int(max(t.keys())+1)):
# At each step we check how many links have been discovered :)
if i in t.keys():
abs_eff = abs_eff + 1 + compteur
compteur += 1
tp += 1
#tmp1 = abs_eff
#print i, " ", abs_eff
else:
fp += 1
abs_eff = abs_eff + compteur
nTest = int(max(t.keys()))
min_val = get_min_eff(nTest, m, n)
max_val = get_max_eff(nTest, m)
rand_val= get_rand_eff(nTest, m, n)
norm_eff = (abs_eff - min_val) / (max_val-min_val)
norm_eff_rand = (rand_val - min_val) / (max_val-min_val)
rel_eff = (norm_eff) / (norm_eff_rand)
prec = tp / (tp+fp)
recall = tp / m
fscore = (2*prec*recall) / (prec+recall)
print "---------------------------------------------------"
print " Statistical Informations"
print "- Precision:\t", prec
print "- Fscore:\t", fscore
print "- Recall:\t", recall
print "---------------------------------------------------"
file_in.close()
print " NOMBRE DE TEST:", nTest
return abs_eff, rel_eff, norm_eff
|
# game ideas...
# cave adventure game, the point of which is to find a way out, to the light..
print("""You awaken in a cave, the only light is that of the lattern nearby on
the cavern floor. You do not know how you got here, all you remember is falling
asleep in your bed. after a brief look around with the lattern in your hand
you start to notice that the cave continues in 2 different directions.""")
print("1. You choose to go down the right hand path")
print("2. You choose to go down the left hand path")
|
from random import randint
from celle import Celle
class Spillebrett:
# The constructor will have four instance variables notably self._rader which
# initiates the rows, self._kolonner which initiates the columns,
# self._rutenett which is an empty list and self._generasjonsnummer
# which is set to zero at the beginning and increases as the board updates.
def __init__(self, rader, kolonner):
self._rader = rader
self._kolonner = kolonner
self._rutenett = []
self._generasjonsnummer = 0
# A nested list is made by going through 2 for-loops where it runs through the
# columns and rows accordingly. A list is appended to the board. A cell object
# is appended to the list. The method _generer is then called in which 1/3
# of the cells become alive.
for rad in range(self._rader):
list = []
for kolonne in range(self._kolonner):
list.append(Celle())
self._rutenett.append(list)
self._generer()
# Nested for-loop that goes through the board and tells about the status of each
# cell. A new line is printed at the start of the next row.
def tegnBrett(self):
for i in range(3):
print("\n")
for rad in range(self._rader):
for kolonne in range(self._kolonner):
print(self._rutenett[rad][kolonne].hentStatusTegn(), end="")
print()
# Two lists: skalLeve (contain dead cells that will become alive)
# and skalDoed (contain living cells that will die) are created.
# The method will go through the board via a nested for-loop to find the cell´s
# coordinates. It will check if the neighbouring cells around the selected
# cell are alive or dead. Depending on the status of the neighbouring cells,
# it will determine whether the current cell will continue to live or die.
def oppdatering(self):
skalLeve = []
skalDoe = []
for rad in range(self._rader):
for kolonne in range(self._kolonner):
celleKoordinater = self._rutenett[rad][kolonne]
# A new list is created and will contain all living neighbouring cells
# around the current cell.
naboer = self.finnNabo(rad, kolonne)
naboerSomErLevende = []
# For each neighbour, if the neighbouring cell is alive, it is appended
# to the list.
for nabo in naboer:
if nabo.erLevende():
naboerSomErLevende.append(nabo)
if celleKoordinater.erLevende():
# With 2 or 3 neighbours, cell remains alive
if len(naboerSomErLevende) in range(2, 4):
skalLeve.append(celleKoordinater)
# cell dies if it has less than 2 (underpop.) or
# more than 3 (overpop.) neighbours
elif len(naboerSomErLevende) < 2 or len(naboerSomErLevende) > 3:
skalDoe.append(celleKoordinater)
# cell revives if it has 3 neighbouring cell that are alive
else:
if len(naboerSomErLevende) == 3:
skalLeve.append(celleKoordinater)
# Status of the cells are changed in the given list
for celleStatus in skalLeve:
celleStatus.settLevende()
for celleStatus in skalDoe:
celleStatus.settDoed()
# When the board updates, it is incremeted by 1.
self._generasjonsnummer += 1
# For each living cell in the board, increment levende by 1.
def finnAntallLevende(self):
levendeCelle = 0
for rad in range(self._rader):
for kolonne in range(self._kolonner):
if self._rutenett[rad][kolonne].erLevende():
levendeCelle += 1
return levendeCelle
# The method _generer goes through the rows and columns through a nested
# loop. The variable tilfeldigTall is created where a random number
# between 0 and 2 is selected. If the random number is 0, the cell at that
# particular coordinate will be set to alive.
def _generer(self):
for rad in range(self._rader):
for kolonne in range(self._kolonner):
tilfeldigTall = randint(0,2)
if tilfeldigTall == 0:
self._rutenett[rad][kolonne].settLevende()
# The method finnNabo was adapted from the live koding video from Uke 10.
# The cell will live or die depending on the neighbouring cells´ status.
# An empty list, naboer, for the neighbouring cells is created. A nested
# for-loop checks for the neighbouring cells from -1, 0 and 1, i.e.
# one cell before the actual cell, the current cell and one cell after
# the actual cell. The if statements check for the corners and edges to
# make sure the cells are within the board and are not equal to the
# current cell. Once all the criteria are fulfilled, the neighbours are
# appended to the list.
def finnNabo(self, rad, kolonne):
naboer = []
for r in range(-1, 2):
for k in range(-1, 2):
naboRad = rad + r
naboKolonne = kolonne + k
gyldigNabo = True
if naboRad < 0 or naboRad >= self._rader:
gyldigNabo = False
if naboKolonne < 0 or naboKolonne >= self._kolonner:
gyldigNabo = False
if naboRad == rad and naboKolonne == kolonne:
gyldigNabo = False
if gyldigNabo:
naboer.append(self._rutenett[naboRad][naboKolonne])
return naboer
|
def posterior(prior, likelihood, observation):
"""Returns the posterior probability of the class variable being true, given
the observation, ie. it returns p(Class=true|observation). The argument
observation is a tuple of n booleans such that observation[i] is the
observed value (T/F) for the input feature X[i]. Prior = a real number
representing p(Class=true). likelihood = a tuple of length n where each
element is a pair of real numbers such that
likelihood[i][False] = p(X[i]=true|C=false) and
likelihood[i][True] = p(X[i]=true|C=true)."""
prior_f = 1 - prior
features_true = 1
features_false = 1
for i in range(len(observation)):
if observation[i]:
features_true *= likelihood[i][True]
features_false *= likelihood[i][False]
else:
features_true *= 1 - likelihood[i][True]
features_false *= 1 - likelihood[i][False]
features_true *= prior
features_false *= prior_f
return features_true / (features_true + features_false)
|
# Uses python3
import sys
def calc_fib(n):
fib_nums=[0,1]
while(n>len(fib_nums)-1):
i=len(fib_nums)
temp_fib=(fib_nums[i-1]+fib_nums[i-2])%10
fib_nums.append(temp_fib)
return fib_nums
def fibonacci_sum_naive(n):
if(n==0):
return 0
elif(n==1):
return 1
else:
fib_nums=calc_fib(n)
sum=0
for i in fib_nums:
sum=(sum+i)%10
return sum
if __name__ == '__main__':
input = sys.stdin.read()
n = int(input)
print(fibonacci_sum_naive(n%60))
|
'''
Try Else Finally
Finally: Regardless of the exceptions, a code will always be executed
'''
try:
x = int(input('Put a number: '))
y = 10/x
except ZeroDivisionError:
print('Cannot divide by zero')
else:
print(y)
finally:
print('Codes were excuted')
|
def selection_sort(alist):
# 与抓牌类似,左手上先有一张牌alist[0],然后抓一张牌alist[1]与手上的牌比较,value代表每次抓取的牌
for i in range(1,len(alist)):
value = alist[i]# 右手摸到的牌
# while循环体套路
j = i-1
while j>=0:
# 与手上左边的牌比较,如果比左边的牌小就交换位置
if value<alist[j]:
alist[j+1] = alist[j]
alist[j] = value
j = j-1
# else:
# # 如果不满足条件了则表明排序已经结束
# break
a = [15,66,19,36,2,46]
selection_sort(a)
print(a)
|
array = ["Malcolm", "X"]
array[0] = "Tray"
print(array[0] + " " + array[1])
groceryArray = ["Eggs", "Milk", "Yogurt", "Kombucha", "Chicken", "Lettuce", "Carrots"]
listSlice = groceryArray[3:6] # ":" slices the array non-inclusive of last index
slice_up_to_three = groceryArray[:3] #inclusive w/o "0" or last index
slice_from_three = groceryArray[3:]
slice_second_from_end = groceryArray[-2]
print(listSlice)
print(slice_up_to_three)
print(slice_from_three)
print(slice_second_from_end)
#Tuples - set of values nested in parenthesis and hold any number of variables
(x_values, y_values) = ([1,2,3],[-1,-2,-3])
# print(f'PLOT THIS POINT: {x_values[2]}, {y_values[0]}' ) - string interpolation python 3.6+
print("PLOT POINT: %s, %s" % (x_values[2], y_values[0])) #old version of string interpolation
tuple = (x_values, y_values) #allows you to pull out each as array and delve into each array/list
print(tuple[0][1])
|
s = 'bicycle'
s[::3] #'bye'
s[::-1] #'elcycib'
print(s[::-2]) # eccb'
print(id(s[::-2]))
print(id(s[::-1])) #id相同
print(type((s[::-2])))
list = [3,4,5,6,7,8]
a=list[::-1]
b=list[1:3]
print(id(a),id(b)) #id不同
|
import collections
info=("feipeixuan",27,"牛逼")
### 元组拆包
name,age,_ = info
print(name,age)
name,*others =info
print(others) #[27, '牛逼']
### 嵌套元组拆包
info = (222,(3,5))
c,(x,y) =info
print(x,y)
### 命名元祖
Card = collections.namedtuple('Card', ['rank', 'suit']) #
print(Card(2,3))
Person = collections.namedtuple('Person',['name','jjj'])
print(Person("fei",(22,33)))
# Card(rank=2, suit=3)
# Person(name='fei', jjj=(22, 33))
|
a=[2,3,4,5,6,78]
b=['22','333','444','888888']
a.sort(reverse=True) #[78, 6, 5, 4, 3, 2]
b.sort(key=len)
print(b)
c={"aaa":22222,"bb":3}
print(sorted(c.items(),key=lambda item:item[1])) # 按照value 排序
print(c.items())
|
# coding:utf-8
"""
@author: mcfee
@description:
@file: test_slice.py
@time: 2020/7/10 下午3:12
"""
a = [1, 2, 3, 4]
print(a[1:-1])
print(type(a[1:-1]))
class Person:
def __getitem__(self, item):
print("222")
return item
person = Person()
print(person[1:-1]) # slice(1, -1, None)
print(dir(slice))
print(slice(None, 10, 2).indices(5)) #长度为5的切片,start=none,end=10,步长为2
b=person[1:-1]
print(b)
|
from random import *
# random number b/w 1 and 100
comp_num = randint(1, 100)
# getting user input
while True: # # test (check format) and get user input again
try:
guess = int(input("Enter an integer input between 1-100 : "))
break
except ValueError:
print("Error! That was not a valid INTEGER number. Try again...")
while guess < 1 or guess > 100: # input in range check
while True: # # test (check format) and get user input again
try:
guess = int(input("Error! input out of bound, Enter an integer input between 1-100 :"))
break
except ValueError:
print("Error! That was not a valid INTEGER number. Try again...")
while comp_num != guess: # Keep Looping if random comp_num not found
if guess > comp_num: # If guess is higer than the random comp_num
print("Too high! Guess again")
# check hotness/coldness
if comp_num-2 <= guess <= comp_num+2:
print("YOUR SO HOT!!!...")
elif comp_num - 5 <= guess <= comp_num + 5:
print("getting even EVEN EVEN! hotter...")
elif comp_num - 9 <= guess <= comp_num + 9:
print("getting even EVEN hotter...")
elif comp_num - 16 <= guess <= comp_num + 16:
print("getting even hotter...")
elif comp_num - 25 <= guess <= comp_num + 25:
print("getting hot...")
elif comp_num - 35 <= guess <= comp_num + 35:
print("still a bit cold...")
elif comp_num-45 <= guess <= comp_num+45:
print("cold...")
elif comp_num - 60 <= guess <= comp_num + 60:
print("Super Cold")
else:
print("Your waaaay too cold!!....")
while True: # test (check format) and get user input again
try:
guess = int(input("Enter an integer input between 1-100 : "))
break
except ValueError:
print("Error! That was not a valid INTEGER number. Try again...")
elif guess < comp_num: # If guess is lower than the random comp_num
print("Too low! Guess again")
# check hotness/coldness
if comp_num-2 <= guess <= comp_num+2:
print("YOUR SO HOT!!!...")
elif comp_num - 5 <= guess <= comp_num + 5:
print("getting even EVEN EVEN! hotter...")
elif comp_num - 9 <= guess <= comp_num + 9:
print("getting even EVEN hotter...")
elif comp_num - 16 <= guess <= comp_num + 16:
print("getting even hotter...")
elif comp_num - 25 <= guess <= comp_num + 25:
print("getting hot...")
elif comp_num - 35 <= guess <= comp_num + 35:
print("still a bit cold...")
elif comp_num-45 <= guess <= comp_num+45:
print("cold...")
elif comp_num - 60 <= guess <= comp_num + 60:
print("Super Cold")
else:
print("Your waaaay too cold!!....")
while True: # # test (check format) and get user input again
try:
guess = int(input("Enter an integer input between 1-100 : "))
break
except ValueError:
print("Error! That was not a valid INTEGER number. Try again...")
# If guess IS INFACT the random comp_num!!!
print("Congrats! the answer was infact '%d' well done!" % comp_num)
|
from abc import ABC, abstractmethod
from utils.state import State
### THIS FILE CONTAINS CODE CLASSES OF DEVELOPED STATE SCORERS
# values of the state variable can be found in state.py
class StateScorer(ABC):
"""This is a base class for a state scorer. All developed state
scorers developed should inherit from this class."""
@abstractmethod
def score(self, state: State) -> float:
"""Returns a scalar representing the score of a given game state."""
raise NotImplementedError
|
#!/usr/bin/env python
# 2019-3-31
from .node import Node
class BinarySearchTree:
def __init__(self):
self.__root = None
self.__comparisons = 0
@property
def comparisons(self):
return self.__comparisons
def __str__(self):
if self.__root is not None:
self.__printTree(self.__root)
return ''
def __printTree(self, cur_node):
if cur_node is not None:
self.__printTree(cur_node.left_child)
print(cur_node.value)
self.__printTree(cur_node.right_child)
def insert(self, value):
# check if the root can be used
if self.__root is None:
self.__root = Node(value)
else:
self.__insert(value, self.__root)
def __insert(self, value, cur_node):
if value < cur_node.value:
if cur_node.left_child is None:
cur_node.setLeftChild(Node(value))
else:
self.__insert(value, cur_node.left_child)
elif value > cur_node.value:
if cur_node.right_child is None:
cur_node.setRightChild(Node(value))
else:
self.__insert(value, cur_node.right_child)
else:
print('value in tree')
def search(self,value):
# reset the comparison value for new search
self.__comparisons = 0
if self.__root is not None:
return self.__search(value, self.__root)
else:
return None
def __search(self, value, cur_node):
if value == cur_node.value:
self.__comparisons += 1
return cur_node
elif value < cur_node.value and cur_node.left_child is not None:
self.__comparisons += 2
return self.__search(value,cur_node.left_child)
elif value > cur_node.value and cur_node.right_child is not None:
self.__comparisons += 3
return self.__search(value,cur_node.right_child)
|
#!/usr/bin/env python3
# 2019-4-16
'''
NOTICE: This is an implementation using the Hashmap from assignment 2.
I prefer the other but just in case alan prefers this, I added it.
'''
import re
from .HashTable import HashTable
class AdjacencyList:
def __init__(self, commands):
self.__commands = commands
# In this case we want each entry to be its own vertex,
# so find the num of vertices to make the table
vertices = len(re.findall('add vertex', ''.join(self.__commands)))+1
self.__graph = HashTable(vertices)
self.buildList()
def __str__(self):
for vertex in self.__graph.keys:
value = self.__graph.get(int(vertex))
print(f'{vertex}\t {value}')
return ''
''' Properties '''
@property
def adjacencyList(self):
return self.__graph
''' Methods '''
def buildList(self):
for cmd in self.__commands:
if re.match(r'add vertex .*', cmd):
identifier = re.sub(r'add vertex', '', cmd)
# I guess theres nothing to do here...
elif re.match(r'add edge .*', cmd):
edge_vals = re.sub(r'add edge', '', cmd)
values = edge_vals.split('-')
self.__graph.put(values[0].strip(), values[1].strip())
self.__graph.put(values[1].strip(), values[0].strip())
|
"""Main games module."""
import prompt
ROUNDS_COUNT = 3
def launch(game):
"""Launch games.
Args:
game: game module
Returns:
Return cli to player.
"""
print('Welcome to the Brain Games!')
player_name = prompt.string('May I have your name? ')
print('Hello, {0}!'.format(player_name))
print(game.QUESTION_OF_GAME)
for _ in range(ROUNDS_COUNT):
question, true_answer = game.generate_round()
print('Question: {0}'.format(question))
player_answer = prompt.string(
'Your answer: ',
)
if player_answer == true_answer:
print('Correct!')
else:
print(
("'{0}' is wrong answer ;(. Correct answer was '{1}'."
).format(player_answer, true_answer),
)
print("Let's try again, {0}!".format(player_name))
return
print('Congratulations, {0}!'.format(player_name))
|
"""
exibindo uma tela vazia.
a tela abre.
escutamos o click em algumas teclas
"""
import pygame
def exibe_janela_e_escuta_click_em_varios_botoes():
largura_da_JANELA = 400
altura_da_JANELA = 400
largura_altura_da_JANELA = (largura_da_JANELA, altura_da_JANELA)
pygame.display.set_mode(largura_altura_da_JANELA)
pygame.display.set_caption("Pressione a setas esquerda, direita e letra A.")
pygame.display.init()
continuar_no_loop_while = True
contador = 0
####################################################
while continuar_no_loop_while:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
continuar_no_loop_while = False
continue # abandono o loop while
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
pygame.display.set_caption("seta para direita pressionada")
if event.key == pygame.K_LEFT:
pygame.display.set_caption("seta para esquerda pressionada")
if event.key == pygame.K_a:
pygame.display.set_caption("letra A pressionada")
####################################################
# após ter feito tudo que queríamos, fechamos o programa:
#pygame.display.quit()
exibe_janela_e_escuta_click_em_varios_botoes()
|
"""
exibindo uma tela vazia.
a tela abre.
escutamos o pressionamento da tecla X
para fechar a tela.
"""
import pygame
def exibe_janela_e_escuta_a_letra_x():
largura_da_JANELA = 400
altura_da_JANELA = 400
largura_altura_da_JANELA = (largura_da_JANELA, altura_da_JANELA)
pygame.display.set_mode(largura_altura_da_JANELA)
pygame.display.set_caption("Pressione a tecla X para encerrar.")
pygame.display.init()
print(f"pygame.KEYDOWN: {pygame.KEYDOWN}") # KEYDOWN == TECLA PRESSIONADA > 768
print(f"pygame.KEYUP: {pygame.KEYUP}") # KEYUP == TECLA LIBERADA > 769
print(f"pygame.QUIT: {pygame.QUIT}") # QUIT == X DA JANELA, PARA SAIR > 256
####################################################
continuar_no_loop_while = True
contador = 0
####################################################
while continuar_no_loop_while:
events = pygame.event.get() # captura todos os eventos ocorridos neste exato instante: tiro uma foto dos eventos
for event in events: # percorrendo todos os eventos que estão dentro da 'foto' tirada
print(f"novo evento detectado nº {contador}")
contador = contador + 1
if event.type == pygame.KEYDOWN: # se o evento foi TECLA PRESSIONADA
if event.key == pygame.K_x: # checo se a tecla foi X
continuar_no_loop_while = False
####################################################
# após ter feito tudo que queríamos, fechamos o programa:
#pygame.display.quit()
exibe_janela_e_escuta_a_letra_x()
|
import numpy
firstLine = [int(x) for x in input().split()]
rows = firstLine[0]
columns = firstLine[1]
matrix = []
for i in range(rows):
M = numpy.array([int(x) for x in input().split()])
matrix.append(M)
print(numpy.transpose(matrix))
print(numpy.array(matrix).flatten())
|
def divide(dividend: int, divisor: int) -> int:
answer = 0
if dividend < 0:
return divide(-dividend, divisor) * -1
if divisor < 0:
divisor *= -1
while dividend - divisor >= 0:
dividend -= divisor
answer += 1
return -answer
elif divisor > 0:
while dividend - divisor >= 0:
dividend -= divisor
answer += 1
return answer
|
import unittest
from knapsack import Knapsack
from dynamic_program import Coins
class Chal4Test(unittest.TestCase):
def test_knapsack_values(self):
bag = (
(10, 60),
(20, 100),
(30, 195),
(40, 120),
(50, 120),
(5, 120),
(60, 120),
(10, 50),
(10, 200),
(20, 120),
)
size = 50
ks = Knapsack(bag, size)
result = ks.solve()
self.assertEqual(((30, 195), (5, 120), (10, 200)), result)
def test_knapsack_empty(self):
bag = ()
size = 50
ks = Knapsack(bag, size)
result = ks.solve()
self.assertEqual((), result)
def test_coins_values(self):
coins = [1, 5, 10, 25]
target_value = 100
c = Coins(coins, target_value)
result = c.solve()
self.assertEqual(4, result)
def test_coins_empty(self):
coins = []
target_value = 100
c = Coins(coins, target_value)
result = c.solve()
self.assertEqual(-1, result)
def test_coins_no_answer(self):
coins = [5, 10, 25]
target_value = 103
c = Coins(coins, target_value)
result = c.solve()
self.assertEqual(-1, result)
if __name__ == "__main__":
unittest.main()
|
from vertex import Vertex
class Graph:
""" Graph Class
A class demonstrating the essential facts and functionalities of graphs.
"""
def __init__(self, file_name=None):
"""Initialize a graph object with an empty dictionary."""
self.vertices = {}
self.num_vertices = 0
self.num_edges = 0
self.type = "G"
# if file_name specified, read in graph from file
if file_name:
self._read_from_file(file_name)
def add_vertex(self, key):
"""Add a new vertex object to the graph with the given key and return
the vertex."""
if key not in self.vertices:
self.num_vertices += 1
self.vertices[key] = Vertex(key)
return self.vertices[key]
def get_vertex(self, key):
"""Return the vertex if it exists"""
return None if key not in self.vertices else self.vertices[key]
def add_edge(self, key1, key2, weight=1):
"""Add an edge from vertex with key `key1` to vertex with key `key2`
with an optional weight."""
if self.get_vertex(key1) is None:
self.add_vertex(key1)
if self.get_vertex(key2) is None:
self.add_vertex(key2)
self.num_edges += 1
self.vertices[key1].add_neighbor(self.vertices[key2], weight)
def get_vertices(self):
"""Return all the vertices in the graph."""
return self.vertices.keys()
def __iter__(self):
"""Iterate over the vertex objects in the graph, to use sytax: for v
in g."""
return iter(self.vertices.values())
def get_edges(self):
"""Return a list of edges in the graph."""
result = []
for v in self.vertices.values():
for w in v.neighbors:
result.append((v.get_id(), w.get_id(), v.get_edge_weight(w)))
return result
def _read_from_file(self, file_name):
"""Read a graph from a file."""
# load file specified
with open(file_name, 'r') as f:
file_lines = f.readlines()
# if less than 3 lines in file, throw error
if len(file_lines) < 3:
raise Exception("Expected input file to contain at least 3 lines.")
# set graph type
self.type = file_lines[0].strip()
if self.type != "G" and self.type != "D":
raise Exception(
f"Expected input file to have a type of G or D for line 1 \
but {self.type} was given."
)
# add graph vertices
for vtx in file_lines[1].strip().split(','):
self.add_vertex(vtx)
# add graph edges
for line in file_lines[2:]:
edge_spec = line.strip("() \n").split(',')
if len(edge_spec) != 3 and len(edge_spec) != 2:
raise Exception(
f"Expected input file edge specification to have 2 or 3 \
items but {line} was given."
)
vtx1, vtx2 = edge_spec[:2]
weight = 1 if len(edge_spec) != 3 else int(edge_spec[2])
if self.type == "G":
self.add_edge(vtx1, vtx2, weight)
self.add_edge(vtx2, vtx1, weight)
else:
self.add_edge(vtx1, vtx2, weight)
|
x = 1
while True:
if x%2==1 and x%3==2 and x%4==3 and x%5==4 and x%6==5 and x%7==0:
break
x += 1
print(f"sol: {x}")
|
class BinaryTree:
"""
A Binary Tree, i.e. arity 2.
=== Attributes ===
@param object data: data for this binary tree node
@param BinaryTree|None left: left child of this binary tree node
@param BinaryTree|None right: right child of this binary tree node
"""
def __init__(self, data, left=None, right=None):
"""
Create BinaryTree self with data and children left and right.
@param BinaryTree self: this binary tree
@param object data: data of this node
@param BinaryTree|None left: left child
@param BinaryTree|None right: right child
@rtype: None
"""
self.data, self.left, self.right = data, left, right
def __eq__(self, other):
"""
Return whether BinaryTree self is equivalent to other.
@param BinaryTree self: this binary tree
@param Any other: object to check equivalence to self
@rtype: bool
>>> BinaryTree(7).__eq__("seven")
False
>>> b1 = BinaryTree(7, BinaryTree(5))
>>> b1.__eq__(BinaryTree(7, BinaryTree(5), None))
True
"""
return (type(self) == type(other) and
self.data == other.data and
(self.left, self.right) == (other.left, other.right))
def __repr__(self):
"""
Represent BinaryTree (self) as a string that can be evaluated to
produce an equivalent BinaryTree.
@param BinaryTree self: this binary tree
@rtype: str
>>> BinaryTree(1, BinaryTree(2), BinaryTree(3))
BinaryTree(1, BinaryTree(2, None, None), BinaryTree(3, None, None))
"""
return "BinaryTree({}, {}, {})".format(repr(self.data),
repr(self.left),
repr(self.right))
def __str__(self, indent=""):
"""
Return a user-friendly string representing BinaryTree (self)
inorder. Indent by indent.
>>> b = BinaryTree(1, BinaryTree(2, BinaryTree(3)), BinaryTree(4))
>>> print(b)
4
1
2
3
<BLANKLINE>
"""
right_tree = (self.right.__str__(
indent + " ") if self.right else "")
left_tree = self.left.__str__(indent + " ") if self.left else ""
return (right_tree + "{}{}\n".format(indent, str(self.data)) +
left_tree)
def __contains__(self, value):
"""
Return whether tree rooted at node contains value.
@param BinaryTree self: binary tree to search for value
@param object value: value to search for
@rtype: bool
>>> BinaryTree(5, BinaryTree(7), BinaryTree(9)).__contains__(7)
True
"""
return (self.data == value or
(self.left and value in self.left) or
(self.right and value in self.right))
def parenthesize(b):
"""
Return a parenthesized expression equivalent to the arithmetic
expression tree rooted at b.
Assume: -- b is a binary tree
-- interior nodes contain data in {'+', '-', '*', '/'}
-- interior nodes always have two children
-- leaves contain float data
@param BinaryTree b: arithmetic expression tree
@rtype: str
>>> b1 = BinaryTree(3.0)
>>> print(parenthesize(b1))
3.0
>>> b2 = BinaryTree(4.0)
>>> b3 = BinaryTree(7.0)
>>> b4 = BinaryTree("*", b1, b2)
>>> parenthesize(b4)
'(3.0 * 4.0)'
>>> b5 = BinaryTree("+", b4, b3)
>>> print(parenthesize(b5))
((3.0 * 4.0) + 7.0)
"""
if not (b.left or b.right):
return str(b.data)
else:
return "({} {} {})".format(parenthesize(b.left),
b.data,
parenthesize(b.right))
def list_longest_path(node):
"""
List the data in a longest path of node.
@param BinaryTree|None node: tree to list longest path of
@rtype: list[object]
>>> list_longest_path(None)
[]
>>> list_longest_path(BinaryTree(5))
[5]
>>> b1 = BinaryTree(7)
>>> b2 = BinaryTree(3, BinaryTree(2), None)
>>> b3 = BinaryTree(5, b2, b1)
>>> list_longest_path(b3)
[5, 3, 2]
"""
if node is None:
return []
else:
return_path_left = list_longest_path(node.left)
return_path_right = list_longest_path(node.right)
if len(return_path_left) > len(return_path_right):
return [node.data] + return_path_left
else:
return [node.data] + return_path_right
def insert(node, data):
"""
Insert data in BST rooted at node if necessary, and return new root.
Assume node is the root of a Binary Search Tree.
@param BinaryTree node: root of a binary search tree.
@param object data: data to insert into BST, if necessary.
>>> b = BinaryTree(5)
>>> b1 = insert(b, 3)
>>> print(b1)
5
3
<BLANKLINE>
"""
return_node = node
if not node:
return_node = BinaryTree(data)
elif data < node.data:
node.left = insert(node.left, data)
elif data > node.data:
node.right = insert(node.right, data)
else: # nothing to do
pass
return return_node
def list_between(node, start, end):
"""
Return a Python list of all values in the binary search tree
rooted at node that are between start and end (inclusive).
@param BinaryTree|None node: binary tree to list values from
@param object start: starting value for list insertion
@param object end: stopping value for list insertion
@rtype: list[object]
>>> list_between(None, 3, 13)
[]
>>> b = BinaryTree(8)
>>> b = insert(b, 4)
>>> b = insert(b, 2)
>>> b = insert(b, 6)
>>> b = insert(b, 12)
>>> b = insert(b, 14)
>>> b = insert(b, 10)
>>> list_between(b, 2, 3)
[2]
>>> L = list_between(b, 3, 11)
>>> L.sort()
>>> L
[4, 6, 8, 10]
"""
if node is None:
return []
else:
left_list = ([] if start >= node.data
else list_between(node.left, start, end))
right_list = ([] if end <= node.data
else list_between(node.right, start, end))
mid_list = [node.data] if start <= node.data <= end else []
return left_list + mid_list + right_list
if __name__ == "__main__":
import doctest
doctest.testmod()
|
"""
Some functions for working with puzzles
"""
from puzzle import Puzzle
from collections import deque
import random
# set higher recursion limit
# which is needed in PuzzleNode.__str__
# uncomment the next two lines on a unix platform, say CDF
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, (2**29, -1))
import sys
sys.setrecursionlimit(10**6)
# TODO
# implement depth_first_solve
# do NOT change the type contract
# you are welcome to create any helper functions
# you like
def depth_first_solve(puzzle):
"""
Return a path from PuzzleNode(puzzle) to a PuzzleNode containing
a solution, with each child containing an extension of the puzzle
in its parent. Return None if this is not possible.
@type puzzle: Puzzle
@rtype: PuzzleNode
"""
l = set()
d = deque()
root = PuzzleNode(puzzle)
d.append(root)
while not len(d) == 0:
puzzle_node = d.pop() # as stack
puzz = puzzle_node.puzzle
if duplicate(puzz, l):
continue
elif puzz.is_solved():
return build_correct_path(puzzle_node)
elif len(puzz.extensions()) == 0:
continue
else: # internal node with extension that is not solved
ext = puzz.extensions()
for e in ext:
children_list = puzzle_node.children
children_list.append(PuzzleNode(e, None, puzzle_node))
for child in puzzle_node.children:
d.append(child)
def build_correct_path(puzzle_node):
"""
build the correct puzzle path from solution by tracing its parents.
@param PuzzleNode puzzle_node: solution puzzle_node
@rtype: PuzzleNode
"""
current = puzzle_node
d2 = deque()
while current.parent:
d2.append(current)
current = current.parent
return_node = d2.pop() # as stack
cur_node = return_node
while not len(d2) == 0:
next_node = d2.pop()
cur_node.children = []
cur_node.children = [next_node]
cur_node = next_node
return return_node
def duplicate(puzzle, l):
"""
return True if puzzle is duplicate, otherwise store it in a set
@parem PuzzleNode puzzle: this PuzzleNode
@rtype: bool
"""
if str(puzzle) in l:
return True
else:
l.add(str(puzzle))
return False
# TODO
# implement breadth_first_solve
# do NOT change the type contract
# you are welcome to create any helper functions
# you like
# Hint: you may find a queue useful, that's why
# we imported deque
def breadth_first_solve(puzzle):
"""
Return a path from PuzzleNode(puzzle) to a PuzzleNode containing
a solution, with each child PuzzleNode containing an extension
of the puzzle in its parent. Return None if this is not possible.
@type puzzle: Puzzle
@rtype: PuzzleNode
"""
l = set()
d = deque()
root = PuzzleNode(puzzle)
d.append(root)
while not len(d) == 0:
puzzle_node = d.popleft() # as queue
puzz = puzzle_node.puzzle
if duplicate(puzz, l):
continue
elif puzz.is_solved():
return build_correct_path(puzzle_node)
elif len(puzz.extensions()) == 0:
continue
else: # internal node with extension that is not solved
ext = puzz.extensions()
for e in ext:
children_list = puzzle_node.children
children_list.append(PuzzleNode(e, None, puzzle_node))
for child in puzzle_node.children:
d.append(child)
# Class PuzzleNode helps build trees of PuzzleNodes that have
# an arbitrary number of children, and a parent.
class PuzzleNode:
"""
A Puzzle configuration that refers to other configurations that it
can be extended to.
"""
def __init__(self, puzzle=None, children=None, parent=None):
"""
Create a new puzzle node self with configuration puzzle.
@type self: PuzzleNode
@type puzzle: Puzzle | None
@type children: list[PuzzleNode]
@type parent: PuzzleNode | None
@rtype: None
"""
self.puzzle, self.parent = puzzle, parent
if children is None:
self.children = []
else:
self.children = children[:]
def __eq__(self, other):
"""
Return whether PuzzleNode self is equivalent to other
@type self: PuzzleNode
@type other: PuzzleNode | Any
@rtype: bool
>>> from word_ladder_puzzle import WordLadderPuzzle
>>> pn1 = PuzzleNode(WordLadderPuzzle("on", "no", {"on", "no", "oo"}))
>>> pn2 = PuzzleNode(WordLadderPuzzle("on", "no", {"on", "oo", "no"}))
>>> pn3 = PuzzleNode(WordLadderPuzzle("no", "on", {"on", "no", "oo"}))
>>> pn1.__eq__(pn2)
True
>>> pn1.__eq__(pn3)
False
"""
return (type(self) == type(other) and
self.puzzle == other.puzzle and
all([x in self.children for x in other.children]) and
all([x in other.children for x in self.children]))
def __str__(self):
"""
Return a human-readable string representing PuzzleNode self.
# doctest not feasible.
"""
return "{}\n\n{}".format(self.puzzle,
"\n".join([str(x) for x in self.children]))
|
"""
The rider module contains the Rider class. It also contains
constants that represent the status of the rider.
=== Constants ===
@type WAITING: str
A constant used for the waiting rider status.
@type CANCELLED: str
A constant used for the cancelled rider status.
@type SATISFIED: str
A constant used for the satisfied rider status
"""
from location import Location
WAITING = "waiting"
CANCELLED = "cancelled"
SATISFIED = "satisfied"
class Rider:
"""A rider for a ride-sharing service.
=== Attributes ===
@type id: str
A unique identifier for the rider.
@type destination: Location
The destination for the rider
@type status: str
Rider's status may be one of waiting, cancelled, or satistied
@type patience: int
The number of time units the rider will wait to be picked up before they cancel their ride
"""
def __init__(self, identifier, origin, destination, patience):
"""
Initialize a rider
status defaults to waiting once initialized
@param Rider self: this rider
@param str identifier: unique identifier of this rider
@param Location origin: this rider's origin
@param Location destination: this rider's destination
@param int patience: The number of time units the rider will wait to be picked up before he cancel the ride
@rtype: None
"""
self.id = identifier
self.origin = origin
self.destination = destination
self.status = WAITING
self.patience = patience
def __str__(self):
"""Return a string representation.
@type self: Rider
@rtype: str
>>> r = Rider('Peter', Location(0, 0), Location(1, 1), 10)
>>> print(r)
rider Peter -> origin: (0, 0), destination: (1, 1), patience 10, status: waiting
"""
return 'rider {} -> origin: {}, destination: {}, patience {}, status: {}'.format(self.id, self.origin, self.destination, self.patience, self.status)
def __eq__(self, other):
'''evaluate equivalence of rider objects
@param Rider self: this rider object
@param Rider | Any other: other rider object
>>> r1 = Rider('Peter', Location(0, 0), Location(1, 1), 10)
>>> r2 = Rider('Peter', Location(0, 0), Location(1, 1), 10)
>>> r3 = Rider('Peter', Location(0, 1), Location(1, 1), 10)
>>> r1 == r2
True
>>> r1 == r3
False
'''
return (isinstance(other, Rider) and
self.id == other.id and
self.origin == other.origin and
self.destination == other.destination and
self.patience == other.patience)
|
#Day 2 Lecture
a=2
print('id(2) =', id(2))
print('id(2) =', id(a))
a = a+1
print('id(a) =', id(a))
print('id(3) =', id(3))
b = 2
print('id(b) =', id(b))
print('id(2) =', id(2))
a = 5
a = 'Hello World!'
a = [1,2,3]
def printHello():
print("Hello")
a = printHello
a()
def outer_function():
b = 34
def inner_function():
c = 42
a = 20
def outer_function():
a=34
def inner_function():
a=20
print('a = ', a)
inner_function()
print('a = ', a)
a=20
outer_function()
print('a = ', a)
def identity(x):
return x
x= (lambda x: x + 1)(2)
print(x)
x= lambda a: a + a+20
print(x(5))
x= lambda a,b,c : a+b+c
print(x(5,4,2))
def myfunc(m):
return lambda a : a * m
mydouble = myfunc(2)
print(mydouble(10))
b = 200
a = 20
if b > a:
print("b greater than a")
class Account:
def __init__(self, account_name, balance=0):
self.account_name = account_name
self.balance = balance
def deposit (self, amount):
self.balance += amount
def withdraw (self, amount):
if amount <= self.balance:
self.balance -= amount
else:
print('cant withdraw amount as no funds')
myAccount = Account("john", 100)
myAccount.deposit(100)
myAccount.withdraw(100)
print(myAccount.balance)
#Data hiding
class dummycounter:
__secretCount=0
def count(self):
self.__secretCount += 1
print (self.__secretCount)
Counter = dummycounter()
Counter.count()
Counter.count()
print(Counter._dummycounter__secretCount)
|
# when there is only one condition to check, then only if is fine
# when there are only two condition then, we will use if and else (e.g. even or odd)
# If all if conditions(if+elif) fails, it executes the else
# If first if condition fails it execute subsequent elif and exit
num = 11
if num == 10:
print('In if condition, number is 10')
elif num == 11:
print('In elif condition number is 11')
elif num == 12:
print('In elif condition number is 12')
else:
print('In else condition, expected number is not present')
print('------')
if num == 10:
print('num is 10')
if num == 11:
print('num is 11')
if num == 12:
print('num is 12')
if num == 20:
pass
|
# File Writing
file_obj = open("my_file.txt", "w")
content = """
these are my file contents
this is line #2
this is line #3
bla bla bla
"""
file_obj.write(content)
file_obj.close()
# File Reading
file_obj = open("my_file.txt", "r")
my_data = file_obj.read()
print(f'file contents: {my_data}')
file_obj.close()
# another easy and widely used method
with open("my_file.txt", "r") as file_obj:
print('reading using with:',file_obj.read())
# File Appending
file_obj = open("my_file.txt", 'a')
new_contents = "\n\n\tthese are my new contents"
file_obj.write(new_contents)
file_obj.close()
with open("my_file.txt", 'a') as f:
f.write(new_contents)
|
# !/usr/bin/env python
# -*- encoding:utf-8 -*-
# __author__ = "Xeon"
# Email: [email protected]
""""""
'''
isinstance: 它判断的是,obj是否是此类,或者此类的子孙类,实例化出来的对象
'''
# class A: pass
# class B(A): pass
#
# obj = B()
#
# print(isinstance(obj, B)) # 返回 True
# print(isinstance(obj, A)) # 返回 True
'''
getattr() 获取属性 ***
hasattr() 是否有属性 ***
setattr() 设置属性 *
delattr() 删除属性 *
反射就是: 通过 字符串 去操作对象(实例化对象 类,模块)
'''
'''
对实例化对象的示例
'''
class A:
def __init__(self, name, age):
self.name = name
self.age = age
obj = A('脸哥', 27) # 实例化对象A
ret = getattr(obj, 'abc', None) # 获取obj的abc属性,没有则返回为None目的是不让报错
print(ret)
print(hasattr(obj, 'age')) # obj是否有age属性
# 增加判断例子
if hasattr(obj, 'name'):
ret = getattr(obj, 'name')
print(ret)
setattr(obj, 'sex', '男') # 设置属性
print(getattr(obj, 'sex'))
delattr(obj, 'name') # 删除属性
print(obj.__dict__)
'''
对类的示例
'''
# class A:
# name = 'alex'
# def __init__(self): pass
#
# def func(self): print('IN FUNC')
# print(getattr(A, 'name')) # 获取A类的name为alex
# ret = getattr(A, 'func')
# ret(None) # 执行A类的动态方法
# ret = input('>>>')
# f1 = getattr(A, ret)(None) # 输入func, 返回IN FUNC
'''
对当前模块(文件)
'''
# def func():
# print('in func')
#
# import sys
#
# current_mode = sys.modules[__name__]
# getattr(current_mode, 'func')
'''
对其他模块(文件)
'''
# 首先在相对路径建立一个fs的python文件
# fs文件内容
# n1 = '二狗'
#
# def func():
# print(666)
#
# class A:
# name = 'alex'
#
# def func2(self):
# print('--------IN FUNC2')
# import fs # 标红先忽略
# print(getattr(fs, 'n1')) # 返回 二狗
#
# ret = getattr(fs, 'func')
# ret() # 返回 666
# 方法1:获取A类的静态属性
# clas = getattr(fs, 'A')
# print(clas.name) # 返回 alex
# 方法2:即执行A类方法,又执行A类的动态方法
# print(getattr(fs.A, 'name')) # 返回 alex
# getattr(fs.A, 'func2')(None) # 返回 --------IN FUNC2
|
#
# @lc app=leetcode id=75 lang=python3
#
# [75] Sort Colors
#
class Solution:
def sortColors(self, nums:[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zeros,ones=-1,-1
for index,num in enumerate(nums):
nums[index] = 2
if num == 0:
zeros += 1
ones += 1
nums[ones] = 1
nums[zeros] = 0
elif num == 1:
ones += 1
nums[ones] = 1
return
|
#
# @lc app=leetcode id=2 lang=python3
#
# [2] Add Two Numbers
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l = l1
temp = 0
while ((l1.next is not None) or (l2.next is not None) ):
num = l1.val + l2.val + temp
l1.val = num % 10
temp = num//10
if(l1.next is None): # Make Sure l1 is longer than l2
l1.next = l2.next
l2.next = None
l1 = l1.next
if(l2.next is None):
l2.val = 0
else: l2 = l2.next
num = l1.val + l2.val + temp
l1.val = num % 10
temp = num//10
if temp:
l1.next = l2
l2.val =1
return l
|
#
# @lc app=leetcode id=10 lang=python3
#
# [10] Regular Expression Matching
#
class Solution:
def isMatch(self, text: str, pattern: str) -> bool:
lengthOfText,lengthOfPattern = len(text),len(pattern)
dp = [[False]* (lengthOfPattern + 1) for _ in range(lengthOfText+1)]
dp[-1][-1] = True #End of Match
for i in range(lengthOfText,-1,-1):
for j in range(lengthOfPattern-1,-1,-1):
if(j == lengthOfPattern-1):
dp[i][j] = ( (i == lengthOfText-1) and (self.isMatchOfSingleCharacter(text[i],pattern[j])) )
else:
if(pattern[j+1] == '*'):
if(i == lengthOfText ): # End of Text
dp[i][j] = dp[i][j+2]
else:
dp[i][j] = (dp[i][j+2] or (self.isMatchOfSingleCharacter(text[i],pattern[j]) and dp[i+1][j]))
else:
if(i == lengthOfText): dp[i][j] = False
else:
dp[i][j] = dp[i+1][j+1] and (self.isMatchOfSingleCharacter(text[i],pattern[j]) )
return dp[0][0]
def isMatchOfSingleCharacter(self,textCharacter,patternCharacter)->bool:
return patternCharacter == '.' or patternCharacter == textCharacter
|
#
# @lc app=leetcode id=81 lang=python3
#
# [81] Search in Rotated Sorted Array II
#
class Solution:
def search(self, nums, target):
if not nums:
return False
low = 0
high = len(nums) - 1
while low <= high:
while low < high and nums[low] == nums[high]:#这样的目的是为了能准确判断mid位置,所以算法的最坏时间复杂度为O(n)
low += 1
mid = (low+high)//2
if target == nums[mid]:
return True
elif nums[mid] >= nums[low]: #高区
if nums[low] <= target < nums[mid]:
high = mid - 1
else:
low = mid + 1
elif nums[mid] <= nums[high]: #低区
if nums[mid] < target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return False
|
import socket
# Create a socket object
s = socket.socket()
# Get the local machine name
host = socket.gethostname()
# Set the port number
port = 12345
# Connect to the server
s.connect((host, port))
while True :
# Send a message to the server
text=input("message to server:")
if text == "q" :
break
s.send(text.encode())
# Receive data from the server
data = s.recv(1024)
# Print the received data
print("server say:",data.decode())
# Close the connection
s.close()
|
import math
ninty_angle = 90
# Create a Parent class, which all the other classes can refer to
class ParentShape():
def __init__(self, base, side, theta):
'''(ParentShape, float, float, float) -> NoneType
REQ: base > 0, side > 0
REQ: 0 < theta < 180
Initialize all the vairables, and make sure they are float
'''
self.base = base
self.side = side
self.theta = theta
# Convert the given angle into degrees and then apply math.sin
# this will allow for the use of theta to find area of shape
def area(self):
''''Return area of shape'''
conv_to_deg = math.radians(self.theta)
find_sin = math.sin(conv_to_deg)
area = self.base*self.side*find_sin
return area
# Return all the variables of the shape in the order: base, side, theta
def bst(self):
return [self.base, self.side, self.theta]
# Create a shape class: Parallelogram
class Parallelogram(ParentShape):
def __init__(self, base, side, theta):
'''(Parallelogram, float, float, float) -> NoneType
REQ: base > 0, side > 0
REQ: 0 < theta < 180
Initialize the variables given using Parent class
'''
ParentShape.__init__(self, base, side, theta)
def __str__(self):
'''Return a message with area of Parallelogram'''
return "I am a Parallelogram with area "+str(ParentShape.area(self))
# Create a new shape class: Rectangle
class Rectangle(ParentShape):
def __init__(self, base, side):
'''(Rectangle, float, float) -> NoneType
REQ: base >0 and side > 0
Initialize the variables given using Parent class
'''
theta = ninty_angle # Make the angle of shape always be 90 degrees
ParentShape.__init__(self, base, side, theta)
def __str__(self):
'''Return a message with the area of the Rectangle '''
return "I am a Rectangle with area "+str(ParentShape.area(self))
# Create a new shape class: Rhombus
class Rhombus(ParentShape):
def __init__(self, base, theta):
'''(Rhombus, float, float) -> NoneType
REQ: base > 0
REQ: 0 < theta < 180
Initialize the variables given using Parent class
'''
side = base # Create a side which is the same value as base
ParentShape.__init__(self, base, side, theta)
# Return a message with the area of the Square
def __str__(self):
'''Return a message with the area of the Rhombus'''
return "I am a Rhombus with area of "+str(ParentShape.area(self))
# Create a new shape class: Square
class Square(ParentShape):
def __init__(self, base):
'''(Square, float) -> NoneType
REQ: base > 0
Initialize the variables given using Parent class
'''
side = base # create a side, with same value as base
theta = ninty_angle # make theta always equal to 90.
ParentShape.__init__(self, base, side, theta)
def __str__(self):
'''Return a message with the area of the Square'''
return "I am a Square with area of "+str(ParentShape.area(self))
|
# Global variables. Feel free to play around with these
# but please return them to their original values before you submit.
a0_weight = 5
a1_weight = 7
a2_weight = 8
term_tests_weight = 20
exam_weight = 45
exercises_weight = 10
quizzes_weight = 5
a0_max_mark = 25
a1_max_mark = 50
a2_max_mark = 100
term_tests_max_mark = 50
exam_max_mark = 100
exercises_max_mark = 10
quizzes_max_mark = 5
exam_pass_mark = 40
overall_pass_mark = 50
def get_max(component_name):
'''(str) -> float
Given the name of a course component (component_name),
return the maximum mark for that component. This is used to allow the GUI
to display the "out of" text beside each input field.
REQ: component_name must be one of: a0,a1,a2,exerises,midterm,exam
>>> get_max('a0')
25
>>> get_max('exam')
100
REQ: component_name in {'a0', 'a1', 'a2', 'exercises', 'term tests',
'quizzes', 'exam'}
'''
# DO NOT EDIT THIS FUNCTION. This function exists to allow the GUI access
# to some of the global variables. You can safely ignore this function
# for the purposes of E2.
if(component_name == 'a0'):
result = a0_max_mark
elif(component_name == 'a1'):
result = a1_max_mark
elif(component_name == 'a2'):
result = a2_max_mark
elif(component_name == 'exercises'):
result = exercises_max_mark
elif(component_name == 'term tests'):
result = term_tests_max_mark
elif(component_name == 'quizzes'):
result = quizzes_max_mark
else:
result = exam_max_mark
return result
def percentage(raw_mark, max_mark):
''' (float, float) -> float
Return the percentage mark on a piece of work that received a mark of
raw_mark where the maximum possible mark of max_mark.
>>> percentage(15, 20)
75.0
>>> percentage(4.5, 4.5)
100.0
REQ: raw_mark >=0
REQ: max_mark > 0
REQ: raw_max <= max_mark
'''
return raw_mark / max_mark * 100
def contribution(raw_mark, max_mark, weight):
''' (float, float, float) -> float
Given a piece of work where the student earned raw_mark marks out of a
maximum of max_marks marks possible, return the number of marks it
contributes to the final course mark if this piece of work is worth weight
marks in the course marking scheme.
>>> raw_contribution(13.5, 15, 10)
9.0
REQ: raw_mark >=0
REQ: max_mark > 0
REQ: weight >= 0
'''
# start your own code here
def percentage(mark_received, marks_out_of):
''' (float, float) -> float
Return the percentage mark on a piece of work that received a mark of
marks_received where the maximum possible mark of max_marks.
>>> percentage(20, 20)
100.0
>>> percentage(3.5, 4.0)
87.5
REQ: raw_mark >=0
REQ: max_mark > 0
REQ: raw_max <= max_mark
'''
return(mark_received/marks_out_of * 100)
#-----------------------------------------------------------------------------
# Function for calculationg Term Mark
# User inserts their marks on assignments, exercises, quizzes, and tests
# The result is overall term mark
def term_work_mark(a0_mark,a1_mark,a2_mark,exercises_mark,quiz_mark,test_marks):
'''(float,float,float,float,float,float) -> (float)
Marks of assignments, exercises, quizzes, and tests, done by the student
are entered. The function will return a percertage which corresponds to
each work divided by the works mark, and mutiplyed by the works weight.
The final result is the average of each work added together which shows
the term mark of the student.
>>> term_work_mark(25, 50, 100, 10, 5, 50)
55.0
>>> term_work_mark(20, 45, 70, 8, 4, 40)
43.9
REQ: a0_mark >=0
REQ: a1_mark >=0
REQ: a2_mark >=0
REQ: exercises_mark >=0
REQ: quiz_mark >=0
REQ: test_marks >=0
'''
# The average of each piece of work done by student is calculated
# the averages of each work are added together to output the term work mark
a0 = ((a0_mark / a0_max_mark)*a0_weight)
a1 = ((a1_mark / a1_max_mark)*a1_weight)
a2 = ((a2_mark / a2_max_mark)*a2_weight)
exercises = ((exercises_mark / exercises_max_mark)*exercises_weight)
quizzes = ((quiz_mark / quizzes_max_mark)*quizzes_weight)
tests = ((test_marks / term_tests_max_mark)*term_tests_weight)
return((float(a0))+(+float(a1))+(float(a2))+(+float(exercises)+
(float(quizzes))+(float(tests))))
#-----------------------------------------------------------------------------
#The function final_mark generates the term mark of the student by adding up
#the percentage received by the student on assignments,tests,quizzes
#tests, and also final exam
def final_mark(a0_mark,a1_mark,a2_mark,exercises_mark
,quiz_mark,test_marks,final_marks):
''' (float,float,float,float,float,float,float) -> (float)
Given the marks scored by the student for
assignments 0,1,2, and the percentage
of the exercises, quizzes, tests, and final exam, the function will
find the average of each and will return a percentage which
corresponds to the students final term mark.
>>> final_mark(25, 50, 100, 10, 5, 50,100)
100.0
>>> final_mark(20, 45, 70, 8, 4, 40, 73)
76.75
REQ: a0_mark >=0
REQ: a1_mark >=0
REQ: a2_mark >=0
REQ: exercises_mark >=0
REQ: quiz_mark >=0
REQ: test_marks >=0
REQ: final_marks >=0
'''
# Here the marks entered of the tests, quizzes, etc.
# are divided by the total marks of each piece of work
# then multiplyed by each of the pieces weight
# the final variable adds up the total percentages of each peice, to
# generate the final term average of the student
a0 = ((a0_mark / a0_max_mark)*a0_weight)
a1 = ((a1_mark / a1_max_mark)*a1_weight)
a2 = ((a2_mark / a2_max_mark)*a2_weight)
exercises = ((exercises_mark / exercises_max_mark)*exercises_weight)
quizzes = ((quiz_mark / quizzes_max_mark)*quizzes_weight)
tests = ((test_marks / term_tests_max_mark)*term_tests_weight)
final = (final_marks / exam_max_mark)*exam_weight
return(a0+a1+a2+exercises+quizzes+tests+final)
#-----------------------------------------------------------------------------
# Function will return True if student receives >= 40 marks on exam and
# receives >=50% on overall term mark, then return True
# if not, return False
def is_pass(a0_mark,a1_mark,a2_mark,exercises_mark,quiz_mark,
test_marks,final_marks):
''' (float,float,float,float,float,float,float) -> (bool)
All the marks of the student on assignments, exercises, quizzes, tests,
and final exam given, are calculated into average. If student scores
higher or equal to 40 marks on the final exam, if false, then
False is returned. If true, then the function checks if the student got
50% or greater overall term mark, if True, then return True. If False,
then return False.
>>> is_pass(20, 45, 70, 8, 4, 40, 41)
True
>>> is_pass(20, 45, 70, 8, 4, 40, 39)
False
>>> is_pass(10, 21, 12, 2, 1, 15, 23)
False
REQ: a0_mark >=0
REQ: a1_mark >=0
REQ: a2_mark >=0
REQ: exercises_mark >=0
REQ: quiz_mark >=0
REQ: test_marks >=0
REQ: final_marks >=0
REQ for student to pass: final_marks >= 40 and add_up >= 50
'''
# All the averages are calculated for each peice of work
# The function will check if exam marks scored are >= 40
# if true then the program will check if term marks are >= 50%
# if true, then returns True.
# if false, returns False.
a0 = ((a0_mark / a0_max_mark)*a0_weight)
a1 = ((a1_mark / a1_max_mark)*a1_weight)
a2 = ((a2_mark / a2_max_mark)*a2_weight)
exercises = ((exercises_mark / exercises_max_mark)*exercises_weight)
quizzes = ((quiz_mark / quizzes_max_mark)*quizzes_weight)
tests = ((test_marks / term_tests_max_mark)*term_tests_weight)
final = (final_marks / exam_max_mark)*exam_weight
add_up = a0+a1+a2+exercises+quizzes+tests+final
# Checking for True or False
if (final_marks >= 40):
if(add_up >=50):
return(True)
else:
return(False)
|
import socket
import sys
import requests
import re
def hosts(host):
""" Return next ip """
host[3] += 1
if host[3] == 256:
if host[2] == 256:
if host[1] == 256:
host[0] += 1
host[1] = 0
host[1] += 1
host[2] = 0
host[2] += 1
host[3] = 0
return host
def request(host):
""" Makes request to parse server`s version """
response = requests.get('http://'+host)
if response.headers['Server'] == '':
print("Поле \"Server\" в заголовке отсутствует")
else:
print("Server: " + response.headers['Server'])
def putin_ip():
""" Ip input """
print("Введите ip адрес (формат x.x.x.x/y): ")
host = input()
if check_ip_format(host) is False:
host = putin_ip()
return host
def error():
""" Print error message """
print("Неверный формат входных данных")
def check_ip_format(host):
""" Check input ip format """
if re.match(r'\d+[.]+\d+[.]+\d\+[.]+\d+[/]+\d+$', host) is None:
error()
return False
sub = int(host.split('/')[1])
if sub > 32:
error()
return False
host = [int(x) for x in host.split('/')[0].split('.')]
for i in host:
if i > 255:
error()
return False
return True
def check_ports_format(mas):
""" Check input ports format"""
if re.match(r'\d+([,]\d+)*$', mas) is None:
error()
return False
return True
def putin_ports():
""" Ports input"""
print("Введите номера портов (через запятую): ")
ports = input().replace(' ', '')
if check_ports_format(ports) is False:
ports = putin_ports()
return ports
host = putin_ip()
sub = int(host.split('/')[1])
mas = putin_ports()
mas = [int(x) for x in mas.split(',')]
pos = int(sub/8)
ips = 2 ** (32 - sub)
host = [int(x) for x in host.split('/')[0].split('.')]
for i in range(pos, 4):
host[i] = 0
for i in range(0, ips):
flag = False
temp = '.'.join([str(x) for x in host])
for port in mas:
s = socket.socket()
s.settimeout(1)
try:
s.connect((temp, port))
except socket.error:
pass
else:
s.close()
print(temp + ' ' + str(port) + ' OPEN')
if (port == 80 or port == 443) and flag is False:
request(temp)
flag = True
host = hosts(host)
|
import random
import sys
def instructions():
print("Welcome to PassGen!")
print("To use PassGen enter values for three arguments.")
print("Argument 1: Password Length (int)")
print("Argument 2: Include Numbers (0=N or 1=Y)")
print("Argument 3: Include Special Characters (0=N or 1=Y)")
return
#Take system arguments and validate to determine if special/numbers are used and length of password
if (len(sys.argv) != 4):
print("ERROR! Incorrect number of arguments entered.")
instructions()
sys.exit(0)
set_bools = [0,0]
try:
num_digits = int(sys.argv[1])
set_bools[0] = int(sys.argv[2])
set_bools[1] = int(sys.argv[3])
except ValueError:
print("Error: Incorrect arguments entered.")
instructions()
sys.exit(0)
#Take requirements in upper case, lower case, special chars, numbers, etc
numbers = "0123456789"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower_case = "abcdefghijklmnopqrstuvwxyz"
special = "!#$%&()+<=>?@^~"
#Get characters for the password
pass_chars = ""
if set_bools[1] == 1:
pass_chars = pass_chars + random.choice(special) + random.choice(special)
if set_bools[0] == 1:
pass_chars = pass_chars + random.choice(numbers) + random.choice(numbers)
for x in range(len(pass_chars), num_digits):
pass_chars = pass_chars + random.choice(upper_case + lower_case)
#Mix up the password
loc = 0
password = ""
loc_set = []
for i in range(0, len(pass_chars)):
loc = random.choice([i for i in range(0, (len(pass_chars))) if i not in loc_set])
loc_set.append(loc)
password = password + pass_chars[loc]
#Output password
print(password)
|
import threading
import _thread
import tkinter as tk
import sys
""" Shows a popup with the alarm time & a button to cancel the alarm """
class Popup(threading.Thread):
def __init__(self, alarmtime):
threading.Thread.__init__(self)
self.__alarmtime = alarmtime
self.daemon = True
self.start()
def run(self):
self.root = tk.Tk()
self.root.title("RasPi Alarm")
# Message box info with alarm time
message = "Alarm is set at {}".format(self.__alarmtime)
msg = tk.Label(self.root, padx = 30, pady = 50, text = message)
msg.pack()
# Cancel button
cancel = tk.Button(self.root, padx = 100, pady = 10, text = "Cancel Alarm", command = self.root.quit)
cancel.pack()
# start GUI
self.root.mainloop()
# when cancel button is clicked, mainloop exits and code continues:
# create flag file to cancel alarm
with open('cancel_alarm', 'w'):
print("Created flag file 'cancel_alarm'")
# destroy popup window
self.root.quit()
print("Alarm cancelled. Give loop some time until sleep is done")
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 13 23:04:48 2018
@author: Habibur Rahman
@email: habib[dot]rahman[at]uits[dot]edu[dot]bd
"""
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return {"isEndOfWord": False, "children": {}, "VisitorCounter" : 0, "Visitors": set()}
def insertWord(self, word, visitorNumber):
current = self.root
for ch in word:
if current["children"].has_key(ch):
node = current["children"][ch]
else:
node = self.getNode()
current["children"][ch] = node
current["VisitorCounter"] = current["VisitorCounter"] + 1
current["Visitors"].add(visitorNumber)
current = node
current["isEndOfWord"] = True
current["VisitorCounter"] = current["VisitorCounter"] + 1
current["Visitors"].add(visitorNumber)
def searchWordPrefix(self, word):
current = self.root
Data = 0
TotalVisitors = 0
for ch in word:
if not current["children"].has_key(ch):
return (False,0, 0)
node = current["children"][ch]
current = node
Data = current["VisitorCounter"]
TotalVisitors = len(current["Visitors"])
return (True, Data, TotalVisitors)
|
# In this Lession we create the constructor
class Employee:
def __init__(self, nickadiname, salary, hobby): # THIS IS CONSTRUCTOR
self.nickname = nickadiname
self.salary = salary
self.hobby = hobby
def details(self):
# CREATE A FUNCTION THAT
return f"Nickname is: {self.nickname} \n Salary is:{self.salary}\n hobby is:{self.hobby}"
# SHOW THE ALL PROPERTIES OF THE SELF
Rohan = Employee("Rondhu", " 2000", "To paly cricket ")
Rahul = Employee("Lauru", "35000", "To paly Football ")
# Rohan.nickname ="Rondhu"
# Rohan.salary = 2000
# Rohan.hobby = "To paly cricket "
# Rahul.nickname ="Lauru"
# Rahul.salary = 35000
# Rahul.hobby = "To paly Football "
print(Rahul.details())
# print(Rahul.details())
|
# a= input("Enter a name ")
# if a.isnumeric():
# raise Exception("number are not allowed")
# print(f"Hello {a}")
a= input("Enter you name ")
try:
print(f"{b} iss allowed!")
except Exception as e:
if a =="singh":
raise ValueError(f"[{a}is blocked")
print()
# raise ValueError(f"[{a}is blocked")
|
def serch(sentence1, sentence2):
"""
This function match the senteces with the
entere query
"""
word1 = sentence1.strip().split(" ")
word2 = sentence2.strip().split(" ")
word_score = 0
for words1 in word1:
for words2 in word2:
if words1.lower() == words2.lower():
word_score += 1
return word_score
if __name__ == "__main__":
sentence = ["python is good ", "python is developed by van rossem ", "python is develpoed by 7990",
"python is not python snake ", "pyton is object oriented language ", "python is interpreted language "] # List of sentece
query = input("Enter the word you want to serch :")
scores = [serch(query, sentences) for sentences in sentence]
sorted_sentence = [sent_score for sent_score in sorted(
zip(scores, sentence), reverse=True) if sent_score[0] != 0]
print(f"{len(sorted_sentence)} result found in ")
for scores, item in sorted_sentence:
print(f" \"{item}\" : with a score of {scores}")
|
def search_name():
word = []
Employee_number = int(input("How many Employee you want to add this company"))
for i in range(Employee_number):
user_inp = input("enter the Company member ")
word.append(user_inp)
print("Your comapny member list is ",word)
# Book = ["aditya","singh"]
while True:
user_sercher = (yield)
if user_sercher in list(word):
print("Your Member in the comany")
else:
print("Another one is tring to enter the company")
if __name__ =="__main__":
no_of_time = 1
while no_of_time:
user= input("enter Start to start the program\nAnd enter s to stop the program ")
if user =="start":
comany_employee =search_name()
next(comany_employee)
user_seching = input("Enter the Member name to clearify the status")
comany_employee.send(user_seching)
elif user=="s":
print("You have sucessfully mange your companty name ")
break
|
from pygame import mixer
from datetime import datetime
from time import time
def Music_player(file, stopper):
mixer.init()
mixer.music.load(file)
mixer.music.play()
while True:
a= input("")
if a == stopper:
mixer.music.stop()
break
def Loggig_the_data(msg):
with open("mylog.txt","a") as f:
f.write(f"{msg} {datetime.now()}\n")
if __name__=="__main__":
water_drinking = time()
eye_exercise = time()
physical_exercise = time()
water_secs =3
eye_second =9
physical_second =5
while True:
# a = input("Enter q to stop the the program ")
# if a != 'q':
if time() - water_drinking > water_secs:
print("It's time to drink the water &Enter drank to stop the alarm")
Music_player("water.mp3", "drank")
Loggig_the_data("water drink at:")
if time() - eye_exercise > eye_second:
print("It's Time to eyes exercise & Enter done the stop the alarm")
Music_player("eyes.mp3", "done")
Loggig_the_data("Eye exercise at")
if time() - physical_exercise - physical_second:
print("It's time to Do physical activity & done to stop the alarm")
Music_player("physical.mp3", "done")
Loggig_the_data("Do exercise at ")
|
# __author : "Flouis"
# date : 2017/12/28
# Python中字典(dict)的概念就等同于Java中Map——键值对
# 字典的键必须是不可变类型
# Python中字符串、整型和元组是不可变类型,列表和字典是可变类型
dictionary={'name':'Flouis','age':23,'company':'Pactera'}
print(type(dictionary))
print(dictionary)
# 对应操作:
# 1.查询元素:
print(dictionary['name'])
# 取出字典中所有的键:
print(list(dictionary.keys()))
# 取出字典中所有的值:
print(list(dictionary.values()))
# 遍历字典:
print(dictionary.items())
for item in dictionary.items():
print(item,end=' ')
print()
# 效率高,建议使用:
for i in dictionary:
print(i,dictionary[i],end='; ')
print()
# 效率低,不建议使用:
for k,v in dictionary.items():
print(k,v,end='; ')
print()
# 2.增加元素:
dictionary['hobby']='Coding & Music & Dota2'
print(dictionary)
# setdefault方法是字典增加元素的一种,如果存在该键则不做添加操作,返回当前键对应的值;如果键不存在,则添加该键值对
x=dictionary.setdefault('University','FAFU')
print(x)
dictionary['friends']=[{'name':'Bear','age':28},{'name':'Robin','age':27}]
print(dictionary)
# 3.修改元素:
dictionary['age']=24
print(dictionary)
dictionary['friends'][0]['age']=29
print(dictionary)
for var in dictionary['friends']:
if var['name'] == 'Bear':
var['company'] = 'Pactera'
print(dictionary)
# 4.删除元素:
dictionary.pop('friends')
print(dictionary)
del dictionary['company']
print(dictionary)
# clear()方法清空字典内容:
dictionary.clear()
print(dictionary)
# 5.合并字典:
dictionary2={1:'123',2:'abc'}
dictionary.update(dictionary2)
print(dictionary)
print(sorted(dictionary.items(),reverse=True))
|
# __author : "Flouis"
# date : 2018/1/9
# Python中只能用关键字set进行集合的声明定义:
s = set('Hello,world.')
print(s) # {'H', ',', 'l', '.', 'r', 'd', 'w', 'e', 'o'}
#s = set(['abc','asdf','abc'])
#print(type(s))
#mylist = list(s)
#print(mylist)
# 可哈希——就是不可变且能被唯一标识的意思。
# set和list可以看成是两个极端——set:无序不可重复,list:有序可重复
# 因为无序所以set就不能像list那样进行切片操作,也不能进行索引相关操作
# 但set可以使用for或迭代器进行遍历操作,也有判断是否某一元素在set中的in操作,当然这些对list都是有的。
print(',' in s)
iterator = iter(s)
#for i in iterator:
# print(i,end=' ')
while True:
try:
print(next(iterator),end=' ')
except StopIteration:
break
print()
s.add('yum')
print(s)
s.clear()
print(s)
|
# __author : "Flouis"
# date : 2018/1/23
if True:
x = 1
print(x)
def f():
print('before')
a = 100
print('after')
# Python的四作用域:built-in > global > enclosing > local
x = int(2.9) # 内置变量
# print(x)
g = 0; # 全局变量
def outer():
o_count = 1 # enclosing (嵌套变量)
print('o_count:',o_count)
def inner():
i_count = 2 # local variable (局部变量)
print('i_count:',i_count)
# print(i_count) # 找不到i_count,因为超出了作用域。
inner()
outer()
# 方法参数不仅可以变量/对象,还可以传方法:
def square(n):
return n * n
def foo(a,b,fct):
return fct(a) + fct(b)
print ( foo(2,3,square) )
|
# Quick sort Algorithm
# Last element as pivot
# To get the correct position of pivot element
def pivot_place(list1,first,last):
pivot = list1[first] # first element as pivot
left = first+1 # indexing left
right = last # indexing right
while True:
while left <= right and list1[left] <= pivot:
left = left + 1
while left <= right and list1[right] >= pivot:
right = right - 1
if left > right:
break
else:
list1[left],list1[right] = list1[right],list1[left]
list1[first],list1[right] = list1[right],list1[first]
return right
def quicksort(list1,first,last):
if first<last:
p = pivot_place(list1,first,last)
quicksort(list1,first,p-1) # dividing into sublist
quicksort(list1,p+1,last) # dividing into sublist
list1 = [56,26,93,17,32,44]
n = len(list1)
quicksort(list1,0,n-1)
print(list1)
|
'''
Write a script that takes three strings from the user and prints them together with their length.
Example Output:
5, hello
5, world
9, greetings
CHALLENGE: Can you edit to script to print only the string with the most characters? You can look
into the topic "Conditionals" to solve this challenge.
'''
user_str1 = str(input("Please enter a word: "))
user_str2 = str(input("Please enter a another word: "))
user_str3 = str(input("Please enter one last word: "))
print(str(len(user_str1)) + ", " + str(user_str1))
print(str(len(user_str2)) + ", " + str(user_str2))
print(str(len(user_str3)) + ", " + str(user_str3))
|
'''
Write a script that creates a dictionary of keys, n and values n*n for numbers 1-10. For example:
result = {1: 1, 2: 4, 3: 9, ...and so on}
'''
my_dict = {}
items = input (f' how many items would you like to add? ')
for i in range (int(items)):
my_dict[i+1] = (i+1)*(i+1)
print(my_dict)
|
# IMPORTS
# for regular expression checking of IP
import re
# CONSTANTS
IP_REGEX = r'^([0-9]{1,3}\.){3}[0-9]{1,3}$'
# CUSTOM ERRORS
class AddressExtractError(Exception):
# Raised when extracting ip and port from address fails
pass
# FUNC:EXTRACT IP PORT
def extract_ip_port(address):
# split address into ip and port
try:
ip, port = address.split(':')
except ValueError:
raise AddressExtractError('address should be in format: <IP>:<Port>')
# validate ip is not empty, is valid IPv4/'localhost'
if not re.match(IP_REGEX, ip) and ip != 'localhost':
raise AddressExtractError('address ip must be a valid IPv4 address')
# validate port exists
if not port:
raise AddressExtractError('address port is required')
# validate port is integer
try:
port = int(port)
except ValueError:
raise AddressExtractError('address port must be a positive integer')
# validate port is in range 1024-65535
if port <= 1023 or port > 65535:
# ports 1-1023 are well-known ports, used by system
# max port is 65535
raise AddressExtractError('address port must be in range 1024-65535')
return ip, port
|
#!/usr/local/bin/python3
#
# arrange_pichus.py : arrange agents on a grid, avoiding conflicts
#
# Submitted by : [PUT YOUR NAME AND USERNAME HERE]
#
# Based on skeleton code in CSCI B551, Spring 2021
#
import sys
# Parse the map from a given filename
def parse_map(filename):
with open(filename, "r") as f:
return [[char for char in line] for line in f.read().rstrip("\n").split("\n")]
# Count total # of pichus on board
def count_pichus(board):
return sum([ row.count('p') for row in board ] )
# Return a string with the board rendered in a human-pichuly format
def printable_board(board):
return "\n".join([ "".join(row) for row in board])
# Add a pichu to the board at the given position, and return a new board (doesn't change original)
def add_pichu(board, row, col):
return board[0:row] + [board[row][0:col] + ['p',] + board[row][col+1:]] + board[row+1:]
# Get list of successors of given board state
def successors(board):
return [ add_pichu(board, r, c) for r in range(0, len(board)) for c in range(0,len(board[0])) if board[r][c] == '.' ]
# check if board is a goal state
def is_goal(board, k):
return count_pichus(board) == k
# Arrange agents on the map
#
# This function MUST take two parameters as input -- the house map and the value k --
# and return a tuple of the form (new_map, success), where:
# - new_map is a new version of the map with k agents,
# - success is True if a solution was found, and False otherwise.
#
def solve(initial_board, k):
fringe = [initial_board]
while len(fringe) > 0:
for s in successors( fringe.pop() ):
if is_goal(s, k):
return(s,True)
fringe.append(s)
return ([],False)
# Main Function
if __name__ == "__main__":
house_map=parse_map(sys.argv[1])
# This is K, the number of agents
k = int(sys.argv[2])
print ("Starting from initial board:\n" + printable_board(house_map) + "\n\nLooking for solution...\n")
(newboard, success) = solve(house_map, k)
print ("Here's what we found:")
print (printable_board(newboard) if success else "None")
|
import sys
# Node class for creating Node object of Graph
# Node class cannot be accessed directly, has to be accesed from the graph
from queue import PriorityQueue
class Node:
def __init__(self, name):
self.id = name
self.latitude = 0
self.longitude = 0
# Dictionaries to create a links between other neighboring nodes
self.miles = {}
self.speedLimit = {}
self.roadName = {}
self.time = {}
def setLatLong(self, latitude, longitude):
self.latitude = latitude
self.longitude = longitude
def addNeighbor(self, neighbor, miles, speedLimit, roadName):
self.miles[neighbor] = miles
self.speedLimit[neighbor] = speedLimit
self.roadName[neighbor] = roadName
self.time[neighbor] = float(self.miles[neighbor]) / 30 if self.speedLimit[neighbor] == '0' or self.speedLimit[
neighbor] == '' else float(self.miles[neighbor]) / float(self.speedLimit[neighbor])
def getNeighbors(self):
return self.miles.keys()
# Graph class to access Node object through the interface
class Graph:
def __init__(self):
self.nodeDict = {} # Dictionary for creating master for all the nodes present and their respective pointers basically for ease of access
# Adding Node to nodeDict
def addNode(self, name):
newNode = Node(name)
self.nodeDict[name] = newNode
return newNode
def setNodeLatLong(self, name, latitude, longitude):
# if name in self.nodeDict:
self.nodeDict[name].setLatLong(latitude, longitude)
# Creating edge between two Nodes
def addEdge(self, frm, to, miles, speedLimit, roadName):
if frm not in self.nodeDict:
self.addNode(frm)
if to not in self.nodeDict:
self.addNode(to)
# add to and fro edge for both the connecting nodes
self.nodeDict[frm].addNeighbor(to, miles, speedLimit, roadName) # give node object as key or just name
self.nodeDict[to].addNeighbor(frm, miles, speedLimit, roadName)
def getNodeLatLong(self, nodeName):
return float(self.nodeDict[nodeName].latitude), float(self.nodeDict[nodeName].longitude)
def getAllNeighbors(self, nodeName):
if nodeName in self.nodeDict:
return self.nodeDict[nodeName].getNeighbors()
return None
# reading Dataset and creating datastructure
def readDatasets(g):
path = "road-segments.txt"
f = open(path)
line = "text"
while line:
line = f.readline().strip()
try:
frm, to, miles, speed, roadName = line.split(" ")
except ValueError: # Reached EOF
continue
g.addEdge(frm, to, miles, speed, roadName)
f.close()
print
"Graph Created for road-segments.txt"
path = "city-gps.txt"
f = open(path)
print
"Feeding GPS Data..."
line = "text"
while line:
line = f.readline().strip()
try:
name, latitude, longitude = line.split(" ")
except ValueError: # Reached EOF
continue
g.setNodeLatLong(name, latitude, longitude)
f.close()
print
"GPS data in memory..."
return g
def printPath(visitedFrom, source, destination, g,
flag): # flag=1 for printing path and 0 for getting total number of previous hops
totalDistance = 0
time = 0
path = [destination]
jump = destination
while True:
nextStop = visitedFrom[jump]
path.append(nextStop)
if nextStop == source:
path = (path[::-1])
if flag == 1:
print
'\nTake the following path for {} to {}\n'.format(source, destination)
for i in range(0, len(path) - 1):
print
"-" * 170
print
'From {:43} via {:24} to {:43} for {:4} miles with maximum speed:{} mph'.format(path[i], g.nodeDict[
path[i]].roadName[path[i + 1]], path[i + 1], g.nodeDict[path[i]].miles[path[i + 1]], g.nodeDict[
path[
i]].speedLimit[
path[i + 1]])
totalDistance = totalDistance + int(g.nodeDict[path[i]].miles[path[i + 1]])
# Take speed limit as 30mph if speed limit not given
time = time + (float(g.nodeDict[path[i]].miles[path[i + 1]]) / 30 if g.nodeDict[path[i]].speedLimit[
path[i + 1]] == "0" or
g.nodeDict[path[i]].speedLimit[
path[
i + 1]] == "" else float(
g.nodeDict[path[i]].miles[path[i + 1]]) / float(g.nodeDict[path[i]].speedLimit[path[i + 1]]))
print
"=" * 170
print
"\nThis total journey of {} miles will take {:4.4f} hours with {} places visited ".format(totalDistance,
time,
len(path) - 1)
print
"=" * 170
print
"\nNOTE: if the maximum speed is 0 or blank then I have selected the speed to be 30 mph\n"
print
"\n{} {:4.4f} {}".format(totalDistance, time, " ".join(map(str, path)))
return
else: # Flag=0 for getting number of hops from source
return len(path) - 1
jump = nextStop
# combined function of dfs bfs and also ids
def bfsdfs(source, destination, g, algo, depth):
visited = {}
fringe = [source]
visitedFrom = {}
while len(fringe) > 0:
if algo == "bfs":
start = fringe.pop(0)
else:
start = fringe.pop()
if depth == 0:
if start == destination:
visitedFrom[destination] = start
return True
return False
visited[start] = 1
for neighbor in g.getAllNeighbors(start):
if neighbor in visited: # do not explore if the node is visited before
continue
visitedFrom[neighbor] = start
if neighbor == destination:
printPath(visitedFrom, source, destination, g, 1)
return True
if depth != None and printPath(visitedFrom, source, neighbor, g, 0) >= depth:
continue
if neighbor not in fringe:
fringe.append(neighbor)
return False
def ids(source, destination, g, algo):
depth = 0
while not (bfsdfs(source, destination, g, "dfs", depth)): # call DFS algorithm with varying depths
depth = depth + 1
# update co ordinates by averaging all Neighbors
def updateCoOrdinates(city, g):
latTotal = lonTotal = 0
neighbors = g.getAllNeighbors(city)
legitimateNeighbors = len(neighbors)
for neighbor in neighbors:
if g.getNodeLatLong(neighbor)[0] != 0.0: # if the neighboring city is not junction
latTotal = latTotal + getLatLong(neighbor, g)[0]
lonTotal = lonTotal + getLatLong(neighbor, g)[1]
else:
legitimateNeighbors = legitimateNeighbors - 1
if legitimateNeighbors == 0:
return -1, -1
x = latTotal / float(legitimateNeighbors)
y = lonTotal / float(legitimateNeighbors)
g.setNodeLatLong(city, x, y)
return x, y
def getLatLong(city, g):
cityX, cityY = g.getNodeLatLong(city)
if (cityX == 0.0):
return updateCoOrdinates(city, g)
if (cityX == -1): # if no coordinates for neighbors as well then set them to 0,0
cityX = cityY = 0.0
return cityX, cityY
from math import radians, cos, sin, asin, sqrt
# Euclidean Distance may be misleading as we travel vertically as the earths shape is spherical hence using Haversine Distance
# reference: http://www.movable-type.co.uk/scripts/latlong.html
def haversineDistance(frm, to, g):
lat1, lon1 = getLatLong(frm, g)
lat2, lon2 = getLatLong(to, g)
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2.0) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2.0) ** 2
c = 2 * asin(sqrt(a))
r = 3956 # Radius of earth in miles 3956 for miles
return c * r
def costFunction(visitedFrom, source, currentState, g, routingOption):
cost = 0
jump = currentState
while True:
if jump == source:
return 0
nextStop = visitedFrom[jump]
if routingOption == 'distance':
cost = cost + float(g.nodeDict[jump].miles[nextStop])
elif routingOption == 'time':
cost = cost + float(g.nodeDict[jump].time[nextStop])
elif routingOption == 'scenic':
cost = cost + (0 if g.nodeDict[jump].speedLimit[nextStop] == "" or float(
g.nodeDict[jump].speedLimit[nextStop]) < 55.0 else float(g.nodeDict[jump].miles[nextStop]))
elif routingOption == 'segments':
cost = cost + 1
if nextStop == source:
return cost
jump = nextStop
def heuristicFunction(currentState, destination, g, routingOption):
if routingOption == 'distance' or routingOption == 'scenic':
return haversineDistance(currentState, destination, g)
elif routingOption == 'time':
return haversineDistance(currentState, destination,
g) / 85.0 # considering 85 is the highest speed limit in USA
elif routingOption == 'segments': # considering 1 as constant heuristic for segments
return haversineDistance(currentState, destination, g) / 4000.0
# References: for algorithm https://en.wikipedia.org/wiki/A*_search_algorithm
def aStar(source, destination, g, routingOption):
pq = PriorityQueue()
# priority is tuple (priority,state name) except for scenic
if routingOption == 'scenic':
pq.put((0, 0,
source)) # use 2 priorities: first is penalty(which is 0 if speed<55 else 1) second is distance for scenic route (penalty,distance,state name)
else:
pq.put((0, source))
visitedFrom = {}
cost = {}
visitedFrom[source] = None
cost[source] = 0
while not pq.empty():
if routingOption == 'scenic': # as there is primary and secondary priority for scenic case
currentState = pq.get()[2]
else:
currentState = pq.get()[1]
if currentState == destination:
printPath(visitedFrom, source, destination, g, 1)
return True
for neighbor in g.getAllNeighbors(currentState):
if routingOption == "distance":
neighborCost = costFunction(visitedFrom, source, currentState, g, routingOption) + float(
g.nodeDict[currentState].miles[neighbor])
elif routingOption == "time":
neighborCost = costFunction(visitedFrom, source, currentState, g, routingOption) + float(
g.nodeDict[currentState].time[neighbor])
elif routingOption == "segments":
neighborCost = costFunction(visitedFrom, source, currentState, g, routingOption) + 1
elif routingOption == "scenic":
neighborCost = costFunction(visitedFrom, source, currentState, g, routingOption) + (
0 if g.nodeDict[currentState].speedLimit[neighbor] == "" or float(
g.nodeDict[currentState].speedLimit[neighbor]) < 55.0 else float(
g.nodeDict[currentState].miles[neighbor]))
else:
print
"proper route option not selected, select the root option among distance, time, segments, scenic"
return False
if neighbor not in cost or neighborCost < cost[neighbor]: # update cost
cost[neighbor] = neighborCost
evaluationVal = neighborCost + heuristicFunction(neighbor, destination, g, routingOption)
if routingOption == 'scenic':
pq.put((neighborCost, evaluationVal, neighbor))
else:
pq.put((evaluationVal, neighbor))
if visitedFrom[currentState] != neighbor: # condition check for avoiding creation of cycles
visitedFrom[neighbor] = currentState
return False
if __name__ == '__main__':
import time
start = time.time()
g = Graph()
g = readDatasets(g) # Convert Dataset to Graph
source = sys.argv[1]
destination = sys.argv[2]
routingOption = sys.argv[3]
algo = sys.argv[4]
if algo == "bfs" or algo == "dfs":
print
"Warning!! {} is a blind search technique and it may not give an optimal solution".format(algo)
path = bfsdfs(source, destination, g, algo, None)
elif algo == "ids":
print
"Warning!! {} is a blind search technique and it may not give an optimal solution".format(algo)
path = ids(source, destination, g, algo)
elif algo == "astar":
path = aStar(source, destination, g, routingOption)
else:
print
"Algorithm not properly selected, select the option among bfs, dfs, ids, astar"
exit(1)
if path == False:
print
"No path found"
print
"\n Total Time Taken:" + str(time.time() - start) + " Seconds"
|
from pythonapi.domain.line import Line
class Paragraph:
def __init__(self, lines: [str]):
self.lines = lines
# self.paragraph = [Line(line, lines) for line in lines]
def __eq__(self, other):
return self.lines == other.lines
def __len__(self):
return len(self.lines)
def __getitem__(self, i):
if isinstance(i, slice):
return Paragraph(self.lines[i.start:i.stop:i.step])
else:
return Line(self.lines[i], self.lines)
def index(self, item: Line) -> int:
return self.lines.index(item.line)
def sort(self):
# i = 0
# line = self.paragraph[i]
paragraph = [Line(line, self.lines) for line in self.lines]
for line in paragraph:
while not line.in_good_position():
line.move_back()
def to_dict(self):
pass
if __name__ == '__main__':
paragraph = ['A:\n', ' E:\n', ' C: Cc\n', ' D: Dd\n', ' B: Bb\n']
Paragraph(paragraph).sort()
# line = Line(' B: Bb\n', paragraph)
# print(line.in_good_position())
|
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
#判断列表是否有环
class Solution:
def hasCycle(self, head):
if head is None or head.next is None:
return False
node1 = head
node2 = head.next
while node1 != node2:
if node2 is None or node2.next is None:
return False
node1 = node1.next
node2 = node2.next.next
return True
# while node2 != None or node2 != None:
# node1 = node1.next
# node2 = node2.next.next
# if node1 == node2:
# return True
# return False
#
#链表中环的入口
class Solution:
def detectCycle(self, head):
if head is None or head.next is None:
return False
node1 = head
node2 = head #快指针
while node2 is None or node2.next is None:
node1 = node1.next
node2 = node2.next.next
if node1 == node2:
node3 = head
while node3 != node1:
node3 =node3.next
node1 = node1.next
return node1 #环的入口
return None
# 快指针与慢指针均从X出发,在Z相遇。此时,慢指针行使距离为a+b,快指针为a+b+n(b+c)。
# 所以2*(a+b)=a+b+n*(b+c),推出
# a=(n-1)*b+n*c=(n-1)(b+c)+c;
|
def mergeSorted(l1, l2):
return mergeSorted_1(l1, l2, [])
def mergeSorted_1(l1, l2, tmp):
if l1 is None or l2 is None:
tmp.extend(l1)
tmp.extend(l2)
return tmp
else:
if l1[0] < l2[0]:
tmp.append(l1[0])
del l1[0]
else:
tmp.append(l2[0])
del l2[0]
return mergeSorted_1(l1, l2, tmp)
def Merge(l1, l2):
ans = []
while l1 and l2:
if l1[0] <= l2[0]:
ans.append(l1.pop(0))
else:
ans.append(l2.pop(0))
ans.extend(l1)
ans.extend(l2)
return ans
print(Merge([1, 3, 5], [2, 4, 6]))
|
def hello():
print('hello world')
hello()
def sey_hello(name):
print(f"Hi {name}")
sey_hello("BOb")
def double(number):
return 2 * number
reesult_1 = double(3)
print(reesult_1)
#
def str_combine(str1, str2):
return f"{str1}{str2}"
result = str_combine('Kazuma', 'Takahashi')
print(result)
|
with open('name.txt', 'r') as f:
my_name = f.read();
def myname(my_name):
return("Hello my name is" + my_name)
with open('hello.txt', 'w') as f:
f.write()
|
# Authors: Dima and Sarah
# Read the data from superheroes.json
import json
import csv
with open('superheroes.json', 'r') as f:
squad = json.load(f)
# Write header to csv file
with open('superheroes.csv', 'w') as f:
writer = csv.writer(f)
#write header
writer.writerow(['name', 'age', 'secretidentity', 'powers', 'squadName', 'homeTown', 'formed', 'secretBase', 'active'])
# Loop over members & write 1 row per member
members = squad['members'] # For this entire dictionary of squad, this accesses the key members
for member in members:
name = member['name']
age = member['age']
secretidentity = member['secretIdentity']
powers = member['powers']
squadName = squad['squadName']
homeTown = squad['homeTown']
formed = squad['formed']
secretBase = squad['secretBase']
active = squad['active']
writer.writerow([name, age, secretidentity, powers, squadName,
homeTown, formed, secretBase, active])
|
# Given an array of integers, return indices of the two
# numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# Given nums = [2, 7, 11, 15], target = 9,
def sumTo(nums, target):
values = {}
for i in range(0, len(nums)):
if values.get(target - nums[i]) != None:
return [values.get(target - nums[i]), i]
values[nums[i]] = i
# O(n)
print(sumTo([1,2,3,4,5], 8))
print(sumTo([1,2,3,4,5], 11))
|
'''
Description: A program that implements functions using list comprehension with map, filter, and reduce.
(I consulted https://www.python-course.eu/lambda.php and the textbook for more examples on list comprehension functions and
how to implement the lambda operator.)
Written By: Anh Mac
Date: 11/12/2018
'''
from functools import reduce
'''
IMPORTANT: The only function below that is allowed to use recursion is map2.
All other functions (including any helper functions you write) must not be recursive. Instead, they should make calls to one or more of map,
filter, and reduce to perform the necessary list traversals.
'''
def inRange(lo, hi, l):
'''
Returns all numbers in the list l that are between lo and hi (inclusive).
>>> inRange(5, 15, [3, 15, 7, 21, 12, 34])
[15, 7, 12]
'''
return list(filter(lambda x: x >= lo and x <= hi, l))
# print(inRange(5, 15, [3, 15, 7, 21, 12, 34]))
def zeroNegatives(l):
'''
Replaces all negative numbers in list l with 0,
leaving all other numbers unchanged.
>>> zeroNegatives([1,3,-4,-6,5,-5])
[1, 3, 0, 0, 5, 0]
'''
return list(map(lambda x: 0 if x<0 else x, l))
# print(zeroNegatives([1,3,-4,-6,5,-5]))
def flatten(l):
'''
Flattens a list of lists into a single list.
>>> flatten([[1,2], [3], [], [4,5,6]])
[1, 2, 3, 4, 5, 6]
'''
def combine(x,y):
return x+y
return list(reduce(combine, l))
# print(flatten([[1,2], [3], [], [4,5,6]]))
def halveEvens(l):
'''
Removes all odd integers from l and divides each even number in half.
The list l is assumed to be a list of integers, and the function returns
a list of integers.
>>> halveEvens([10,21,32,42,55])
[5, 16, 21]
'''
removeOdd = list(filter(lambda x: x%2 == 0, l)) # create list with odd numbers removed
return list(map(lambda x: x//2, removeOdd)) # half all remaining values in filtered list
# print(halveEvens([10,21,32,42,55]))
def map2(f, l1, l2):
'''
Behaves like the map function, but it traverses two lists simultaneously.
Specifically, map(f, [x1,...,xn], [y1,...,yn]) returns [f(x1,y1), ..., f(xn,yn)].
You may assume that l1 and l2 have the same length.
>>> map2(lambda x,y: [x,y], [1,2,3], [4,5,6])
[[1, 4], [2, 5], [3, 6]]
'''
if l1 == []:
return []
if l2 == []:
return []
else:
return [f(l1[0], l2[0])] + map2(f, l1[1:], l2[1:])
# print(map2(lambda x,y: [x,y], [1,2,3], [4,5,6]))
def dotProduct(v1, v2):
'''
Computes the dot product of the vectors v1 and v2, each of which is a list
of numbers. The dot product of [x1,...,xn] and [y1,...,yn] is
x1*y1 + ... + xn*yn.
You may assume that v1 and v2 have the same length.
NOTE: You will want to make use of the map2 function that you defined above.
>>> dotProduct([1,2,3],[4,5,6])
32
'''
def product(x, y):
return map2(lambda x,y: x*y, v1, v2)
return reduce(lambda x,y: x+y, product(v1, v2))
# print(dotProduct([1,2,3],[4,5,6]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.