text stringlengths 37 1.41M |
|---|
#Jamie Christy and Mai Li Goodman
#CS 111 Final Project
#Framework Script
import Tkinter as tk
import animation
import random
import rabbit
import Image
import ImageTk
class GameApp(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root, pady=20,padx=20,width=600, height=600)
root.title('RABBITS RABBITS RABBITS')
self.frame = tk.Frame(root)
self.canvas = tk.Canvas(root)
self.grid()
self.grid_propagate(0)
self.power = 1
self.rabbitCount = 1
self.setUp()
#self.spawn()
def setUp(self):
'''places a score counter and the first rabbit'''
score = tk.Label(self, text='You have '+str(self.rabbitCount)+' rabbits!!!', font='Cambria 20 bold')
score.grid(row=0,sticky=tk.N)
x = random.randint(100,500)
y = random.randint(100,500)
firstRabbit = tk.PhotoImage(file = 'rabbit.gif')
label = tk.Label(self,image = firstRabbit,background="red")
label.grid(row=0,column=0)
#self.canvas.create_image(200,200, image=firstRabbit)
root = tk.Tk()
app = GameApp(root)
app.mainloop()
|
import sqlite3
def create_tables(cursor):
cursor.execute("""CREATE TABLE employees
(id INTEGER PRIMARY KEY, name text, monthly_salary int, yearly_bonus int, position text)""")
def insert(item, cursor):
name = item["name"]
monthly_salary = item["monthly_salary"]
yearly_bonus = item["yearly_bonus"]
position = item["position"]
data_to_insert = (name, monthly_salary, yearly_bonus, position)
query = "INSERT INTO employees VALUES(NULL, ?, ?, ?, ?)"
cursor.execute(query, data_to_insert)
data = [{
# "id": 1,
"name": "Ivan Ivanov",
"monthly_salary": 5000,
"yearly_bonus": 10000,
"position": "Software Developer"
}, {
# "id": 2,
"name": "Rado Rado",
"monthly_salary": 500,
"yearly_bonus": 0,
"position": "Technical Support Intern"
}, {
# "id": 3,
"name": "Ivo Ivo",
"monthly_salary": 10000,
"yearly_bonus": 100000,
"position": "CEO"
}, {
# "id": 4,
"name": "Petar Petrov",
"monthly_salary": 3000,
"yearly_bonus": 1000,
"position": "Marketing Manager"
}, {
# "id": 5,
"name": "Maria Georgieva",
"monthly_salary": 8000,
"yearly_bonus": 10000,
"position": "COO"
}]
conn = sqlite3.connect("company_test.db")
cursor = conn.cursor()
create_tables(cursor)
for item in data:
insert(item, cursor)
conn.commit()
conn.close()
|
import unittest
from solution import count_words
class CountWordsTest(unittest.TestCase):
"""docstring for CountWordsTest"""
def test_count_words(self):
res1 = {'banana': 1, 'pie': 1, 'apple': 2}
res2 = {'python': 3, 'ruby': 1}
self.assertEqual(res1, count_words(["apple", "banana", "apple", "pie"]))
self.assertEqual(res2, count_words(["python", "python", "python", "ruby"]))
if __name__ == '__main__':
unittest.main()
|
def sum_of_divisors(num):
total = 0
for i in range(1, num + 1):
if num % i == 0:
total += i
return total
def main():
print(sum_of_divisors(7))
print(sum_of_divisors(1000))
if __name__ == '__main__':
main()
|
def magic_string(string):
k = len(string) // 2
count_changes = 0
for index, char in enumerate(string):
if index < k and char == "<":
count_changes += 1
elif index >= k and char == ">":
count_changes += 1
return count_changes
def main():
print(magic_string(">><<><"))
print(magic_string(">>>><<<<"))
print(magic_string("<<>>"))
print(magic_string("<><<<>>>>><<>>>>><>><<<>><><><><<><<<<<><<>>><><><"))
if __name__ == '__main__':
main()
|
coins = [100, 50, 20, 10, 5, 2, 1]
def calculate_coins(sum):
int_sum = sum * 100
num_coins = {}
for coin in coins:
count = 0
while int_sum >= coin:
int_sum -= coin
count += 1
num_coins[coin] = count
return num_coins
def main():
print(calculate_coins(0.53))
print(calculate_coins(8.94))
if __name__ == '__main__':
main()
|
def list_to_number(numList):
num = 0
exp = 0
for item in numList[::-1]:
num += item * (10 ** exp)
exp += 1
return num
def main():
print(list_to_number([1, 2, 3]))
print(list_to_number([9, 9, 9, 9, 9]))
print(list_to_number([1, 2, 3, 0, 2, 3]))
if __name__ == '__main__':
main()
|
def is_an_bn(word):
n = len(word)
if n % 2 != 0:
return False
n = n // 2
check = 'a' * n + 'b' * n
if word == check:
return True
return False
def main():
print(is_an_bn(""))
print(is_an_bn("rado"))
print(is_an_bn("aaabb"))
print(is_an_bn("aaabbb"))
print(is_an_bn("aabbaabb"))
print(is_an_bn("bbbaaa"))
print(is_an_bn("aaaaabbbbb"))
if __name__ == '__main__':
main()
|
# output the square of a number as value with the number as key in a dictionary
myDict = {}
x = int(raw_input())
for a in range(1, x + 1):
myDict[a] = a * a
print myDict
|
from Piece import *
import os
class Player(object):
def __init__(self,name,color):
self.name = name
self.color = color
self.listOfPieces = [] #a list containing all the pieces the player has
self.pieceKeys = {} # a dict which returns the piece based on it's nom
self.listOfNoms = ["k","q","r2","r1","k1","b1","k2"
,"b2","p1","p2","p3","p4","p5","p6","p7","p8"] #list of the noms of the pieces
self.addition1 = 0
self.addition2 = 0
self.board = None
self.isBad = True
self.init = "w"
self.opponent = None
self.king = self.queen = self.rook1 = self.rook2 = self.bishop1 = self.bishop2 = self.knight1 = self.knight2 = self.pawn1 = self.pawn2 = self.pawn3 = self.pawn4 = self.pawn5 = self.pawn6 = self.pawn7 = self.pawn8 = None
self.build_deck()
self.assignPieceByName()
#Adding items to player list as objects...
def build_deck(self):
if(self.color == "black"):
self.addition1 = 7
self.addition2 = 5
self.init = "b"
#Initizaling the pieces for each player
self.king = Piece(self.color,"king",0+self.addition1,4,"k ",self,self.init+"k ")#0
self.queen = Piece(self.color,"queen",0+self.addition1,3,"q ",self,self.init+"q ")#1
self.rook2 = Piece(self.color,"rook",0+self.addition1,7,"r2",self,self.init+"r2")#3
self.rook1 = Piece(self.color,"rook",0+self.addition1,0,"r1",self,self.init+"r1")#2
self.knight1 = Piece(self.color,"knight",0+self.addition1,1,"k1",self,self.init+"k1")#4
self.bishop1 = Piece(self.color,"bishop",0+self.addition1,2,"b1",self,self.init+"b1")#6
self.knight2 = Piece(self.color,"knight",0+self.addition1,6,"k2",self,self.init+"k2")#5
self.bishop2 = Piece(self.color,"bishop",0+self.addition1,5,"b2",self,self.init+"b2")#7
self.pawn1 = Piece(self.color,"pawn",1+self.addition2,0,"p1",self,self.init+"p1")#8
self.pawn2 = Piece(self.color,"pawn",1+self.addition2,1,"p2",self,self.init+"p2")#9
self.pawn3 = Piece(self.color,"pawn",1+self.addition2,2,"p3",self,self.init+"p3")#10
self.pawn4 = Piece(self.color,"pawn",1+self.addition2,3,"p4",self,self.init+"p4")#11
self.pawn5 = Piece(self.color,"pawn",1+self.addition2,4,"p5",self,self.init+"p5")#12
self.pawn6 = Piece(self.color,"pawn",1+self.addition2,5,"p6",self,self.init+"p6")#13
self.pawn7 = Piece(self.color,"pawn",1+self.addition2,6,"p7",self,self.init+"p7")#14
self.pawn8 = Piece(self.color,"pawn",1+self.addition2,7,"p8",self,self.init+"p8")#15
#Adding items to the list of each player
self.listOfPieces.extend((self.king,self.queen,self.rook2
,self.rook1,self.knight1,self.bishop1
,self.knight2,self.bishop2
,self.pawn1,self.pawn2,self.pawn3
,self.pawn4,self.pawn5,self.pawn6
,self.pawn7,self.pawn8))
def assignPieceByName(self):
i = 0
for piece in self.listOfNoms:
self.pieceKeys[piece] = self.listOfPieces[i]
i = i+1
def getmyDict(self):
return self.pieceKeys
def getPlayerName(self):
return self.name
def getPlayerColor(self):
return self.color
def getPieceIndex(self,pieceName):
return self.item_keys[pieceName]
def show_list(self):
for i in range(0,len(self.listOfPieces)):
self.listOfPieces[i].showInfo()
def movePiece(self,piece):
selectedPiece = self.pieceKeys[piece]
#ph = PieceMovesHelper(self.board)
#availableMoves = ph.getPieceMoves(selectedPiece,self)
#print(availableMoves)
row = int(input("enter Row\n"))-1
col = self.board.getColIndex(input("enter Col\n").upper())
celltobeChecked = self.board.listOfCells[row][col]
if(not celltobeChecked.get_piece() == None):
if(self.getPlayerName() == celltobeChecked.get_piece().getPieceOwner().getPlayerName()):
print("Can't eat from your self")
self.movePiece(piece)
else:
self.opponent.listOfPieces.remove(celltobeChecked.get_piece())
self.board.listOfCells[selectedPiece.getRow()][selectedPiece.getCol()].remove_piece()
selectedPiece.setRow(row)
selectedPiece.setCol(col)
self.board.addItemsToCells()
else:
self.board.listOfCells[selectedPiece.getRow()][selectedPiece.getCol()].remove_piece()
selectedPiece.setRow(row)
selectedPiece.setCol(col)
self.board.addItemsToCells()
def setPlayingBoard(self,board):
self.board = board
def setOpponent(self,opponent):
self.opponent = opponent
|
# string review
mystring = 'testing hello there'
print(mystring + ' ' + mystring)
# index - get everything there and after
print(mystring[2:])
# index - get everything up to but not including index 3
print(mystring[:3])
# index - get everything up to but not including index 3
print(mystring[1:3])
# skipping every other
print(mystring[::2])
#upper case
print(mystring.upper())
#lower case
print(mystring.lower())
print(mystring.split())
|
def pca(X, ncomp):
"""
Principal component analysis.
Parameters
----------
X : array_like
Samples-by-dimensions array.
ncomp : int
Number of components.
Returns
-------
components : ndarray
First components ordered by explained variance.
explained_variance : ndarray
Explained variance.
explained_variance_ratio : ndarray
Percentage of variance explained.
Examples
--------
.. doctest::
>>> from numpy import round
>>> from numpy.random import RandomState
>>> from limix.stats import pca
>>>
>>> X = RandomState(1).randn(4, 5)
>>> r = pca(X, ncomp=2)
>>> r['components']
array([[-0.75015369, 0.58346541, -0.07973564, 0.19565682, -0.22846925],
[ 0.48842769, 0.72267548, 0.01968344, -0.46161623, -0.16031708]])
>>> r['explained_variance'] # doctest: +FLOAT_CMP
array([6.44655993, 0.51454938])
>>> r['explained_variance_ratio'] # doctest: +FLOAT_CMP
array([0.92049553, 0.07347181])
"""
from sklearn.decomposition import PCA
from numpy import asarray
X = asarray(X, float)
pca = PCA(n_components=ncomp)
pca.fit(X)
return dict(
components=pca.components_,
explained_variance=pca.explained_variance_,
explained_variance_ratio=pca.explained_variance_ratio_,
)
|
"""
Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
In this example, assume nodes with the same value are the exact same node objects.
Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space.
"""
import copy
class LinkedList:
def __init__(self):
self.head = None
class Node:
def __init__(self, value = None):
self.value = value
self.next = None
def getIntersectNode(A, B):
new_A = copy.copy(A)
new_B = copy.copy(B)
while new_B.head != None:
new_A = copy.copy(A)
while new_A.head != None:
if new_A.head.value == new_B.head.value:
return new_A.head.value
else:
new_A.head = new_A.head.next
new_B.head = new_B.head.next
return "No intersection found"
if __name__=="__main__":
node1_a = Node(3)
node2_a = Node(7)
node3_a = Node(8)
node4_a = Node(10)
node1_a.next = node2_a
node2_a.next = node3_a
node3_a.next = node4_a
A = LinkedList()
A.head = node1_a
node1_b = Node(99)
node2_b = Node(1)
node3_b = Node(8)
node4_b = Node(10)
node1_b.next = node2_b
node2_b.next = node3_b
node3_b.next = node4_b
B = LinkedList()
B.head = node1_b
print (getIntersectNode(A, B))
|
from __future__ import print_function
def main():
bilanganPertama = 5
bilanganKedua = 4
listSaya = [1,2,3,4,5]
if(bilanganPertama == bilanganKedua):
print('Bilangan Sama ')
if(bilanganPertama >= bilanganKedua):
print('Bilangan pertama lebih besar ')
if(bilanganPertama <= bilanganKedua):
print('Bilangan pertama lebih Kecil ')
if(bilanganPertama != bilanganKedua):
print('Bilangan pertama dan Kedua berbeda ')
if(bilanganPertama in listSaya):
print('Bilangan pertama ada pada list ')
if __name__ == '__main__':
main() |
from __future__ import print_function
def main():
# for iterasi in range(5):
# print(iterasi)
threshodl = True
iterasiWhile = 0
a = 0
# while(iterasiWhile<5):
# print('Ganteng')
# iterasiWhile +=1
while(threshodl):
print('Ganteng')
if(a == 4):
threshodl = False
a+=1
if __name__ == '__main__':
main() |
from __future__ import print_function
def main():
bilanganPertama = int(input('Bilangan Pertama : '))
bilanganKedua = int(input('Bilangan Kedua : '))
hasilTambah = bilanganPertama + bilanganKedua
hasilKurang = bilanganPertama - bilanganKedua
hasilKali = bilanganPertama * bilanganKedua
hasilBagi = bilanganPertama / bilanganKedua
hasilPangkat = bilanganPertama ** bilanganKedua
hasilModulus = bilanganPertama % bilanganKedua
print('Hasil Tambah : %d'%hasilTambah)
print('Hasil Tambah : %d'%hasilKurang)
print('Hasil Tambah : %d'%hasilKali)
print('Hasil Tambah : %d'%hasilBagi)
print('Hasil Tambah : %d'%hasilPangkat)
print('Hasil Tambah : %d'%hasilModulus)
if __name__ == '__main__':
main() |
"""
created by Nagaj at 02/05/2021
"""
from album import Album
from song import Song
class Artist:
def __init__(self, name):
self.name = name
self.songs = []
self.albums = []
self.items = []
def __repr__(self):
return f"Artist-<{self.name}>"
def __contains__(self, item):
return item in self.songs
def __getitem__(self, item):
return self.albums[item]
def add_album(self, album: Album):
self.albums.append(album.to_json())
def add_song(self, song: Song):
self.songs.append(song.to_json())
def add_song_to_album(self, song: Song, album: Album):
album.songs.append(song.to_json())
alb = album.to_json()
if alb not in self.items:
self.items.append(alb)
|
import simplegui
import random
range_max = int(100)
guess_max = int(7)
# helper function to start and restart the game
def new_game():
global secret_number
global remain_guess
global range_max
global guess_max
secret_number = random.randint(0,range_max)
remain_guess = guess_max
print 'New game with range 1-' + str(range_max)
print
# define event handlers for control panel
def range100():
global range_max
global guess_max
range_max = int(100)
guess_max = int(7)
new_game()
def range1000():
global range_max
global guess_max
range_max = int(1000)
guess_max = int(10)
new_game()
def input_guess(guess):
guess_num = int(guess)
print "Guess was: " + guess
global remain_guess
remain_guess = remain_guess - 1
if remain_guess > 0:
if guess_num < secret_number:
print 'Higher'
print str(remain_guess) + " guesses remain"
print
elif guess_num > secret_number:
print 'Lower'
print str(remain_guess) + " guesses remain"
print
else:
print 'Correct'
new_game()
elif remain_guess == 0:
if guess_num < secret_number:
print 'Higher'
print "Sorry, you've run out of guesses!"
print
new_game()
elif guess_num > secret_number:
print 'Lower'
print "Sorry, you've run out of guesses!"
print
new_game()
else:
print 'Correct'
new_game()
# create frame
frame = simplegui.create_frame("Guess the number", 200, 200)
# register event handlers for control elements and start frame
frame.add_button("Get range 0-100", range100, 200)
frame.add_button("Get range 0-1000", range1000, 200)
frame.add_input("Enter guess!", input_guess, 200)
frame.start()
# call new_game
new_game()
|
def triangular_sum(n):
"""
Example of a recursive function that computes
a triangular sum
"""
if n == 0:
return 0
else:
return n + triangular_sum(n-1)
#print triangular_sum(3)
def number_of_threes(n, count):
"""
Takes a non-negative integer num and compute the
number of threes in its decimal form
Returns an integer
"""
str_n = str(n)
if len(str_n) == 1 and str_n == "3":
count += 1
return count
elif len(str_n) == 1 and str_n != "3":
return count
elif str_n[0] == "3":
return number_of_threes(str_n[1:], count + 1)
elif str_n[0] != "3":
return number_of_threes(str_n[1:], count)
#print number_of_threes(34545633334, 0)
def number_of_threes1(string):
for char in string:
res = n3(string[1:])
if char == "3":
res += 1
return res
return 0
def number_of_threes2(num):
"""
Takes a non-negative integer num and computes the
number of threes in its decimal form
Returns an integer
"""
if num == 0:
return 0
else:
unit_digit = num % 10
threes_in_rest = number_of_threes2(num // 10)
if unit_digit == 3:
return threes_in_rest + 1
else:
return threes_in_rest
#print number_of_threes(323)
def is_member(mylist, elem):
"""
Take list my_list and determines whether elem is in my_list
Returns True or False
"""
if mylist == []:
return False
else:
if mylist[0] == elem:
return True
else:
return is_member(mylist[1:], elem)
#print is_member(['c', 'b', 't'], 'a')
def remove_x(my_string):
"""
Takes a string my_string and removes all instances of
the character 'x' from the string
Returns a string
"""
if my_string == "":
return ""
else:
first_chr = my_string[0]
rest_removed = remove_x(my_string[1:])
if first_chr != 'x':
return first_chr + rest_removed
else:
return rest_removed
#print remove_x("catxxdogx")
def insert_x(my_string):
"""
Takes a string my_string and add the character 'x'
between all pairs of adjacent characters in my_string
Returns a string
"""
if my_string == "":
return ""
else:
if len(my_string) == 1:
first_chr = my_string[0]
else:
first_chr = my_string[0] + 'x'
rest = insert_x(my_string[1:])
return first_chr + rest
#print insert_x("cato")
def insert_x2(my_string):
"""
Takes a string my_string and add the character 'x'
between all pairs of adjacent characters in my_string
Returns a string
"""
if len(my_string) <= 1:
return my_string
else:
first_character = my_string[0]
rest_inserted = insert_x(my_string[1 :])
return first_character + 'x' + rest_inserted
#print insert_x("cato")
def list_reverse(my_list):
"""
Takes a list my_list and returns new list
whose elements are in reverse order
Returns a list
"""
if my_list == []:
return []
else:
elem = my_list[0]
rest = list_reverse(my_list[1:])
return rest + [elem]
#print list_reverse([1,2,3,5,4])
def gcd(num1, num2):
"""
Euclid's Algorithm: handling of num1 = 0 or num2 = 0 is the key
Takes non-negative integers num1 and num2 and
returns the greatest common divisor of these numbers
"""
if num2 > num1:
return gcd(num2, num1)
else:
if num2 == 0:
return num1
else:
return gcd(num1 - num2, num2)
#print gcd(3, 0)
def slice(my_list, first, last):
if my_list == []:
return []
else:
elem_idx = len(my_list) - 1
elem = my_list.pop()
rest = slice(my_list, first, last)
if first <= elem_idx <= last:
return rest + [elem]
else:
return rest
#print slice(['a', 'b', 'c'], 0, 1)
def slice2(my_list, first, last):
"""
Takes a list my_list and non-negative integer indices
satisfying 0 <= first <= last <= len(my_list)
Returns the slice my_list[first : last]
"""
if my_list == []:
return []
else:
first_elem = my_list.pop(0)
if first > 0:
rest_sliced = slice(my_list, first - 1, last - 1)
return rest_sliced
elif last > 0:
rest_sliced = slice(my_list, 0, last - 1)
return [first_elem] + rest_sliced
else:
return []
print slice2([1, 2, 3], 1, 2)
|
"""
# Mini-project #3 - Monte Carlo Tic-Tac-Toe Player
# as a Coursera's "Principles of computing"
# course assignment.
# Author: Sergey Korytnik
# Date: 12th August 2016
#
"""
import random
import poc_ttt_gui
import poc_ttt_provided as provided
import time
# Constants for Monte Carlo simulator
# You may change the values of these constants as desired, but
# do not change their names.
NTRIALS = 300 # Number of trials to run
SCORE_CURRENT = 1.0 # Score for squares played by the current player
SCORE_OTHER = 1.0 # Score for squares played by the other player
# Add your functions here.
def mc_trial_impl(board, player, empty_squares):
"""
This function takes a current board and the next player to move.
The function plays a game starting with the given player
by making random moves, alternating between players.
The function returns when the game is over.
The modified board contains the state of the game,
The function returns state of the game (PALYERX,PLAYERO or DRAW).
"""
dim = board.get_dim()
num_occupied = dim * dim - len(empty_squares)
lower_check_limit = dim + dim - 1
random.shuffle(empty_squares)
for (row,col) in empty_squares:
board.move(row, col, player)
num_occupied += 1
if num_occupied >= lower_check_limit:
game_status = board.check_win()
if game_status != None:
return game_status
player = provided.switch_player(player)
return provided.DRAW
def mc_trial(board, player):
"""
This fucnction just calls mc_trial_impl and ignores its return value.
The function must make the machine grader happy.
"""
mc_trial_impl(board, player, board.get_empty_squares())
def mc_update_scores_impl(scores, board, player, winner):
"""
This function takes a grid of scores (a list of lists)
with the same dimensions as the Tic-Tac-Toe board,
a board from a completed game, which player
the machine player is and winner of the current game.
The function scores the completed board and updates
the scores grid. As the function updates the scores
grid directly, it does not return anything.
"""
if player == provided.PLAYERX:
player_x_score = SCORE_CURRENT
player_o_score = -SCORE_OTHER
else:
player_o_score = SCORE_CURRENT
player_x_score = -SCORE_OTHER
if player != winner:
player_o_score = - player_o_score
player_x_score = - player_x_score
dim = board.get_dim()
for (row_index, row) in enumerate(scores):
for col_index in xrange(dim):
square = board.square(row_index, col_index)
if square == provided.PLAYERX:
row[col_index] += player_x_score
elif square == provided.PLAYERO:
row[col_index] += player_o_score
def mc_update_scores(scores, board, player):
"""
This function takes a grid of scores (a list of lists)
with the same dimensions as the Tic-Tac-Toe board,
a board from a completed game, and which player
the machine player is. The function scores the completed
board and updates the scores grid. As the function
updates the scores grid directly,
it does not return anything.
"""
winner = board.check_win()
if winner != provided.DRAW:
mc_update_scores_impl(scores, board, player, winner)
def get_max_score(scores, empty_squares):
"""
finds a maximum value (score) in a grid of scores for
elements of the grid listed in empty_squares
(list of tuples (row,col))
"""
return max( map(
lambda rowcol: scores[rowcol[0]][rowcol[1]],
empty_squares)
)
def get_best_move_impl(scores, empty_squares):
"""
This function takes a grid of scores and list
of tuples (row col) referencing elements in the grid.
The function finds all of the elements with the
maximum score and randomly returns one of them as
a (row, column) tuple. It is an error to call this
function with a board that has no empty squares
(there is no possible next move), so your function
may do whatever it wants in that case.
"""
max_score = get_max_score(scores, empty_squares)
max_score_candidates = filter(
lambda rowcol: scores[rowcol[0]][rowcol[1]] == max_score,
empty_squares)
return random.choice(max_score_candidates)
def get_best_move(board, scores):
"""
This function takes a current board and a grid of scores.
The function finds all of the empty squares with the
maximum score and randomly returns one of them as
a (row, column) tuple. It is an error to call this
function with a board that has no empty squares
(there is no possible next move), so your function
may do whatever it wants in that case.
"""
return get_best_move_impl(
scores,
board.get_empty_squares()
)
def mc_move(board, player, trials):
"""
This function takes a current board,
which player the machine player is,
and the number of trials to run.
The function uses the Monte Carlo
simulation described above to return
a move for the machine player in the
form of a (row, column) tuple.
"""
empty_squares = board.get_empty_squares()
dim = board.get_dim()
scores = [ [0] * dim for dummy_index in range(dim) ]
for dummy_index in xrange(trials):
test_board = board.clone()
status = mc_trial_impl(
test_board,
player,
empty_squares
)
if status != provided.DRAW:
mc_update_scores_impl(
scores,
test_board,
player,
status
)
return get_best_move_impl(scores, empty_squares)
def performance_test():
"""
the performance test borrowed from
http://www.codeskulptor.org/#user41_rAX7Nukse9WzOOV.py
"""
time.time()
start = time.time()
provided.play_game(mc_move, NTRIALS, False)
print str(provided.play_game)+": \t" + str( (time.time() - start) )
# Test game with the console or the GUI. Uncomment whichever
# you prefer. Both should be commented out when you submit
# for testing to save time.
#provided.play_game(mc_move, NTRIALS, False)
#poc_ttt_gui.run_gui(4, provided.PLAYERX, mc_move, NTRIALS, False)
performance_test() |
# -*- coding: utf-8 -*-
import urllib
import urllib2
URL_IP = 'http://httpbin.org/ip'
URL_GET = 'http://httpbin.org/get'
def use_simple_urllib2():
response = urllib2.urlopen(URL_IP)
print '>>>>Response Headers:'
print response.info()
print ''.join([line for line in response.readlines()])
def use_params_urllib2():
# 构建请求参数
params = urllib.urlencode({'param1': 'hello', 'param2': 'world'})
print 'Resquest Params:'
print params
# 发送请求
response = urllib2.urlopen('?'.join([URL_GET, '%s']) % params)
# 处理响应
print '>>>>Response Headers:'
print response.info()
print '>>>>Status Code:'
print response.getcode()
print '>>>>Response Body:'
print ''.join([line for line in response.readlines()])
if __name__ == '__main__':
print '>>>>Use simple urllib2:'
use_simple_urllib2()
print
print '>>>>Use params urllib2:'
use_params_urllib2() |
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if not nums1 or not nums2:
return []
nums1.sort()
nums2.sort()
res = []
i = j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
res.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return res
# T:O(mlogm + nlogn)
"""
Follow up:
Q. What if the given array is already sorted? How would you optimize your algorithm?
If both arrays are sorted, I would use two pointers to iterate, which somehow resembles the merge process in merge sort.
Q. What if nums1's size is small compared to nums2's size? Which algorithm is better?
Suppose lengths of two arrays are N and M, the time complexity of my solution is O(N+M) and the space complexity if O(N) considering the hash. So it's better to use the smaller array to construct the counter hash.
Well, as we are calculating the intersection of two arrays, the order of array doesn't matter. We are totally free to swap to arrays.
Q. What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
Divide and conquer. Repeat the process frequently: Slice nums2 to fit into memory, process (calculate intersections), and write partial results to memory.
"""
|
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# input / output type?
# time / space req
# duplicate?
# corner case?
if not nums:
return -1
# not rotate
if nums[-1] > nums[0]:
return nums[0]
left, right = 0, len(nums) - 1
while left + 1 < right:
mid = left + (right - left) // 2
if nums[mid] > nums[-1]:
left = mid
else:
right = mid
# print left
# print right
return nums[left] if nums[left] < nums[right] else nums[right]
test = Solution()
nums = [3,4,5,1,2]
print(test.findMin(nums))
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
queue = [root]
res = []
while queue:
res.append(sum([node.val for node in queue]) * 1.0 / len(queue))
temp = []
for node in queue:
if node.left:
temp.append(node.left)
if node.right:
temp.append(node.right)
queue = temp
return res
# T:O(n) - # of nodes in the tree
# S: O(m) - max num of nodes in one level
|
# Array - count() and extend()
import array
arr1 = array.array('i', [1, 2, 3, 1, 2, 5])
arr2 = array.array('i', [1, 2, 3])
print("The occurrences of 1 in array is: ", end='')
print(arr1.count(1))
arr1.extend(arr2)
print("Modified array: ", end='')
for i in range(0, len(arr1)):
print(arr1[i], end=' ')
|
# Type conversion using tuple(), set(), list()
s = 'Geeks'
c = tuple(s)
print("After converting string to tuple: ", end='')
print(c)
c = set(s)
print("After converting string to set: ", end='')
print(c)
c = list(s)
print("After converting string to list: ", end='')
print(c)
|
# Demo of conditional statement
num = int(input("Enter a number: "))
if(num > 15):
print("Good number!")
else:
print("Bad number!")
|
# Adding elements to a set
set1 = set()
print("Initial blank set: ")
print(set1)
set1.add(8)
set1.add(9)
set1.add(11)
print("Set after addition of three elements: ")
print(set1)
for i in range(1, 6):
set1.add(i)
print("Set after the addition of elements in range 1-6: ")
print(set1)
set1.add((6, 7))
print("Set after the addition of a tuple: ")
print(set1)
set1.update([10, 11])
print("Set after the addition of elements using update: ")
print(set1)
# Addition of single element - add
# Addition of multiple elements - update
|
# Concatenation of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Geeks', 'for', 'geeks')
Tuple3 = Tuple1 + Tuple2
print("Tuple1: ")
print(Tuple1)
print("Tuple2: ")
print(Tuple2)
print("Tuples after concatenation: ")
print(Tuple3)
|
# Unpacking of dictionary items using **
def fun(a, b, c):
print(a, b, c)
d = {'a':2, 'b':4, 'c':10}
fun(**d)
|
# Use of absolute function in Math library
import math
def main():
num = float(input("Enter a decimal number: "))
num = math.fabs(num)
print(num)
if __name__ == '__main__':
main() |
# coding=utf-8
import sys
import string
vowels = 'aeiouyåäöAEIOUYÅÄÖ'.decode('utf-8')
while True:
word = raw_input("Please type in a word: ")
if word == '--quit':
sys.exit()
word = word.decode('utf-8')
modified_word = []
for c in word:
if c not in vowels and c not in string.punctuation and c != ' ':
modified_word.append(c + 'o' + c.lower())
else:
modified_word.append(c)
modified_word = ''.join(modified_word)
print modified_word
|
def leaderboard_sort(leaderboard, changes):
for move in changes:
movement = move.split()
indx = leaderboard.index(movement[0])
if '+' in movement[1]:
dist = int(movement[1].strip('+'))
leaderboard.insert(indx-dist, leaderboard.pop(indx))
else:
dist = int(movement[1].strip('-'))
leaderboard.insert(indx + dist, leaderboard.pop(indx))
return leaderboard
print(leaderboard_sort(['John', 'Brian', 'Jim', 'Dave', 'Fred'], ['Dave +1', 'Fred +4', 'Brian -1'])) |
# Best Solution:
# def anagrams(word, words): return [item for item in words if sorted(item)==sorted(word)]
def anagrams(word, words):
word_dict, output = {}, []
for letter in word:
try:
word_dict[letter] += 1
except KeyError:
word_dict[letter] = 1
for set in words:
ref_dict = {}
if len(set) != len(word):
continue
else:
for letter in set:
try:
ref_dict[letter] += 1
except KeyError:
ref_dict[letter] = 1
if ref_dict == word_dict:
output.append(set)
return output
print(anagrams('aabb', ['bba'])) |
def is_valid_walk(walk):
if len(walk) != 10:
return False
location = [0,0]
for direction in walk:
if direction == 'e':
location[0] += 1
elif direction == 'w':
location[0] -= 1
elif direction == 'n':
location[1] += 1
elif direction == 's':
location[1] -= 1
if location == [0,0]:
return True
else:
return False
print(is_valid_walk(['e']*10))
|
def likes(arry):
no_likes = len(arry)
if no_likes == 0:
return 'no one likes this'
elif no_likes == 1:
return f'{arry[0]} likes this'
elif no_likes ==2:
return f'{arry[0]} and {arry[1]} like this'
elif no_likes == 3:
return f'{arry[0]},{arry[1]} and {arry[2]} like this'
else:
res = no_likes - 2
return f'{arry[0]}, {arry[1]} and {res} others like this'
print(likes([]))
print(likes(['John']))
print(likes(['John', 'Mark']))
print(likes(['John', 'Mark', 'Jacob', 'Mary'])) |
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
pass
class Cat(Animal):
pass
dog=Dog()
dog.run()
cat=Cat()
cat.run()
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
print(isinstance(dog, Cat))
def run_twice(animal):
animal.run()
animal.run()
run_twice(Animal())
class Tortoise(Animal):
def run(self):
print('Tortoise is running slowly...')
run_twice(Tortoise())
print(type(dog))
print(isinstance([1, 2, 3], tuple))
|
# coding: utf-8
__author__ = 'Leon.Nie'
# 返回用户输入的密码的
import hashlib
# 用于存储用户名密码
db = {}
def get_md5(str):
md5 = hashlib.md5()
md5.update(str.encode('utf-8'))
return md5.hexdigest()
def register(user, pw):
if(user in db)==False:
db[user] = get_md5(pw + user + 'the_Salt')
print('User %s has been registered successfully' % user)
else:
print('User %s has already been registered ' % user)
def login(user, pw):
if (user in db):
if get_md5(pw + user + 'the_Salt') == db[user]:
print('User %s login successfully' % user)
else:
print('Password incorrect!')
else:
print('User %s doesn\'t exist' % user)
if __name__ == '__main__':
while True:
n = input('Choose your action, 1 or 2:\n1. Login\n2. Register\n')
if n == '1':
username = input('Please enter your username: ')
password = input('Please enter your password: ')
login(username, password)
elif n == '2':
username = input('Please enter your username: ')
password = input('Please enter your password: ')
register(username, password)
else:
pass |
from decorator_test import my_decorator
import time
from time import sleep
@my_decorator
def just_some_function():
print("Wheee!")
just_some_function()
print("___________________")
def timing_function(some_function):
"""
Outputs the time a function takes
to execute.
"""
def wrapper():
t1 = time.time()
some_function()
t2 = time.time()
return "Time it took to run the function:" + str((t2 - t1)) + "\n"
return wrapper
@timing_function
def my_function():
num_list = []
for x in range(0, 10000):
num_list.append(x)
print("\nSum of all the numbers:" + str(sum(num_list)))
print(my_function())
print("__________")
def sleep_decorator(function):
"""
Limits how fast the function is
called.
"""
def wrapper(*args, **kwargs):
sleep(2)
return function(*args, **kwargs) # 可变参数与关键字参数
return wrapper
@sleep_decorator
def print_number(num):
return num
print(print_number(222))
for x in range(1, 6):
print(print_number(x))
|
L = ['a', 'b', 'c']
for i, value in enumerate(L):
# enumerate函数可以把一个list变成索引-元素对
print(i, value)
|
def set_adj_list(vertex_list,edge_list):
for i in vertex_list:
for j in vertex_list:
if (i,j) in edge_list:
adjacency_list[i].append(j)
def print_adj_list(adjacency_list):
for i in range(len(adjacency_list)):
print i,'->',adjacency_list[i]
def bfs(adjacency_list,node_start):
node_queue.append(node_start)
while len(node_queue)!=0:
node_start=node_queue.pop()
for neighbour in adjacency_list[node_start]:
if neighbour not in node_visited:
print neighbour,
node_visited.append(neighbour)
node_queue.append(neighbour)
print
vertex_list=[0,1,2,3,4]
edge_list=[(0,1),(0,2),(1,2),(1,3),(2,3),(3,4)]
adjacency_list=[[],[],[],[],[]]
set_adj_list(vertex_list,edge_list)
print_adj_list(adjacency_list)
node_start=0
node_queue=[]
node_visited=[]
bfs(adjacency_list,node_start)
|
#!/usr/bin/python2.7
# coding:utf-8
# Aurélien REY
# Groupe 3
# Théorie des graphes
# TP1 - Exercice 4
import random as rand
def Chaine(G, s, t) :
d = list()
current = s
while current != t :
d.append(current)
current = G[current][rand.randint(0, len(G[current]) - 1)]
d.append(t)
return d
g = {}
g['A'] = ['B', 'C', 'E']
g['B'] = ['A', 'D', 'F']
g['C'] = ['A', 'G']
g['D'] = ['B']
g['E'] = ['A', 'F']
g['F'] = ['B', 'E']
g['G'] = ['C']
result = Chaine(g, 'E', 'C')
s = ""
for k in result :
s += "{} > ".format(k)
s = s[:len(s) - 3]
print "La chaine {} est une chaine permettant d'aller du point E au point C".format(s)
input() |
some_text = '''hello\n
[something between square\n
and still some text\n
brackets, to see if it is working]\n
last time'''
def dropuntil(pred, text):
"""Drop until condition met. Last item dropped."""
if pred(text.pop(0)):
return dropuntil(pred, text)
return text
def parse_text(text, accumulator=[]):
if not text:
return accumulator
if '[' in text[0]:
text.pop(0)
text = list(dropuntil(lambda line: not ']' in line, text))
accumulator.append(text[0])
return parse_text(text[1:], accumulator)
print(parse_text(some_text.splitlines()))
|
#列表或者字典 当做全局变量 可以不用global 直接用
nums = [11,22,33]
infor = {"name":"laowang"}
def test():
#for num in nums:
# print(num)
nums.append(44)
infor["age"]=18
#infor["name"] = "laoli"
def test2():
print(nums)
print(infor)
test()
test2()
|
'''
class Dog:
#私有方法
def __send_msg(self):
print("-----正在发送短信-----")
#公有方法
def send_msg(self,new_money):
if new_money>10000:
#当验证成功后再调用上边的私有方法
self.__send_msg()
else:
print("余额不足请充值后在发送短信……")
dog = Dog()
dog.send_msg(100)
'''
#del
class Dog:
def __del__(self):
print("------英雄over-------")
dog1 = Dog()
dog2 = dog1
del dog1 #不会调用__del__方法,因为这个对象还有其他的变量指向他,即 引用计算不是0
del dog2 #此时会调用__del__方法,因为没有变量指向他了
print("=============")
#如果在程序结束时,有些对象还存在,那么Python解释器会自动调用他们的__del__方法来完成清理工作
|
#1.打印功能提示
print("="*50)
print(" 名片管理系统 V0.01")
print(" 1.添加一个新的名片")
print(" 2.删除一个新的名片")
print(" 3.修改一个新的名片")
print(" 4.查询一个新的名片")
print(" 5.退出系统")
print("="*50)
#用来存储名片
card_infors = []
while True:
#2.获取用户的输入
num = int(input("请输入操作序号:"))
#3.根据用户的数据执行相应的功能
if num==1:
new_name = input("请输入新的名字:")
new_qq = input("请输入新的QQ:")
new_wec = input("请输入新的微信:")
new_addr = input("请输入新的地址:")
#定义一个新的字典,用来存储一个新的名片
new_infor = {}
new_infor['name'] = new_name
new_infor['qq'] = new_qq
new_infor['wec'] = new_wec
new_infor['addr'] = new_addr
#将一个字典添加到列表中
card_infors.append(new_infor)
print(card_infors)
elif num==2:
pass
elif num==3:
pass
elif num==4:
pass
elif num==5:
break
else:
print("输入有误,请重新输入")
print("")
|
#1.打印菜单功能
print("="*30)
print(" 学生管理系统V0.01 ")
print(" 1.添加一个新的信息")
print(" 2.删除一个学生信息")
print(" 3.修改一个学生信息")
print(" 4.查询一个学生信息")
print(" 5.显示所有学生信息")
print(" 6.退出系统")
print(" 7.删除数据库")
print("="*30)
admin_infors = []
while True:
#2.用户输入
num = int(input("请输入操作序号:"))
#3.添加姓名
if num == 1:
new_name = input("请输入您要添加的姓名:")
new_age = int(input("请输入该学生的年龄:"))
new_SID = int(input("请输入该学生的学号:"))
new_sex = input("请输入该学生的性别:")
new_infor = {}
new_infor['name'] = new_name
new_infor['age'] = new_age
new_infor['SID'] = new_SID
new_infor['sex'] = new_sex
print(new_infor)
admin_infors.append(new_infor)
print(admin_infors)
#4.删除姓名
elif num ==2:
i = 0
del_name = input("请输入您要删除的姓名:")
for temp in admin_infors:
i += 1
if del_name == temp['name']:
print("要删除的信息已找到!")
del admin_infors[i-1]
print("信息已删除!")
#print(i)#for test
break
else:
print("您要删除的信息不在此……")
#5.修改姓名
elif num ==3:
modi_name = input("请输入您要修改的学生姓名:")
j = 0
for temp in admin_infors:
j += 1
if modi_name == temp['name']:
print("要修改的姓名已找到")
new_name = input("请输入您要添加的姓名:")
new_age = int(input("请输入该学生的年龄:"))
new_SID = int(input("请输入该学生的学号:"))
new_sex = input("请输入该学生的性别:")
new_infor = {}
new_infor['name'] = new_name
new_infor['age'] = new_age
new_infor['SID'] = new_SID
new_infor['sex'] = new_sex
admin_infors[j-1] = new_infor
print("信息已修改")
break
else:
print("您要修改的学生信息不在此")
#6.查询姓名
elif num ==4:
find_name = input("请输入您要查询的名字:")
for temp in admin_infors:
if find_name == temp['name']:
print("姓名\t年龄\t学号\t性别")
print("%s\t%s\t%s\t%s"%(temp['name'],temp['age'],temp['SID'],temp['sex']))
break
else:
print("您要查找的信息不在此")
#7.显示所有学生信息
elif num ==5:
print("姓名\t年龄\t学号\t性别")
for temp in admin_infors:
print("%s\t%s\t%s\t%s"%(temp['name'],temp['age'],temp['SID'],temp['sex']))
#8.退出系统
elif num ==6:
print("感谢使用本系统,再见!")
break
#9.数据库删除
elif num ==7:
num = int(input("请输入数字1再次确认删除数据库:"))
if num == 1:
admin_infors.clear()
print("数据库已删除!系统已自动报警,谁也跑不了!!!")
else:
print("操作失败")
else:
print("您的输入有误,请重新输入")
|
#1. 获取用户的输入
num = int(input("请输入一个数字(1~7:):"))
#2. 判断用户的数据,并且显示对应的信息
if num==1:
print("星期一")
elif num==2:
print("星期二")
elif num==3:
print("星期三")
elif num==4:
print("星期四")
elif num==5:
print("星期五")
elif num==6:
print("星期六")
elif num==7:
print("星期七")
else:
print("你输入的数据有误……")
|
from math import sqrt
def judgePrime(num):
if num <= 1:
return 0
#for i in range(2,int(sqrt(num)+1)):
''' for i in range(2,num):#此两种算法皆可,上面比下面快很多,找素数只需要除到平方根+1
if num%i == 0:
return 0
return 1
'''
i = 1#有问题
while i*i <= num:
if num%i == 0:
return 0
i += 1
return 1
j = 1
for a in range(0,100000):
if judgePrime(a) == 1:
#print(a)
j += 1
print("素数的个数是:%d"%j)
|
#1.打印功能提示
print('='*50)
print(' 名字管理系统 V8.6')
print(' 1:添加一个新的名字:')
print(' 2:删除一个新的名字:')
print(' 3:修改一个新的名字:')
print(' 4:查询一个新的名字:')
print('='*50)
names = []#定义一个空的列表从来存储添加名字
while True: #死循环
#2.获取用的选择
num = int(input("请输入功能序号:"))
#3.根据用户的选择,执行相应的功能
if num==1:
new_name = input('请输入名字:')
names.append(new_name)
print(names)
elif num==2:
pass
elif num==3:
pass
elif num==4:
find_name = input('请输入要查询的名字:')
if find_name in names:
print('找到了你要找的人')
else:
print('查无此人')
else:
print('您的输入有误,请重新输入')
|
import os
#1.获取用户文件夹输入
fold_name = input("请输入您要重命名的文件夹:")
funFlag = int(input("请输入您的需求(1 表示添加标志,2表示删除标志):")) #1表示添加标志 2表示删除标志
string_name = input("请输入您要添加或删除的字符:")
#2.获取所有文件名
file_names = os.listdir(fold_name)
#跳进文件夹执行
os.chdir(fold_name)
#遍历输出所有文件名字
for name in file_names:
#print(name)#for test
if funFlag == 1:
newName = string_name + name
elif funFlag == 2:
num = len(string_name)
newName = name[num:]
#print(newName)#for test
os.rename(name,newName)
|
#在Python中 值是靠引用来传递
# id() 判断两个变量是否为同一个值的引用 id可理解为内存的地址标示
a = 1
b = a
print(id(a))
print(id(b))
a = 2
print(id(a))
|
class SweetPotato:
"""定义一个地瓜类"""
def __init__(self):
self.cookString = "生的"
self.cookLevel = 0
self.condiments = []#用来保存添加的佐料
def __str__(self):
return "地瓜的状态是%s(%d),添加的佐料有%s"%(self.cookString,self.cookLevel,str(self.condiments))
def cook(self,cookTime):
self.cookLevel += cookTime
if self.cookLevel >= 0 and self.cookLevel < 3:
self.cookString = "生的"
elif self.cookLevel >= 3 and self.cookLevel < 6:
self.cookString = "半生不熟"
elif self.cookLevel >= 6 and self.cookLevel < 9:
self.cookString = "熟透了"
elif self.cookLevel >= 9:
self.cookString = "烤糊了"
def addCondiments(self,item):
self.condiments.append(item)
di_gua = SweetPotato()
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.addCondiments("洋葱")
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.addCondiments("大蒜")
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
di_gua.addCondiments("韭菜")
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.addCondiments("番茄汁")
di_gua.cook(1)
print(di_gua)
|
age = input("请输入你的年龄:")
age_number = int(age)
if age_number>18:
print("已成年,可以去网吧嗨皮")
else:
print("未成年,回家写作业吧")
|
def test(a,b):
a+b
result1 = test(11,22)
print(result1)#None 因为没有return
#定义一个匿名函数
func = lambda a,b:a+b
result2 = func(11,22)
print(result2)#和普通函数不一样,不需要return
|
import random
player = input("请输入:剪刀(0) 石头(1) 布(2):")
player = int(player)
computer = random.randint(0,2)
if((player == 0) and (computer == 2)) or ((player == 1) and (computer == 0)) or ((player ==2) and (computer == 1)):
print("获胜,哈哈,你太厉害了!")
elif player == computer:
print("平局,要不要再来一局")
else:
print("输了,不要走,洗洗手在接着来,决战到天明")
|
__author__ = 'Dario Hermida'
import main as calculate
import numpy as np
import matplotlib as plot
def testing_main(min_salary, max_salary, step):
regular_salary = []
ruling_salary = []
salary = list(range(min_salary, max_salary, step))
for input_bruto in salary:
regular_salary.append(calculate.regular_salary(input_bruto))
ruling_salary.append(calculate.thirty_percent_rulling(input_bruto))
# print('this should be your salary', calculate.regular_salary(input_bruto))
# print('this should be your Ruling salary', calculate.thirty_percent_rulling(input_bruto))
return regular_salary, ruling_salary
|
# determine if a list is sorted
itemsOrdered = [6, 8, 19, 20, 23, 49, 87]
itemsUnordered = [6, 20, 8, 19, 56, 23, 87, 41, 49, 53]
def isSorted(itemList):
# Use brute force method
""" for i in range(0, len(itemList)-1):
if (itemList[i] > itemList[i+1]):
return False """
return all(itemList[i] <= itemList[i+1] for i in range(len(itemList)-1))
# return True
print(isSorted(itemsOrdered))
print(isSorted(itemsUnordered)) |
"""List partitioning library.
Minimal Python library that provides common functions
related to partitioning lists.
"""
import doctest
def parts(xs, number=None, length=None):
"""
Split a list into either the specified number of parts or
a number of parts each of the specified length. The elements
are distributed somewhat evenly among the parts if possible.
>>> list(parts([1,2,3,4,5,6,7], length=1))
[[1], [2], [3], [4], [5], [6], [7]]
>>> list(parts([1,2,3,4,5,6,7], length=2))
[[1, 2], [3, 4], [5, 6], [7]]
>>> list(parts([1,2,3,4,5,6,7], length=3))
[[1, 2, 3], [4, 5, 6], [7]]
>>> list(parts([1,2,3,4,5,6,7], length=4))
[[1, 2, 3, 4], [5, 6, 7]]
>>> list(parts([1,2,3,4,5,6,7], length=5))
[[1, 2, 3, 4, 5], [6, 7]]
>>> list(parts([1,2,3,4,5,6,7], length=6))
[[1, 2, 3, 4, 5, 6], [7]]
>>> list(parts([1,2,3,4,5,6,7], length=7))
[[1, 2, 3, 4, 5, 6, 7]]
>>> list(parts([1,2,3,4,5,6,7], 1))
[[1, 2, 3, 4, 5, 6, 7]]
>>> list(parts([1,2,3,4,5,6,7], 2))
[[1, 2, 3], [4, 5, 6, 7]]
>>> list(parts([1,2,3,4,5,6,7], 3))
[[1, 2], [3, 4], [5, 6, 7]]
>>> list(parts([1,2,3,4,5,6,7], 4))
[[1], [2, 3], [4, 5], [6, 7]]
>>> list(parts([1,2,3,4,5,6,7], 5))
[[1], [2], [3], [4, 5], [6, 7]]
>>> list(parts([1,2,3,4,5,6,7], 6))
[[1], [2], [3], [4], [5], [6, 7]]
>>> list(parts([1,2,3,4,5,6,7], 7))
[[1], [2], [3], [4], [5], [6], [7]]
>>> list(parts([1,2,3,4,5,6,7], 7, [1,1,1,1,1,1,1]))
[[1], [2], [3], [4], [5], [6], [7]]
>>> list(parts([1,2,3,4,5,6,7], length=[1,1,1,1,1,1,1]))
[[1], [2], [3], [4], [5], [6], [7]]
>>> list(parts([1,2,3,4,5,6], length=[2,2,2]))
[[1, 2], [3, 4], [5, 6]]
>>> list(parts([1,2,3,4,5,6], length=[1,2,3]))
[[1], [2, 3], [4, 5, 6]]
>>> list(parts([1,2,3,4,5,6], 2, 3))
[[1, 2, 3], [4, 5, 6]]
>>> list(parts([1,2,3,4,5,6], number=3, length=2))
[[1, 2], [3, 4], [5, 6]]
>>> list(parts([1,2,3,4,5,6], 1.2))
Traceback (most recent call last):
...
TypeError: number of parts must be an integer
>>> list(parts([1,2,3,4,5,6], length=1.2))
Traceback (most recent call last):
...
TypeError: length parameter must be an integer or list of integers
>>> list(parts([1,2,3,4,5,6], 2, length=[1,2,3]))
Traceback (most recent call last):
...
ValueError: number of parts does not match number of part lengths specified in input
>>> list(parts([1,2,3,4,5,6,7], number=3, length=2))
Traceback (most recent call last):
...
ValueError: list cannot be split into 3 parts each of length 2
>>> list(parts([1,2,3], length=4))
[[1, 2, 3]]
>>> list(parts([1,2,3], number=3, length=[1,2,3]))
[[1], [2, 3]]
>>> list(parts([1,2,3]))
Traceback (most recent call last):
...
ValueError: must specify number of parts or length of each part
>>> list(parts([1,2,3], length=[4]))
Traceback (most recent call last):
...
ValueError: cannot return part of requested length because list too short
>>> list(parts([1,2,3], number=1, length=[4]))
Traceback (most recent call last):
...
ValueError: cannot return part of requested length because list too short
"""
if number is not None and not isinstance(number, int):
raise TypeError("number of parts must be an integer")
if length is not None:
if not isinstance(length, int):
if not isinstance(length, list) or\
(not all([isinstance(l, int) for l in length])):
raise TypeError(
"length parameter must be an integer or list of integers"
)
if number is not None and length is None:
number = max(1, min(len(xs), number)) # Number should be reasonable.
length = len(xs) // number
i = 0
# Produce parts by updating length after each part to ensure
# an even distribution.
while number > 0 and i < len(xs):
number -= 1
if number == 0:
yield xs[i:]
break
else:
yield xs[i:i + length]
i += length
length = (len(xs) - i) // number
elif number is None and length is not None:
if isinstance(length, int):
length = max(1, length)
for i in range(0, len(xs), length): # Yield parts of specified length.
yield xs[i:i + length]
else: # Length is a list of integers.
xs_index = 0
len_index = 0
while xs_index < len(xs):
if xs_index + length[len_index] <= len(xs):
yield xs[xs_index:xs_index + length[len_index]]
xs_index += length[len_index]
len_index += 1
else:
raise ValueError(
"cannot return part of requested length because list too short"
)
elif number is not None and length is not None:
if isinstance(length, int):
if length * number != len(xs):
raise ValueError(
"list cannot be split into " + str(number) +\
" parts each of length " + str(length)
)
length = max(1, length)
for i in range(0, len(xs), length): # Yield parts of specified length.
yield xs[i:i + length]
else: # Length is a list of integers.
if len(length) == number:
xs_index = 0
len_index = 0
while xs_index < len(xs):
if xs_index + length[len_index] <= len(xs):
yield xs[xs_index:xs_index + length[len_index]]
xs_index += length[len_index]
len_index += 1
else:
raise ValueError(
"cannot return part of requested length because list too short"
)
else:
raise ValueError(
"number of parts does not match number of part lengths specified in input"
)
else: # Neither is specified.
raise ValueError("must specify number of parts or length of each part")
if __name__ == "__main__":
doctest.testmod() # pragma: no cover
|
"""
003-plot-timeseries.py
Plot data from the Harry Potter data-set as a time-series
"""
import matplotlib.pyplot as plt
import load_hp_data as hp
import math
# We can play with styles:
# plt.style.use('bmh')
plt.style.use('ggplot')
# To see available styles, type:
#plt.style.available
fig, ax = plt.subplots(1)
ax.plot(hp.columns['timestamp'],
hp.columns['size'],
'g.' #get green dot plot
# color='g', marker="."
)
ax.set_xlabel('Time')
ax.set_ylabel('Size of the edit')
# plt.show()
# Challenge: Is edit size related to how long it's been since the last edit?
# => Plot the relationship between edit size and the time since the last edit:
## Hint 1: the number of seconds between two edits is:
#delta_time1 = (hp.columns['timestamp'][1] - hp.columns['timestamp'][0]).total_seconds()
## Hint 2:
# You can give `plt.plot` more arguments to control the shape/size/color
# of the markers used. For example, try:
# ax.plot([1,2,3], [2,4,8], '.')
# ax.plot([1,2,3], [2,4,8], 'r.')
figure, axis = plt.subplots(1)
x_time=[]
y_size=[]
total_edit_count = len(hp.rows)
for i in range(len(hp.columns['timestamp'])-1):
x_time.append((hp.columns['timestamp'][i+1] - hp.columns['timestamp'][i]).total_seconds())
# y_size.append((hp.columns['size'][i+1] - hp.columns['size'][i]))
axis.plot(x_time, hp.columns['size'][1:],'.',alpha=0.01)
axis.loglog()
plt.show()
#solution!
# fig, ax = plt.subplots(1)
#
# delta = []
# for i in range(len(hp.columns['timestamp'])-1):
# t1 = hp.columns['timestamp'][i]
# t2 = hp.columns['timestamp'][i-1]
# delta.append((t2-t1).total_seconds())
# ax.plot(delta, hp.columns['size'][1:], '.')
#how to deal with biased data-set?
# ax.set_xlim([0, 10000000])#reduce range
# ax.loglog()
# plt.show()
# And see online documentation here:
# http://matplotlib.org/api/pyplot_summary.html
# http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
|
# f = open('demo.txt', 'r')
# content = f.readline(29)
# print(content)
# f.close()
courses = [
("Javascript", 200),
("Python", 290),
("C++", 210),
]
courses.append(("Django", 400))
print(courses)
filtered = list(map(lambda item: item[1], courses))
print(filtered)
print("He said \"this is not a good software\", please access D:\\LionKing")
def myFunction(a, b):
print('Value', a + b)
myFunction(190, 130)
list = [[1,2,4,3], [14,24], [23, 24, 53]]
print(list[1][1])
itera = [1, 2, 3, 3]
print(sum(itera, 12))
|
import sqlite3
connection = sqlite3.connect('movies.db')
cursor = connection.cursor()
cursor.execute("INSERT INTO Movies VALUES('Taxi driver', 'Martin Scorsese', 1976)")
cursor.execute("SELECT * FROM Movies")
print(cursor.fetchone())
connection.commit()
connection.close()
|
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 21 18:16:27 2020
@author: vais4
"""
class BinaryTree():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def addChild(self, data):
if data == self.data:
return
elif data < self.data:
if self.left:
self.left.addChild(data)
else:
self.left = BinaryTree(data)
else:
if self.right:
self.right.addChild(data)
else:
self.right = BinaryTree(data)
def traversal(self):
elements = []
if self.left:
elements += self.left.traversal()
elements.append(self.data)
if self.right:
elements += self.right.traversal()
return elements
def search(self, val):
if self.data == val:
return True
if val < self.data:
if self.left:
return self.left.search(val)
else:
return False
if val > self.data:
if self.right:
return self.right.search(val)
else:
return False
def find_min(self):
if self.left is None:
return self.data
return self.left.find_min()
def find_max(self):
if self.right is None:
return self.data
return self.right.find_max()
def delete(self, val):
if val < self.data:
if self.left:
self.left = self.left.delete(val)
elif val > self.data:
if self.right:
self.right = self.right.delete(val)
else:
if self.left is None and self.right is None:
return None
elif self.left is None:
return self.right
elif self.right is None:
return self.left
min_val = self.right.find_min()
self.data = min_val
self.right = self.right.delete(min_val)
return self
if __name__ == '__main__':
numbers = [17,4,1,20,9,23,18,34,-4,17]
root = BinaryTree(numbers[0])
for i in range (1,len(numbers)):
root.addChild(numbers[i])
print(root.traversal())
print(root.search(21))
root.delete(9)
print(root.traversal())
|
#making a class student info as i will use a several objects student 1 , student 2 , etc
class student_info:
#student name as a method
def student_name(self,name):
self.student_name=name
return name
#student mark as a method
def student_mark(self,mark):
self.student_mark=mark
return mark
#method to calculate the avg
def student_avg(self):
avg = (self.student_mark/100)*100
return avg
#method to calculate the rating
def student_rating(self):
avg = self.student_avg()
if avg < 50:
return 'Fail'
elif avg >= 50 :
return 'succeed'
#adding lists to store several students data
name =[]
mark =[]
avg=[]
rating=[]
#for loop to get the information from the user
for i in range(3):
i = student_info()
name.append(i.student_name(input('Enter a name \n')))
mark.append(i.student_mark(int(input('Enter his mark\n'))))
avg.append(i.student_avg())
rating.append(i.student_rating())
#printing all the data
print(name,',\t',mark,',\t',avg,',\t',rating,',\t')
|
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
tariff = int(input("Which tariff? 11 or 31?"))
while tariff != 11 and tariff !=31:
if tariff == 11:
tariff= TARIFF_11
else:
tariff= TARIFF_31
usage = float(input("Enter daily use in kWh"))
days = int(input("Enter number of days in billing period"))
callBill = tariff * usage * days
print("Estimated bill:", callBill)
|
import pywhatkit
print('Convert the text into handwritten\n')
txt = input('Enter the text(paragraph) - \n')
pywhatkit.text_to_handwriting(txt, rgb=[0,0,255]) |
import random
def cebolinha(txt):
txt = txt.replace('\n', ' @¨# ')
txt = txt.split()
final_txt = []
for word in txt:
word.strip()
if word == '@¨#':
word = word.replace('@¨#', '\n')
else:
check_word = ''.join([i for i in word if i.isalpha()])
if check_word[len(check_word) - 1] != 'r' and check_word[
len(check_word) - 1] != 'R':
word = word.replace('r', 'l').replace('R', 'L')
else:
count_r_down = word.count('r')
count_r_upper = word.count('R')
word = word.replace('r', 'l', count_r_down - 1).\
replace('R',
'L',
count_r_upper - 1)
final_txt.append(word + ' ')
final_txt = ''.join(final_txt).replace(' \n ', '\n').replace('\n ',
'\n').replace(
' \n', '\n')
return final_txt
def upper_and_lower(txt):
capitalize = 0
final_txt = []
for letter in txt:
if capitalize:
letter = letter.upper()
capitalize = 0
else:
letter = letter.lower()
capitalize = 1
final_txt.append(letter)
return ''.join(final_txt)
class Zalgo:
def __init__(self):
self.numAccentsUp = (1, 3)
self.numAccentsDown = (1, 3)
self.numAccentsMiddle = (1, 2)
self.maxAccentsPerLetter = 3
# downward going diacritics
self.dd = ['̖', ' ̗', ' ̘', ' ̙', ' ̜', ' ̝', ' ̞', ' ̟', ' ̠', ' ̤',
' ̥', ' ̦', ' ̩', ' ̪', ' ̫', ' ̬', ' ̭', ' ̮', ' ̯', ' ̰',
' ̱', ' ̲', ' ̳', ' ̹', ' ̺', ' ̻', ' ̼', ' ͅ', ' ͇', ' ͈',
' ͉', ' ͍', ' ͎', ' ͓', ' ͔', ' ͕', ' ͖', ' ͙', ' ͚', ' ', ]
# upward diacritics
self.du = [' ̍', ' ̎', ' ̄', ' ̅', ' ̿', ' ̑', ' ̆', ' ̐', ' ͒', ' ͗',
' ͑', ' ̇', ' ̈', ' ̊', ' ͂', ' ̓', ' ̈́', ' ͊', ' ͋', ' ͌',
' ̃', ' ̂', ' ̌', ' ͐', ' ́', ' ̋', ' ̏', ' ̽', ' ̉', ' ͣ',
' ͤ', ' ͥ', ' ͦ', ' ͧ', ' ͨ', ' ͩ', ' ͪ', ' ͫ', ' ͬ', ' ͭ',
' ͮ', ' ͯ', ' ̾', ' ͛', ' ͆', ' ̚', ]
# middle diacritics
self.dm = [' ̕', ' ̛', ' ̀', ' ́', ' ͘', ' ̡', ' ̢', ' ̧', ' ̨', ' ̴',
' ̵', ' ̶', ' ͜', ' ͝', ' ͞', ' ͟', ' ͠', ' ͢', ' ̸', ' ̷',
' ͡', ]
def zalgofy(self, text):
# Zalgofy a string
# get the letters list
letters = list(text) # ['t','e','s','t',' ','t',...]
# print(letters)
# new_word = ''
new_letters = []
# for each letter, add some diacritics of all varieties
for letter in letters: # 'p', etc...
a = letter # create a dummy letter
# skip this letter we can't add a diacritic to it
if not a.isalpha():
new_letters.append(a)
continue
num_accents = 0
num_u = random.randint(self.numAccentsUp[0], self.numAccentsUp[1])
num_d = random.randint(self.numAccentsDown[0],
self.numAccentsDown[1])
num_m = random.randint(self.numAccentsMiddle[0],
self.numAccentsMiddle[1])
# Try to add accents to the letter, will add an upper, lower,
# or middle accent randomly until
# either num_accents == self.maxAccentsPerLetter or we have added
# the maximum upper, middle and lower accents. Denoted
# by num_u, num_d, and num_m
while num_accents < self.maxAccentsPerLetter and num_u + num_m + \
num_d != 0:
randint = random.randint(0,
2) # randomly choose what accent
# type to add
if randint == 0:
if num_u > 0:
a = self.combine_with_diacritic(a, self.du)
num_accents += 1
num_u -= 1
elif randint == 1:
if num_d > 0:
a = self.combine_with_diacritic(a, self.dd)
num_d -= 1
num_accents += 1
else:
if num_m > 0:
a = self.combine_with_diacritic(a, self.dm)
num_m -= 1
num_accents += 1
# a = a.replace(" ","") #remove any spaces, this also gives it
# the zalgo text look
# print('accented a letter: ' + a)
new_letters.append(a)
new_word = ''.join(new_letters)
return new_word
@staticmethod
def combine_with_diacritic(letter, diacritic_list):
# Combines letter and a random character from diacriticLis
return letter.strip() + diacritic_list[
random.randrange(0, len(diacritic_list))].strip()
def zalgo_txt(txt):
z = Zalgo()
z.numAccentsUp = (1, 3)
z.numAccentsDown = (1, 3)
z.numAccentsMiddle = (1, 2)
z.maxAccentsPerLetter = 40
return z.zalgofy(txt)
def double_struck(txt):
normal_letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM" \
"NOPQRSTUVWXYZ"
double_struck_letter = \
"𝟘𝟙𝟚𝟛𝟜𝟝𝟞𝟟𝟠𝟡𝕒𝕓𝕔𝕕𝕖𝕗𝕘𝕙𝕚𝕛𝕜𝕝𝕞𝕟𝕠𝕡𝕢𝕣𝕤𝕥𝕦𝕧𝕨𝕩𝕪𝕫𝔸𝔹ℂ𝔻𝔼𝔽𝔾ℍ𝕀𝕁𝕂𝕃𝕄" \
"ℕ𝕆ℙℚℝ𝕊𝕋𝕌𝕍𝕎𝕏𝕐ℤ"
trantab = txt.maketrans(normal_letters, double_struck_letter)
txt = txt.translate(trantab)
return txt
def cursive(txt):
normal_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM" \
"NOPQRSTUVWXYZ"
cursive_letter = \
"𝓪𝓫𝓬𝓭𝓮𝓯𝓰𝓱𝓲𝓳𝓴𝓵𝓶𝓷𝓸𝓹𝓺𝓻𝓼𝓽𝓾𝓿𝔀𝔁𝔂𝔃𝓐𝓑𝓒𝓓𝓔𝓕𝓖𝓗𝓘𝓙𝓚𝓛𝓜" \
"𝓝𝓞𝓟𝓠𝓡𝓢𝓣𝓤𝓥𝓦𝓧𝓨𝓩"
trantab = txt.maketrans(normal_letters, cursive_letter)
txt = txt.translate(trantab)
return txt
def large(txt):
normal_letters = "`1234567890-=~!@#$%^&*()_+qwertyuiop[]QWERTYUIOP" \
"{}|asdfghjkl;'ASDFGHJKL:" \
"\\zxcvbnm,./ZXCVBNM<>?"
fancy_letter = "`1234567890-=~!@#$%^&*()_+qwertyuiop" \
"[]QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:" \
"\\zxcvbnm,./ZXCVBNM<>?"
trantab = txt.maketrans(normal_letters, fancy_letter)
txt = txt.translate(trantab)
return txt
def circled(txt):
normal_letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcde" \
"fghijklmnopqrstuvwxyz"
fancy_letter = "⓪①②③④⑤⑥⑦⑧⑨ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏⓐⓑⓒⓓⓔ" \
"ⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ"
trantab = txt.maketrans(normal_letters, fancy_letter)
txt = txt.translate(trantab)
return txt
def negative_circled(txt):
normal_letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcde" \
"fghijklmnopqrstuvwxyz"
fancy_letter = \
"🄌➊➋➌➍➎➏➐➑➒🅐🅑🅒🅓🅔🅕🅖🅗🅘🅙🅚🅛🅜🅝🅞🅟🅠🅡🅢🅣🅤🅥🅦🅧🅨🅩🅐🅑🅒🅓🅔" \
"🅕🅖🅗🅘🅙🅚🅛🅜🅝🅞🅟🅠🅡🅢🅣🅤🅥🅦🅧🅨🅩"
trantab = txt.maketrans(normal_letters, fancy_letter)
txt = txt.translate(trantab)
return txt
def parenthesis(txt):
normal_letters = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
"abcdefghijklmnopqrstuvwxyz"
fancy_letter = \
"⑴⑵⑶⑷⑸⑹⑺⑻⑼🄐🄑🄒🄓🄔🄕🄖🄗🄘🄙🄚🄛🄜🄝🄞🄟🄠🄡🄢🄣🄤🄥🄦🄧🄨🄩" \
"⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵"
trantab = txt.maketrans(normal_letters, fancy_letter)
txt = txt.translate(trantab)
return txt
def fraktur(txt):
normal_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
fancy_letter = \
"𝔄𝔅ℭ𝔇𝔈𝔉𝔊ℌℑ𝔍𝔎𝔏𝔐𝔑𝔒𝔓𝔔ℜ𝔖𝔗𝔘𝔙𝔚𝔛𝔜ℨ𝔞𝔟𝔠𝔡𝔢𝔣𝔤𝔥𝔦𝔧𝔨𝔩𝔪𝔫𝔬𝔭𝔮𝔯𝔰𝔱𝔲𝔳𝔴𝔵𝔶𝔷"
trantab = txt.maketrans(normal_letters, fancy_letter)
txt = txt.translate(trantab)
return txt
def leet(txt):
normal_letters = "tTiIbBoOsSaAeElLzZ"
fancy_letter = "771188005544331122"
trantab = txt.maketrans(normal_letters, fancy_letter)
txt = txt.translate(trantab)
return txt
|
import time
a=time.strftime("%Y%m%d%H%M%S%MS", time.localtime())
print(a)
"""
Compare the date str and now
"""
##timeA="5 28 22:24:24 2016"
timeA="8 10 14:30:00 2016"
timeATick=time.mktime(time.strptime(timeA,"%m %d %H:%M:%S %Y"))
print(timeATick)
print(time.time())
if timeATick<time.time():
print("The date before now")
else:
print("The date after now") |
def myfun(a,b):
a=5
b=3
return b-a
if __name__=='__main__':
#print(myfun(b=5))
#TypeError: myfun() missing 1 required positional argument: 'a'
for i in range(1,10,2):
print(i) |
from functools import reduce
# дискретная нейронная сеть хопфилда
# пример синхронной работы
instances = [
[1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1], # x1
[-1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1], # x2
[-1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, -1] # x3
]
# испорченные образцы
y1 = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
y2 = [-1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, 1]
y3 = [1, -1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1]
# каждый вектор транспонируем и умножаем на сам себя
def get_matrix_from_instance(v):
matrix = []
for index in range(len(v)):
matrix.append([])
for index2 in range(len(v)):
matrix[index].append(v[index2] * v[index])
return matrix
all_matrices = list(map(get_matrix_from_instance, instances))
# складываем все матрицы
def add_up_the_matrices(matrices):
matrix = []
for index in range(len(matrices)):
if index == 0:
matrix = matrices[index]
else:
for i1 in range(len(matrices[index])):
for i2 in range(len(matrices[index][i1])):
matrix[i1][i2] = matrix[i1][i2] + matrices[index][i1][i2]
return matrix
matrix_w = add_up_the_matrices(all_matrices)
# выводим полученную матрицу(W)
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in matrix_w]))
# умножаем полученную матрицу(W) на вектор испорченного образца
def multiply_matrix_by_bad_instance(vector, counter):
new_vector = []
if counter == 10:
print('Не соответствует ни одному образцу')
return
for i in range(len(matrix_w)):
new_vector.append(0)
for i2 in range(len(matrix_w[i])):
new_vector[i] = new_vector[i] + (matrix_w[i][i2] * vector[i2])
super_puper_vector = activation_func(new_vector)
equal = compare_result_with_instances(super_puper_vector)
if equal:
return
else:
counter = counter + 1
multiply_matrix_by_bad_instance(super_puper_vector, counter)
# передаем полученный вектр в активационную функцию
def activation_func(vector):
return list(map(lambda x: -1 if x < 0 else 1, vector))
def compare_result_with_instances(vector):
equal = None
for i1 in range(len(instances)):
val = list(map(lambda x, y: True if x == y else False, vector, instances[i1]))
if False not in val:
equal = True
print(
'образец #' + str(i1 + 1) + ': ' + str(instances[i1]) + ' равен входному образцу:' + str(y1))
break
return equal
multiply_matrix_by_bad_instance(y1, 0)
|
# coding: utf-8
import random
def montyhall(n=1, change_door=True):
result_list = []
for i in range(0, n):
ds = DoorShow(change_door=change_door)
result_list.append(ds.run())
true_count = result_list.count(True)
false_count = result_list.count(False)
print('True: {} [{}]'.format(true_count, true_count / n * 100))
print('False: {} [{}]'.format(false_count, false_count / n * 100))
def _create_doors():
doors = []
while len(doors) < 3:
if len(doors) == 2 and not any(doors):
doors.append(True)
continue
if any(doors):
doors.append(False)
continue
doors.append(random.choice([True, False])) # bool(random.getrandbits(1))
return doors
class DoorShow(object):
def __init__(self, change_door=True):
self.doors = _create_doors()
self.change_door = change_door
self.first_choice = None
self.second_choice = None
def first_door(self):
door_n = random.choice([0, 1, 2])
self.first_choice = (door_n, self.doors[door_n])
def second_door(self):
if not self.change_door:
return
first_choice_index = [0, 1, 2].index(self.first_choice[0])
alternatives = [0, 1, 2]
alternatives.pop(first_choice_index)
if self.doors[alternatives[0]]:
self.second_choice = (alternatives[0], self.doors[alternatives[0]])
else:
self.second_choice = (alternatives[1], self.doors[alternatives[1]])
def result(self):
if self.change_door:
return self.second_choice[1]
return self.first_choice[1]
def run(self):
self.first_door()
self.second_door()
return self.result()
|
def bfs( start, end, graph ):
todo = [(start, [start])]
while len( todo ):
node, path = todo.pop( 0 )
for next_node in graph[node]:
if next_node in path:
continue
elif next_node == end:
yield path + [next_node]
else:
todo.append( (next_node, path + [next_node]) )
if __name__ == '__main__':
graph = { 'A': ['B','C'],
'B': ['D'],
'C': ['E'],
'D': ['E', 'F'],
'E': [] }
[ print( x ) for x in bfs( 'A', 'F', graph ) ]
|
import sys
nterms = 10
f1 = 1
f2 = 1
fn = 0
count = 0
if nterms <= 0:
print ("Enter a positive number")
elif nterms == 1:
print (f1)
else:
while count <= nterms:
print(f1,f2)
fth = (fn - 1) + (fn - 2)
f1 = f2
f2 = fth
count += 1 |
#coding: cp949
print ("̿ , α _ver4")
age = int(input("̸ Էϼ: "))
choice = int(input(" ϼ. (1: , 2: ſ ī) "))
kid = 2000
teen = 3000
adult = 5000
if choice == 1:
if age<0:
print("ٽ Էϼ")
elif age<4:
print("ϴ ̸ Դϴ")
elif age>=4 and age<14:
print("ϴ ̸ 2000 Դϴ")
charge = int(input(" Էϼ : "))
if charge < kid:
print("%d ڶϴ. ԷϽ %d ȯմϴ."%(kid-charge ,charge))
elif charge == kid:
print("մϴ. Ƽ մϴ.")
elif charge > kid:
print("մϴ. Ƽ ϰ Ž %d ȯմϴ." %(charge-kid))
elif age>=14 and age<19:
print("ϴ ûҳ ̸ 3000 Դϴ")
charge = int(input(" Էϼ : "))
if charge < teen:
print("%d ڶϴ. ԷϽ %d ȯմϴ."%(teen-charge, charge))
elif charge == teen:
print("մϴ. Ƽ մϴ.")
elif charge > teen:
print("մϴ. Ƽ ϰ Ž %d ȯմϴ."%(charge-teen))
elif age>=19 and age<66:
print("ϴ ̸ 5000 Դϴ")
charge = int(input(" Էϼ : "))
if charge < adult:
print("%d ڶϴ. ԷϽ %d ȯմϴ."%(adult-charge,charge))
elif charge == adult:
print("մϴ. Ƽ մϴ.")
elif charge > adult:
print("մϴ. Ƽ ϰ Ž %d ȯմϴ." %(charge-adult))
elif age>=66:
print("ϴ ε̸ Դϴ")
if choice == 2:
if age>=4 and age<14:
print(" ݾ εǾ %d Ǿϴ. Ƽ մϴ." %(kid-(kid*0.1)))
elif age>=14 and age<19:
print(" ݾ εǾ %d Ǿϴ. Ƽ մϴ." %(teen-(teen*0.1)))
elif age>=19 and age<60:
print(" ݾ εǾ %d Ǿϴ. Ƽ մϴ." %(adult-(adult*0.1)))
elif age>=60 and age<66:
print(" ݾ εǾ %d Ǿϴ. Ƽ մϴ." %(adult-(adult*0.15)))
|
# coding: cp949
#pocket = ['paper','cellphone','money']
#pocket = ['paper','cellphone']
pocket=[]
item=input("Ͽ ì⼼: ")
pocket.append(item)
if'card' in pocket:
print("ſī ýø Ż õմϴ")
elif 'money' in pocket:
print(" ̿ ì⼼.")
elif 'cellphone' in pocket:
print("Ʈ ī ִ Ȯϼ")
else:
pass
|
def chocolate_dist(age_list):
age_list.sort(reverse=True)
#print(age_list)
length=len(age_list)
count_arr=[]
#print(age_list)
#print(length)
for i in range(length):
if(i==0):
count_arr.append(1)
continue
if(age_list[i]==age_list[i-1]):
count_arr.append(count_arr[i-1])
else:
count_arr.append(count_arr[i-1]+1)
#print(count_arr)
print(sum(count_arr))
age_list=list(map(int,input("Please enter the age of children:\n").split(",")))
chocolate_dist(age_list) |
#!/usr/bin/python3
#using os module to change working directory
#os.cwd() returns the path of current working directory.
import os
cwd = os.getcwd()
print("Current Working Directory:\n %s" %(cwd))
os.chdir("dir1")
print("\nWe go to chile directory using os.chdir().\nNow Current Working Directory:\n %s" %(os.getcwd()))
os.chdir(os.pardir)
print("\nWe go to parent directory using os.pardir().\nNow Current Working Directory:\n %s" %(os.getcwd()))
|
#!/usr/bin/python3
#Shows if a number is prime number or not
import threading
class PrimeNumber(threading.Thread):
def __init__(self, number):
threading.Thread.__init__(self)
self.Number = number
def run(self):
counter = 2
while counter*counter < self.Number:
if self.Number % counter == 0:
print ("%d is a prime number because %d = %d * %d" %(self.Number, self.Number, counter, self.Number/counter))
counter = counter + 1
print ("%d is a prime number" %(self.Number))
threads = []
while True:
input = long(input("number: "))
if input < 1:
break
threads = PrimeNumber(input)
threads += [thread]
thread.start()
for x in threads:
x.join()
|
# Binary Indexed Tree
# Reference http://hos.ac/slides/20140319_bit.pdf
class BIT:
def __init__(self, size):
self.bits = [0 for i in range(size+1)]
self.size = size
def update(self, index, value = 1):
index += 1
while index <= self.size:
self.bits[index] += value
index += index & (-1 * index)
def sum(self, index):
index += 1
ans = 0
while index > 0:
ans += self.bits[index]
index -= index & (-1 * index)
return ans |
#! /usr/bin/env python
import locale
from dialog import Dialog
d = Dialog(dialog="dialog")
def handle_exit_code(d, code):
# if the users clicks 'Cancel' or presses 'ESC' button
if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
# if the user clicks the 'Cancel button'
if code == d.DIALOG_CANCEL:
msg = "Are you sure you want to exit?"
else: # case for 'ESC'
msg = "You pressed ESC. Do you really want to quit?"
if d.yesno(msg) == d.DIALOG_OK: # if the user clicks 'OK' further, app terminates
# write a snippet here to go back to main menu
d.msgbox('Good Bye!', width = 20, height = 5)
return 0
else:
return 1
def get_password(d):
while 1:
(code, password) = d.passwordbox("Please Enter Your CLI password", width = 60)
if handle_exit_code(d, code):
break
return password
if d.yesno("Are you REALLY sure you want to see this?") == d.OK:
d.passwordbox("Please Enter Your CLI password", width = 60)
d.msgbox("You have been warned...")
# We could put non-empty items here (not only the tag for each entry)
code, tags = d.checklist("What sandwich toppings do you like?",
choices=[("Catsup", "", False),
("Mustard", "", False),
("Pesto", "", False),
("Mayonnaise", "", True),
("Horse radish","", True),
("Sun-dried tomatoes", "", True)],
title="Do you prefer ham or spam?",
backtitle="And now, for something "
"completely different...")
if code == d.OK:
# 'tags' now contains a list of the toppings chosen by the user
pass
else:
code, tag = d.menu("OK, then you have two options:",
choices=[("(1)", "Leave this fascinating example"),
("(2)", "Leave this fascinating example")])
if code == d.OK:
# 'tag' is now either "(1)" or "(2)"
pass
|
#contador = 1
#while(contador <= 10):
# print(contador)
# contador = contador + 1
#for contador in range(1, 11):
# print(contador)
num_tabuada = int(input('Digite o número você deseja a tabuada: '))
for multiplicador in range(1,11):
calc = num_tabuada*multiplicador
print('{}x{}={}'.format(num_tabuada,multiplicador,calc)) |
class Queue:
def __init__(self):
self.__storage = list()
def is_empty(self):
return len(self.__storage) == 0
def push(self, item):
self.__storage.append(item)
def first(self):
if not self.is_empty():
return self.__storage[0]
else:
raise Exception("Queue is empty")
def pop(self):
first_item = self.first()
self.__storage = self.__storage[1:]
return first_item
def __contains__(self, item):
return item in self.__storage
|
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
get_sum = sum(n_num)
mean = get_sum / n
print("Mean / Average is: " + str(mean)) |
myDic = {
1: {'name': '아아', 'price': 1000, '': 1},
2: {'name': '따아', 'price': 2000, '': 2},
3: {'name': '라떼', 'price': 3000, '': 3},
}
while(True):
money = int(input('준 돈 : '))
menuNum = int(input('''1. 아아
2. 따아
3. 라떼
주문 번호 : '''))
count = int(input('수량 : '))
if(myDic[menuNum]['stock'] - count >= 0):
print('{0} 주문! 거스름돈은 {1}원 입니다'
.format(myDic[menuNum]['name'], str(money - myDic[menuNum]['price'])))
myDic[menuNum]['stock'] -= count
print('{0} 개 남아있습니다'.format(myDic[menuNum]['stock']))
else:
print('주문불가!')
|
import unittest
from text_tetris import *
class TestTetrisMethods(unittest.TestCase):
# Simple tests for most important functions
def test_mix_field_and_current_piece(self):
temp_field = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
piece = [[0,1],[0,1]]
current_piece_object = {'piece':piece, 'x':1, 'y':1}
expected = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0]]
self.assertEqual(mix_field_and_current_piece(current_piece_object, temp_field), expected)
def test_is_occupied(self):
temp_field = [[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,1,0]]
piece = [[0,1],[0,1]]
current_piece_object = {'piece':piece, 'x':0, 'y':0}
self.assertTrue(is_occupied(piece, 0, 0, temp_field, dx=1))
self.assertFalse(is_occupied(piece, 0, 0, temp_field, dx=-1))
if __name__ == '__main__':
unittest.main()
|
def square (n):
return n*n
def cube (n):
return n*n*n
def average (values):
nvals = len(values)
sum=0.0
for c in values:
sum+=c
return float (sum)/nvals
|
import cv2
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
img=cv2.imread("photo.jpg")
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#^^We wanted to have a grayscale image of the pic
faces=face_cascade.detectMultiScale(gray_img, # "detectMultiScale" >>See at the bottom for explanation
scaleFactor=1.1, #Telling python to search bigger faces by scaling down picture by
minNeighbors=5) # 1.05= 5% OR 1.5=50% and search again and again til a face is detected
# Small number means more accuracy but more time
for x, y, w, h in faces:
img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
#^^ x,y= coordinates of upper left corner of the rectangle
# w, h are the width and height. (x+w,x+h) the other
# corner of the rectangle. 3 is the thickness of rectangle
#print(type(faces))
#print(faces)
resized=cv2.resize(img,(int(img.shape[1]/3),int(img.shape[1]/3)))
#cv2.imshow("Gray",gray_img) # Show picture in a window with name Gray
cv2.imshow("Gray",resized)
cv2.waitKey(0) # Window stays until user presses any key
cv2.destroyAllWindows()
# "detectMultiScale"
# It basically detects coordinates of upperleft corner of the face rectange
# and also gives height and width of the rectangle defining the face |
#Move Data from second register/Data into first register
def mv(Din):
#mv -> 000
Imm = "000"
#Checks if instruction is between two registers or immediate data and register
imData = isImmediateData(Din[1])
#Calculates primary Register address(3 bits)
rX = DecToBinary(Din[0][1])
#If immediate data convert hex data into 9 bits
if( imData ):
HexToBinary(Din[1])
else:
#Calculate address of secondary register (3bits)
pass
#Pad the beggining of the command with 6 zeros
pass
rY = "000000110"
completeCode = Imm + str(imData) +rX + rY
return completeCode
def mvt():
print("You Called Move Top!!")
#Checks if the command uses two registers or a register and immediate data from the instruction signal
def isImmediateData(op):
return 0 if op[0] == "r" else 1
#Takes in a hexadecimal number and returns the binary number as a string
def HexToBinary(hex):
nibbles = []
#Interate through each Hex digit and covert to nibble
for index, digit in enumerate(hex):
print("WORKING ON DIGIT",digit)
#Prep the MSB for new Digit
for i in range(4): nibbles.insert(0,0)
dig = int(digit)
#Convert Digit to 4 bits by dividing by each column and flooring
for i in range(4):
print("DIG IS CURRENTLY:",dig)
nibbles[3-i] = dig//(2**(3-i))
dig = dig - nibbles[3-i]*(2**(3-i))
nibbles.reverse()
output = "".join(map(str,nibbles))
print(nibbles)
print(output)
#Incomplete Function
def DecToBinary(dec):
if(False):
nibbles = []
for index, digit in enumerate(hex):
for i in range(4): nibbles.append(0)
dig = int(digit)
for i in range(4):
nibbles[index*4 + 3-i] = dig//(2**(3-i))
dig = dig - nibbles[index*4 + 3-i]*(2**(3-i))
return("001") |
# Got help from this! https://www.smallsurething.com/comparing-files-in-python-using-difflib/
import sys, pprint
from deepdiff import DeepDiff
pp = pprint.PrettyPrinter(indent=2)
def main():
print(sys.argv)
if len(sys.argv) != 3:
return
with open(sys.argv[1]) as f1, open(sys.argv[2]) as f2:
lines1 = f1.readlines()
lines2 = ['red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'blue', 'blue', 'blue', 'orange', 'yellow', 'yellow', 'yellow', 'o', 'o', 'o', 'o', 'o', 'o']
lines2 = [line + '\n' for line in lines2]
print(lines1)
print(lines2)
ddiff = DeepDiff(lines1, lines2)
pp.pprint(ddiff)
if __name__ == "__main__":
main()
|
# Got help from this! https://www.smallsurething.com/comparing-files-in-python-using-difflib/
import sys
import difflib
def main():
print(sys.argv)
if len(sys.argv) != 3:
return
with open(sys.argv[1]) as f1, open(sys.argv[2]) as f2:
lines1 = f1.readlines()
lines2 = f2.readlines()
# print(lines1)
# print(lines2)
for diff in difflib.context_diff(lines1, lines2):
print(diff)
if __name__ == "__main__":
main()
|
def main():
global randomNumber
randomNumber=getRandomNum()
guessRandomNumber(randomNumber)
def getRandomNum():
import random
return random.randint(1,10)
def guessRandomNumber (randomNumb):
global continueProgram
continueProgram = True
while (continueProgram == True):
print("Welcome to the Number Guessing Game!!!")
#continueProgram = True
print("What number am I thinking of from 1 to 10? You have 3 chances!")
global num
guessNum=False
guessChance=1
while (guessNum==False):
validInput = False
while (validInput == False):
try:
if guessNum !=4:
num = int(input("Please guess a number from 1 to 10:"))
num > 0 and num < 11
validInput = True
except:
print("Silly...I said a NUMBER from 1 to 10!")
if guessChance == 3:
guessNum = True
validInput = True
num=0
print("Sorry!!!! The number I was thinking of is:")
print(randomNumb)
guessChance = guessChance + 1
'''try:
num >0 and num<11
validInput = True
except:
print("DOPE!...I said a NUMBER from 1 to 10!")
'''
if num>11 or num<0 or (num!=int):
print("Silly...I said a NUMBER from 1 to 10!")
else:
validInput = True
if guessChance == 3:
guessNum = True
print("Sorry!!!! The number I was thinking of is:")
print(randomNumb)
guessChance = guessChance + 1
if num == randomNumb:
print("Hooray! You guessed the number I was thinking of!!!!")
print("The number I was thinking of is:")
print(randomNumb)
guessNum=True
if ((num==randomNumb+1) or num==(randomNumb-1))and (guessChance!=4):
print("Your guess is HOT!!!...CALIENTE!!!")
if guessChance==3:
guessNum=True
print("Sorry!!!! The number I was thinking of is:")
print(randomNumb)
elif ((num==randomNumb+2) or num==(randomNumb-2))and (guessChance!=4):
print("Your guess is WARM!")
if guessChance == 3:
guessNum = True
print("Sorry!!!! The number I was thinking of is:")
print(randomNumb)
guessChance = guessChance + 1
else:
if (num <randomNumb or num>randomNumb) and (guessChance!=4) and (0<num<11):
print("Sorry!!!Your guess is COLD..BRRRR")
if guessChance == 3 and num!=randomNumb:
guessNum = True
print("The number I was thinking of is:")
print(randomNumb)
guessChance = guessChance + 1
wantToContinue = str(input("--Do you want to play again? Press Q if you want to quit, all other input continues:"))
wantToContinue = wantToContinue.strip()
if wantToContinue == "Q" or wantToContinue == "q":
continueProgram = False
else:
main()
main()
|
def main():
CelsiusFahrenheitTemp()
def CelsiusFahrenheitTemp():
CelsiusFahrenheitTitle="Celsius Fahrenheit"
print(CelsiusFahrenheitTitle)
CTemp = 0
count = 101
while CTemp<count:
FTemp=float(1.8*CTemp+32)
print(CTemp,"C",end=" ")
print(FTemp,"F")
CTemp = CTemp+5
main()
for celsius in range (0,101,5):
print("Celsius:",celsius, "Fahrenheit:",float(1.8*celsius+32)) |
import time
from random import randint
from datetime import timedelta
class Tamagotchi:
def __init__(self, name):
self.name = name
self.kleur = self.kieskleur()
def kieskleur (self):
Kleuren = ["rood","groen","bruin"]
GekozenKleur = Kleuren[randint(0,2)]
return GekozenKleur
def geboorte (self):
'''de hond wordt geboren en krijgt een geboortedatum.
De gebruiker krijgt de mogelijkheid om een naam te kiezen'''
self.geboortedatum = time.time()
def wakeup (self):
print(f"{self.name} is geboren")
def leeftijd (self):
leeftijd = time.time() - self.geboortedatum
return leeftijd
def hondenjaren (self):
hondenjaren = (time.time() - self.geboortedatum) * 7
return hondenjaren
def info (self):
infoleeftijd = timedelta(seconds = self.leeftijd())
infoleeftijdhondenjaren = timedelta(seconds = self.hondenjaren())
print("{} is {} seconden oud".format(self.name, infoleeftijd.seconds))
print("maar voor {} voelt dit als {} seconden oud".format(self.name, infoleeftijdhondenjaren.seconds))
print("Hoe wil jij jou tamagotchi noemen ? ")
Tamaname = input()
hond = Tamagotchi(Tamaname)
hond.geboorte()
hond.wakeup()
hond.info()
'''
hondjaren
geboorte functie uitbreiden, merk en zo
soort en kleur random
een beetje denken over de spelregels.
random()
''' |
class Scene:
"""
A scene has a name and a detector function, which returns true if the scene is
detected, false otherwise.
Attributes:
name (string): A descriptive name of what the scene consists of.
detector (function): A function that checks if that scene is present.
"""
def __init__(self, name, detector):
self.name = name
self.detector = detector
def detected(self, params):
detected, params = self.detector(params)
return (detected, params) |
class BaseAlgorithm:
""" Abstract base class meant to be inherited from to implement new algorithms.
Subclasses must implement the schedule method.
Attributes:
max_recompute (int): Maximum number of periods between calling the scheduling algorithm even if no events occur.
If None, the scheduling algorithm is only called when an event occurs. Default: None.
"""
def __init__(self):
self._interface = None
self.max_recompute = None
def __repr__(self):
arg_str = ", ".join([f"{key}={value}" for key, value in self.__dict__.items()])
return f"{self.__class__.__name__}({arg_str})"
@property
def interface(self):
""" Return the algorithm's interface with the environment.
Returns:
Interface: An interface to the enviroment.
Raises:
ValueError: Exception raised if interface is accessed prior to an interface being registered.
"""
if self._interface is not None:
return self._interface
else:
raise ValueError(
"No interface has been registered yet. Please call register_interface prior to using the"
"algorithm."
)
def register_interface(self, interface):
""" Register interface to the _simulator/physical system.
This interface is the only connection between the algorithm and what it is controlling. Its purpose is to
abstract the underlying network so that the same algorithms can run on a simulated environment or a physical
one.
Args:
interface (Interface): An interface to the underlying network whether simulated or real.
Returns:
None
"""
self._interface = interface
def schedule(self, active_evs):
""" Creates a schedule of charging rates for each ev in the active_evs list.
NOT IMPLEMENTED IN BaseAlgorithm. This method MUST be implemented in all subclasses.
This method returns a schedule of charging rates for each
Args:
active_evs (List[EV]): List of EV objects which are currently ready to be charged and not finished charging.
Returns:
Dict[str, List[float]]: Dictionary mapping a station_id to a list of charging rates. Each charging rate is
valid for one period measured relative to the current period, i.e. schedule['abc'][0] is the charging
rate for station 'abc' during the current period and schedule['abc'][1] is the charging rate for the
next period, and so on. If an algorithm only produces charging rates for the current time period, the
length of each list should be 1. If this is the case, make sure to also set the maximum resolve period
to be 1 period so that the algorithm will be called each period. An alternative is to repeat the
charging rate a number of times equal to the max recompute period.
"""
raise NotImplementedError
def run(self):
""" Runs the scheduling algorithm for the current period and returns the resulting schedules.
Returns:
See schedule.
"""
schedules = self.schedule(self.interface.active_evs)
return schedules
|
#!/usr/bin/python3
""" printing a text """
def text_indentation(text):
""" This method prints a text with 2 new lines after each of these
characters: ., ? and : and there should be no space at the begining
or at the end of each printed line.
Args:
text (str): parameter
Raises:
TypeError: if text is not a str
"""
if type(text) is not str:
raise TypeError("text must be a string")
check = 1
for char_reader in text:
if check != 0 and char_reader == ' ':
continue
check = 0
print(char_reader, end="")
if char_reader in [':', '?', '.']:
check = 1
print("\n")
|
#!/usr/bin/python3
for a in range(97, 123):
if a in [101, 113]:
continue
print("{:c}".format(a), end='')
|
#!/usr/bin/python3
for decimal in range(0, 100):
if decimal < 99:
print("{:02d},".format(decimal), end=' ')
print("{}".format(decimal))
|
#!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
lastDigit = number % 10
if number < 0:
lastDigit = abs(number) % 10 # absolute value first for negative nums
lastDigit = -lastDigit
else:
lastDigit = number % 10
print("Last digit of", number, "is", lastDigit, "and is", end=" ")
if lastDigit > 5:
print("greater than 5")
elif lastDigit == 0:
print("0")
elif lastDigit < 6:
print("less than 6 and not 0")
|
#!/usr/bin/python3
"""
Python script that takes in a letter and sends a POST request to
http://0.0.0.0:5000/search_user with the letter as a parameter.
The letter must be sent in the variable q
If no argument is given, set q=""
If the response body is properly JSON formatted and not empty,
display the id and name like this: [<id>] <name>
Otherwise:
Display Not a valid JSON if the JSON is invalid
Display No result if the JSON is empty
Packages: only requests and sys
Tested on container running on port 5000, json random generated.
"""
import requests
from sys import argv
if __name__ == "__main__":
q = ""
if len(argv) > 1:
q = argv[1]
letter = {'q': q}
req = requests.post('http://0.0.0.0:5000/search_user', letter)
try:
get_json = req.json()
if get_json == {}:
print("No result")
else:
print("[{}] {}".format(get_json.get('id'), get_json.get('name')))
except:
print("Not a valid JSON")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.