text stringlengths 37 1.41M |
|---|
def carga():
art=[]
pre=[]
for x in range(5):
valor1=raw_input('Nombre del articulo: ')
art.append(valor1)
valor2=float(input('Precio: '))
pre.append(valor2)
return [art,pre]
def imprimir(v1,v2):
print('Listado de productos')
print(v1,v2)
def imprimir_mayor(v1,v2):
print('Precio mayor')
mayor = v2[0]
r = 0
for x in range(1,len(v2)):
if v2[x] > mayor:
mayor = v2[x]
r = r + 1
print(v1[r],v2[r])
def precio_menor(v1,v2,menor):
print('Precio menor a',menor)
for x in range(len(v2)):
if v2[x] <= menor:
print(v1[x],v2[x])
art, pre = carga()
imprimir(art,pre)
imprimir_mayor(art,pre)
menor = float(input('Precio: '))
precio_menor(art,pre, menor)
|
cont = 0
valor = int(input('Valor del 1 al 10: '))
for r in range(12):
cont = cont + valor
print(cont) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from copy import deepcopy
AVAILABLE_COLORS = {
"y": "yellow",
"b": "blue",
"g": "green",
}
# If the received color is one of the available colors,
# this function will return a recipe with color ingrediant
# and apropriate instructions. Otherwise, the unchanged recipe will be returned.
def add_color(recipe, color):
colored_recipe = deepcopy(recipe)
if color.lower() in AVAILABLE_COLORS:
color_ingredient = {
"name": "%s food coloring" % AVAILABLE_COLORS[color.lower()],
"quantity": 3,
"measure": "teaspoons",
"properties": ["liquid"],
}
instructions = colored_recipe["instructions"]
colored_recipe["ingredients"].append(color_ingredient)
instructions.insert(len(instructions) - 1, "Add the food coloring.")
return colored_recipe
|
from challenge import *
from Tests_December_1_2017a import *
def inverse_captcha(input):
""" This function takes of string of numbers. The function returns the sum of the matching indices and assumes the list is circular."""
index_in_input = 0
next_index_in_input = index_in_input + 1
sum_of_matched = 0
last_index_in_input = input[-1]
for item in range(0,len(input)-1):
if input[index_in_input] == input[next_index_in_input]:
sum_of_matched = int(input[index_in_input]) + sum_of_matched
index_in_input += 1
if (next_index_in_input + 1) != last_index_in_input:
next_index_in_input += 1
else:
# print("ELSE block ran")
index_in_input += 1
next_index_in_input += 1
if input[0] == last_index_in_input:
sum_of_matched = sum_of_matched + int(last_index_in_input)
return sum_of_matched
challenge = list(str(challenge))
print(inverse_captcha(challenge))
|
def cheker_N():
while True:
try:
argument = int(input())
if (argument > 0 ):
break
except ValueError:
print('НАСТУПНОГО РАЗУ ВВЕДІТЬ НАТУРАЛЬНЕ ЧИСЛО:')
continue
return argument
def cheker_X():
while True:
try:
argument = float(input())
break
except ValueError:
print('НАСТУПНОГО РАЗУ ВВЕДІТЬ ЧИСЛО:')
continue
return argument
def calculate():
sum = 0
for i in range(1,n+1):
sum += (x**i)/(x-n)
return sum
print("""ЛАБОРАТОРНА РОБОТА №1
ВИКОНАВ СТУДЕНТ 1 КУРСУ ГРУППИ КМ-84
МИСАК ЮРІЙ
ПРОГРАМУВАННЯ ЦИКЛІЧНИХ АЛГОРИТМІВ
""")
while True:
print("Введіть: N")
n = cheker_N()
print("Введіть: X")
x = cheker_X()
if int(x) == n :
print("N НЕ ПОВИННО = X")
continue
print(calculate()) |
# -*- coding: utf-8 -*-
import sys
codes = input()
pre = ''
for code in codes:
if pre == code:
print('Bad')
sys.exit()
pre = code
print('Good')
|
"""
Author:: hossain mishu
Date:5/3/2020
Follow:: https://github.com/Hossain-Mishu
"""
class Queue:
'''#to initialized a queue constractor just make an instance of Queue class.'''
#initializing constructor FUNCTION
def __init__(self):
self.items = []
#METHODE for adding item in Queue
def enqueue(self,item):
self.items.append(item)
#METHODE for geting item from Queue
def dequeue(self):
return self.items.pop(0)
#METHODE for checking if Queue is empty.
def is_empty(self):
if self.items==[]:
return True
return False
def great():
print('\n')
print('\n')
print(' '+'*******************<>*******************')
print(' '+'*******************<>*******************')
print(' '+'WELCOME TO PATIENTS MANAGMENT SYSTEM')
print(' '+'*******************<>*******************')
print(' '+'Created by HOSSAIN MISHU')
print(' '+'*******************<>*******************')
print(' '+'*******************<>*******************')
print('\n')
if __name__=='__main__':
import sys
import time
import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty('voice',voices[1].id)
def say(text):
engine.say(text)
engine.runAndWait()
box = Queue()
great()
say('welcome to patients management system')
say("fun on behalf creator hossain mishu...this funny system is implimenting Queue data structure...let's fun..")
print(' '+'Press 1 to admite patients.')
say('Press one to admite patients.')
print(' '+'Press 2 to call patients.')
say('Press two to call patients')
print(' '+'Press 0 to close todays service.')
say('Press zero to close todays service')
print(' '+'*******************<>*******************')
while True:
n = int(input())
print(' '+'*******************<>*******************')
if n ==1:
d = {}
say('Enter token number')
id = input(' '+'Enter token number:')
say('Enter patients name')
name = input(' '+'Enter patients name:')
say('Enter counter number')
counter = input(' '+'Enter counter number:')
d['id']=id
d['name']=name
d['counter']=counter
try:
box.enqueue(d)
print('\n')
print(' '+'*******************<>*******************')
print(' '+'Successful!!..patients is admitted.')
print(' '+'*******************<>*******************')
print('\n')
say('Successfull...patients is admited')
except:
say('Sorry!!!..cant admite now..servive is interrepted.')
elif n == 2:
if box.is_empty()==True:
print(' '+'Can\'t get item from empty database.')
say("Can\'t get item from empty database..")
print(' '+'Add some patients first')
say('add some patients first')
print(' '+'*******************<>*******************')
time.sleep(1)
else:
d = box.dequeue()
print(' '+'id = {}'.format(d['id']))
say('id...'+d['id'])
print(' '+'name = {}'.format(d['name']))
say('Name...'+d['name'])
print(' '+'Please go to counter {}.'.format(d['counter']))
say('Please go to counter...'+d['counter'])
print(' '+'*******************<>*******************')
print('\n')
elif n == 0:
print(' '+'Thanks for being with us..please come again.')
say('Thanks for being with us...please come again')
print(' '+"you can download this funny system source code from github.")
say("you can download this funny system source code from github.")
print(' '+"Visit: https://github.com/Hossain-Mishu/patient-management-system")
say("visit https://github.com/Hossain-Mishu/patient-management-system...use git clone command or download the zip file")
say('have fun...')
print(' '+'*******************<>*******************')
time.sleep(2)
sys.exit(1)
else:
print(' '+'Invalid number pressed...try again..')
say('Invalid number pressed..try again')
say('you can just chose betwen 1...2...or...0')
time.sleep(1)
print(' '+'*******************<>*******************')
|
def quick_sort(the_list):
if len(the_list) < 2:
return the_list
else:
mid_value = the_list[0]
less = [item for item in the_list[1:] if item < mid_value]
great = [item for item in the_list[1:] if item >= mid_value]
return quick_sort(less) + [mid_value] + quick_sort(great)
print (quick_sort([34,1,65,77,1,3,54,8,0,3,45,8,99,22])) |
"""
COMP30024 Artificial Intelligence
Semester 1, 2021
Project Part B
David Peel 964682
Kevin Russell 1084088
"""
from state.game_state import GameState
from strategy.minimax import minimax_paranoid_reduction
from strategy.evaluation import greedy_choose
from strategy.book import book_first_four_moves
from time import time
class Player:
def __init__(self, player):
"""
Called once at the beginning of a game to initialise this player.
Set up an internal representation of the game state.
The parameter player is the string "upper" (if the instance will
play as Upper), or the string "lower" (if the instance will play
as Lower).
"""
self.game_state = GameState(is_upper=(player == "upper"))
self.game_state.pruning_is_aggressive = True
self.start_time = self.end_time = self.time_consumed = 0
def action(self):
"""
Called at the beginning of each turn. Based on the current state
of the game, select an action to play this turn.
"""
self.start_timer()
if self.game_state.turn < 4:
result = book_first_four_moves(self.game_state)
elif self.time_consumed < 59:
result = minimax_paranoid_reduction(self.game_state)
else:
result = greedy_choose(self.game_state)
self.end_timer()
return result
def update(self, opponent_action, player_action):
"""
Called at the end of each turn to inform this player of both
players' chosen actions. Update your internal representation
of the game state.
The parameter opponent_action is the opponent's chosen action,
and player_action is this instance's latest chosen action.
"""
self.game_state.update(player_action, opponent_action)
def start_timer(self):
self.start_time = time()
def end_timer(self):
self.end_time = time()
self.time_consumed += self.end_time - self.start_time
|
"""
COMP30024 Artificial Intelligence
Semester 1, 2021
Project Part B
David Peel 964682
Kevin Russell 1084088
"""
from heapq import heappush
from state.game_state import GameState
from state.token import defeats
from state.location import distance
"""
Generic components of the greedy implementation
"""
def opponent_distance_scores(game_state: GameState):
"""
Return a heap of type [(-distance_score, move)] such that popping from the heap will provide the
state with the highest distance score.
"""
queue = []
for friend_move in game_state.next_friend_transitions():
score = opponent_distance_score(game_state, friend_move, game_state.next_enemy_transitions())
heappush(queue, (-score, friend_move))
return queue
def opponent_distance_score(game_state: GameState, friend_move, next_enemy_moves):
"""
Return the average score for a particular friend move and all possible enemy moves
"""
avg_score = 0
for enemy_move in next_enemy_moves:
new_state = game_state.update(enemy_move, friend_move)
avg_score += individual_distance_score(new_state)
avg_score /= len(next_enemy_moves)
return avg_score
def individual_distance_score(new_state: GameState):
"""
Return the distance score for a particular game state.
For every enemy, the nearest friend that can defeat it is found (if it exists).
The distance from the two pieces is calculated and a score is derived.
Scores for individual pairs range from 0 to 8.
Higher scores mean closer together pieces.
"""
max_dist = 8
score = 0
for (enemy_t, enemy_loc) in new_state.enemies:
min_dist = max_dist
for(friend_t, friend_loc) in new_state.friends:
if defeats(friend_t, enemy_t):
curr_dist = distance(friend_loc, enemy_loc)
if curr_dist < min_dist:
min_dist = curr_dist
score += max_dist - min_dist
return score
|
range_low = "264793"
range_high = "803935"
positions = [0,1,2,3,4]
def check_doubles(code):
for pos in positions:
if code.count(code[pos])==2:
return(True)
return(False)
def check_increasing(code):
for pos in positions:
if code[pos] > code[pos+1]:
return(False)
return(True)
#main process
search_lis = []
numbers_to_check = int(range_high)-int(range_low)
print(f"Remaining combinations: {numbers_to_check}")
#make the original list
for code in range(int(range_low),int(range_high)):
code = str(code)
if check_doubles(code) and check_increasing(code):
search_lis.append(code)
numbers_to_check -= 1
if numbers_to_check%100 == 0:
print(f"Remaining combinations: {numbers_to_check}")
print(f"Total number of codes = {len(search_lis)}")
|
money = input("How much is your money on hand?")
amount = input ("How much is the iPhone X?")
print ("You can avail",money/amount)
print (" iPhone X, and will have an extra" , money%amount," pesos")
print ("You'll need", amount-(money%amount)," pesos to avail another iPhone X.")
|
import re
import random
stepCounter = 0
board = ({1: {1:" ", 2:" ", 3:" "},
2: {1:" ", 2:" ", 3:" "},
3: {1:" ", 2:" ", 3:" "}})
def whosFirst():
if random.randint(0, 1) == 0:
return 'O'
else:
return 'X'
def checkEmpty(board, row, col):
if board[row][col] == " ":
return True
return False
def drawBoard(board):
print(' ' + board[1][1] + ' | ' + board[1][2] + ' | ' + board[1][3])
print('-----------')
print(' ' + board[2][1] + ' | ' + board[2][2] + ' | ' + board[2][3])
print('-----------')
print(' ' + board[3][1] + ' | ' + board[3][2] + ' | ' + board[3][3])
def checkRows(board):
for key in board:
rvals = list(set(board[key].values()))
if len(rvals) == 1 and rvals[0] != " ":
return "real " + str(key)
return 0
def checkCols(board):
for col in range (1,3):
colum = [board[1][col], board[2][col], board[3][col]]
cvals = list(set(colum))
if len(cvals) == 1 and cvals[0] != " ":
return "veerg " + str(col)
return 0
def checkDiag(board):
diag1 = list(set([board[1][1], board[2][2], board[3][3]]))
diag2 = list(set([board[1][3], board[2][2], board[3][1]]))
if len(diag1) == 1 and diag1[0] != " ":
return "diagonaalselt ülevalt vasakult alla paremale"
if len(diag2) == 1 and diag2[0] != " ":
return "diagonaalselt alt vasakult ülesse paremale"
return 0
def checkIfFull(board):
for x in range(1, 4):
for y in range(1, 4):
if (checkEmpty(board, x, y)):
return False
return True
def checkIfkWinner(board):
if not (checkDiag(board) == 0):
return checkDiag(board)
if not (checkRows(board) == 0):
return checkRows(board)
if not (checkCols(board) == 0):
return checkCols(board)
turn = whosFirst()
print ("Mänguplats:")
drawBoard(board)
print("Mängujuhend: Sisesta rida ja veerg kujul RIDA-VEERG [3-2].")
while True:
insert = input(f"Mängija {turn} kord, sisesta uus rida-veerg [1-2].")
if len(insert) == 0:
break
stepCounter += 1
match = re.match('^[1-3]-[1-3]$', insert)
row = int(insert[0])
col = int(insert[2])
if match == None:
print('Sisend ei vasta vormingule, palun proovi uuesti.')
elif not(checkEmpty(board, row, col)):
print('See koht on juba võetud, proovi uuesti.')
else:
board[row][col] = turn
drawBoard(board)
if (checkIfkWinner(board)):
print (f"Võitis mängija {turn}, {checkIfkWinner(board)}.")
break
if (checkIfFull(board)):
print (f"Plats sai täis, jäite viiki.")
break
if turn == 'O':
turn = 'X'
else:
turn = 'O'
|
print('Grocery list:')
print('"add" to add items and "view" to view list')
grocery_list = []
while True:
command = input('Enter command: ')
if command == 'add':
to_add = input('Enter new item: ')
grocery_list.append(to_add)
# elif stands for "else if"
elif command == 'view':
for i in range(len(grocery_list)):
print(grocery_list[i])
else:
print('Invalid command')
|
"""
Program for a challenge at hackerrank.com
We're going to make our own Contacts application! The application must perform two types of operations:
add name, where name is a string denoting a contact name. This must store name as a new contact in the application.
find partial, where partial is a string denoting a partial name to search the application for.
It must count the number of contacts starting with partial and print the count on a new line.
"""
class Node:
"""Node class"""
def __init__(self):
self.children = {}
self.valid = 0
# store the number of children so we can count the number of
# valid words faster
self.num_children = 0
class Trie:
""" a trie class, that allows insertion and lookup """
def __init__(self):
self.root = Node()
def insert(self, name):
''' (self, str) -> None
inserts a name as a trie
'''
current = self.root
for letter in name:
if current.children.get(letter) == None:
node = Node() # create a new node
current.children[letter] = node
# update the number of children
current.num_children += 1
current = current.children[letter]
current.valid = 1
def search(self, name):
"""(self, str) -> int
searches based on a string and returns
the number of children that belong to the
partial string """
result = 0
current = self.root
for letter in name:
find_node = current.children.get(letter)
if find_node:
current = find_node
else:
return 0
# we found the right node
return current.num_children + current.valid
if __name__ == "__main__":
# main function
tries = Trie()
num = int(input().strip('\n'))
for i in range(num):
command = input().split()
if command[0] == "add":
tries.insert(command[1])
elif command[0] == "find":
print(tries.search(command[1]))
|
#%%
# Import dependencies
import pandas as pd
# %%
file_path = "./Resources/shopping_data.csv"
df_shopping = pd.read_csv(file_path, encoding="ISO-8859-1")
df_shopping.head(5)
# %%
# Look at what data we have
df_shopping.columns
df_shopping.dtypes
# %%
# Find null values
for column in df_shopping.columns:
print(f"Column {column} has {df_shopping[column].isnull().sum()} null values")
# %%
# Drop null values
df_shopping = df_shopping.dropna()
# %%
# Find duplicate entries
print(f"Duplicate entries: {df_shopping.duplicated().sum()}")
# %%
# Remove the CustomerID Column
df_shopping.drop(columns=["CustomerID"], inplace=True)
df_shopping.head()
# %%
# Transform string column
def change_string(member):
if member == "Yes":
return 1
else:
return 0
df_shopping["Card Member"] = df_shopping["Card Member"].apply(change_string)
df_shopping.head()
# %%
# Transform annual income
df_shopping["Annual Income"] = df_shopping["Annual Income"] / 1000
df_shopping.head()
# %%
# Rename columns
df_shopping = df_shopping.rename(columns={"Card Member": "Card_Member", "Annual Income": "Annual_Income", "Spending Score (1-100)": "Spending_Score"})
df_shopping.head()
# %%
# Saving cleaned data
file_path = "./Resources/shopping_data_cleaned.csv"
df_shopping.to_csv(file_path, index=False)
# %%
|
print('Welcome to the Ramasedi Central Bank')
Bank_account_balance = 1000
trials = 0
while trials <= 3:
pin = int(input(' Enter your banking pin '))
if pin == 1234:
print('you have entered your pin correctly')
print('press 1 for balance ')
print('press 2 to withdraw cash')
print('press 4 to exit')
withdrawal_amount = int(input('Enter withdrawal amount '))
else:
print('pin is incorrect, please take your card and try again... ')
break
service = int(input('how can we help '))
if service == 1:
print(f'you have P{Bank_account_balance}.00 in your bank account.')
elif service == 2:
print(withdrawal_amount)
break
while withdrawal_amount > Bank_account_balance:
print('sorry, you do not have that amount of money in your bank account...')
break
if withdrawal_amount <= 0:
print('please enter a valid amount')
Bank_account_balance -= withdrawal_amount
print(Bank_account_balance)
|
#High scores
scores = []
choice = None
while choice != 0:
print(
"""
High scores
0- exit
1- show scores
2- add a score
3- delete a score
4-sort scores
""")
choice = input("Choice: ")
print()
#exit
if choice == 0:
print('Good-bye.')
elif choice == 1: #list high score table
print('High Scores')
for score in scores:
print(score)
elif choice == 2: #add a score
score = int(input('What score did you get?: '))
scores.append(score)
elif choice == 3: #remove a score
score = int(input('Remove which score?: '))
if score in scores:
scores.remove(score)
else:
print(score, 'isn\'t in the high scores list.')
elif choice == 4: #sort scores
scores.sort(reverse=True)
else: #some unknown choice
print('Sorry but', choice, 'isn\'t a valid choice.')
print('Scores: ', scores)
|
# -*- coding:utf-8 -*-
total = 0
a = '1.23,2.4,3.123'
for c in a:
if c.isnumeric():
total = total + int(c)
print(total)
|
# -*- coding:utf-8 -*-
def getGrades(fname):
try:
gradesFile = open(fname, 'r')
except IOError:
raise ValueError('getGrades could not open ', fname)
grades = list()
for line in gradesFile:
try:
grades.append(float(line))
except:
raise ValueError('Unable to convert line to float ')
return grades
if __name__ == "__main__":
try:
grades = getGrades('quiz1grades.txt')
grades.sort()
median = grades[len(grades) // 2]
print('Median grade is ', median)
except ValueError as errorMsg:
print('Whoops.', errorMsg)
|
# -*- coding:utf-8 -*-
from m100401 import mergeSort
def lastNameFirstName(name1, name2):
arg1 = name1.split(' ')
arg2 = name2.split(' ')
if arg1[1] != arg2[1]:
return arg1[1] < arg2[1]
else:
return arg1[0] < arg2[0]
def firstNameLastName(name1, name2):
arg1 = name1.split(' ')
arg2 = name2.split(' ')
if arg1[0] != arg2[0]:
return arg1[0] < arg2[0]
else:
return arg1[1] < arg2[1]
if __name__ == "__main__":
L = ['Tom Brady', 'Eric Grimson', 'Gisele Bundchen']
newL = mergeSort(L, lastNameFirstName)
print('Sorted by last name=', newL)
newL = mergeSort(L, firstNameLastName)
print('Sorted by first name=', newL)
L = [3, 5, 2]
D = {'a': 12, 'c': 5, 'b': 'dog'}
print(sorted(L))
print(L)
L.sort()
print(L)
print(sorted(D))
# D.sort()
L = [[1, 2, 3], (3, 2, 1, 0), 'abc']
# key=xxx stable sort
print(sorted(L, key=len, reverse=True))
|
'''student=['666','555','mail']
print(student[-1])
student.append('51zxw')
print(student)
student.insert(0,'hello')
print(student)
student.pop (1)
print(student)
#元组(tuple)
course=('chinese','English','math','computer')
print(course)
print(course[-1])
print(course[1:3])
print(course[:2])
print(len(course))
score=(99,66,55,84,78,64,99)
print(max(score))
print(min(score))
#python字典
student={1:'jack',2:'bob',3:'marry',4:'micle' }
print(student[3])
student[5]='huqiao'
print(student)
student[2]='Harry'
print(student)
del student[2]
print(student)
student.clear()
print(student)
del student
print(student)'''
#条件判断
score=100
if score>=80:
print("score is A")
elif score>=60:
print("score is B")
else:
print("score is C")
#循环语句
student=['jack','bob','marry','micle']
for stu in student:
print(stu)
sum=0
for i in range(11):
sum+=i
print(sum)
n=10
while n>0:
n-=1
print(n)
print("over!") |
def CountDigit(number, digit ):
count = 0
for i in str(number):
if i.isalnum():
if int(i) == digit:
count+=1
return count
number,digit=input().split()
number=int(number)
digit=int(digit)
count=CountDigit(number,digit )
print("Number of digit 2 in "+str(number)+":",count) |
class Entity:
transparent = "T" # This character is ignored when drawing the ASCII art
def __init__(self, x, y, ASCII, overworldChar):
self.x = x
self.y = y
# defines the origin at the top left of the ASCII art. Example of 3x3 ASCII art below. "O" is the position of the x, y values
# O X X
# X X X
# X X X
self.ASCII = ASCII #Arena - Array of Strings (2D)
self.overworldChar = overworldChar # single char
def draw(self, screen, ASCII):
"""
"Draws" the Entity's ASCII on the screen starting from x, y and drawing to the right and down
:param screen:
:param ASCII: either arena or overworld ASCII
"""
for i in range(0, len(ASCII)):
for j in range(0, len(ASCII[i])):
if ASCII[i][j] != Entity.transparent: # ignore any transparent values currently "T"
try:
screen.buffer[self.y + i][self.x + j] = ASCII[i][j]
except IndexError:
print("out of bounds")
def drawArena(self, screen):
"""
draws the Arena ASCII
:param screen:
"""
self.draw(screen, self.ASCII)
def drawOverworld(self, screen):
"""
Draws the Overworld ASCII
:param screen:
"""
self.draw(screen, self.overworldChar)
|
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class InvertBT:
# def __init__(self, root):
# self.root = root
def invertBinaryTree(self, root):
def helper(root):
if not root:
return None
left = root.left
right = root.right
root.left, root.right = right, left
helper(left)
helper(right)
return root
return helper(root)
'''
4
/ \
2 7
/ \ / \
1 3 6 9
'''
if __name__ == "__main__":
def printInorder(root):
if root:
printInorder(root.left)
print(root.val)
printInorder(root.right)
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(7)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(6)
root.right.right = TreeNode(9)
invertbt = InvertBT()
invertedRoot = invertbt.invertBinaryTree(root)
printInorder(invertedRoot)
|
class Solution:
# nums: List[int]
def searchInsert(self, nums, target):
if len(nums) == 1:
if target > nums[0]:
return 1
return 0
low, high = 0, len(nums)-1
while low < high:
mid = (high+low)//2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid
if target <= nums[high]:
return high
return high+1
target = 2
nums = [1,3,5,6]
solution = Solution()
print(solution.searchInsert(nums, target))
|
""" Reference:--https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/"""
class Node:
def __init__(self,key):
self.value=key
self.left=None
self.right=None
def __str__(self):
return str(self.value)
def insert0(root,node):
current_node=root
if node.value < root.value:
if root.left==None:
root.left=node
else:
current_node=current_node.left
insert0(current_node,node)
else:
if root.right==None:
root.right=node
else:
current_node=current_node.right
insert0(current_node,node)
def insert(root,node):
#if root is None:
#root=node
#else:
if node.value < root.value:
if root.left==None:
root.left=node
else:
insert(root.left,node)
else:
if root.right==None:
root.right=node
else:
insert(root.right,node)
def maxdepth(root):#each time getHeight will give height of node (leftc/rightc/root) where node can be seen as a root.
if root==None:
return -1
else:#just mimic the tree and assign no to left and right child according to depth at each level .
lDepth=maxdepth(root.right)
rDepth=maxdepth(root.left)
if (lDepth > rDepth):
return lDepth+1
else:
return rDepth+1
def getHeight(root):#each time getHeight will give height of node (leftc/rightc/root) where node can be seen as a root.
if root == None:
return -1
else:
return 1 + max(getHeight(root.left), getHeight(root.right))#just mimic the tree and assign no to left and right child according to depth at each level .
def level(root,key):
level=0
while(root.value!=key):
if key<root.value:
root=root.left
level+=1
elif key>root.value:
root=root.right
level+=1
return level
def inorder(root):
if root:
inorder(root.left)
print(root.value)
inorder(root.right)
# Driver program to test the above functions
# Let us create the following BST
# 50
# / \
# 30 70
# / \ / \
# 20 40 60 80
# 8
# / \
# 6 11
# / \ / \
# 5 7 10 12
# / \
# 9 13
"""r = Node(50)
insert(r,Node(30))
insert(r,Node(20))
insert(r,Node(40))
insert(r,Node(70))
insert(r,Node(60))
insert(r,Node(80))"""
r = Node(8)
insert(r,Node(6))
insert(r,Node(5))
insert(r,Node(7))
insert(r,Node(11))
insert(r,Node(12))
insert(r,Node(13))
insert(r,Node(10))
insert(r,Node(9))
# Print inoder traversal of the BST
inorder(r)
print("max_height")
print(maxdepth(r))
print(level(r,10))
|
class Min_heap:
def __init__(self,maxsize):
self.size=0
self.maxsize=maxsize
self.arr=[0]*(maxsize+1)
self.front=0
def parent(self,pos):
return pos-1//2
def left_child(self,pos):
return pos*2+1
def right_child(self,pos):
return pos*2+2
def insert(self,ele):
if self.size<self.maxsize:
i=self.size
self.arr[i]=ele
self.size+=1
def heapify(self,length,front):
smallest=front
left=self.left_child(smallest)
right=self.right_child(smallest)
if left<length and self.arr[left]<self.arr[smallest]:
smallest=left
if right<length and self.arr[right]<self.arr[smallest]:
smallest=right
if smallest!=front:
(self.arr[smallest],self.arr[front])=(self.arr[front],self.arr[smallest])
self.heapify(length,smallest)
def heapsort(self,length):
for i in range(self.size//2,-1,-1):
self.heapify(length,i)
for i in range(self.size-1,-1,-1):
self.arr[self.front],self.arr[i]=self.arr[i],self.arr[self.front]
self.heapify(i,self.front)
def Print(self):
for i in range(0, (self.size//2)):
print(" PARENT : "+ str(self.arr[i])+" LEFT CHILD : "+
str(self.arr[2 * i + 1])+" RIGHT CHILD : "+
str(self.arr[2 * i + 2]))
if __name__ == "__main__":
print('The minHeap is ')
minHeap = Min_heap(6)
minHeap.insert(9)
minHeap.insert(5)
minHeap.insert(13)
minHeap.insert(12)
minHeap.insert(45)
minHeap.insert(16)
minHeap.Print()
minHeap.heapsort(6)
print("heapsort")
minHeap.Print()
|
from turtle import Turtle
class Ball(Turtle):
def __init__(self):
super().__init__()
self.shape('circle')
self.color('white')
self.move_speed = 0.1
self.penup()
self.x = 10
self.y = 10
def move(self):
self.move_speed = 0.01
new_x = self.xcor() + self.x
new_y = self.ycor() + self.y
self.goto(new_x, new_y)
def collide(self, something):
try:
top_window = (something.window_height() - 20) / 2
bottom_window = (something.window_height() - 20) / - 2
if self.ycor() >= top_window or self.ycor() <= bottom_window:
return True
except AttributeError:
if something.xcor() == 350:
if self.distance(something) < 20 or \
self.distance(something) < 80 and \
self.xcor() >= something.xcor() - 20:
return True
if something.xcor() == -350:
if self.distance(something) < 20 or \
self.distance(something) < 80 and \
self.xcor() <= something.xcor() + 20:
return True
def bounce_walls(self):
self.move_speed = 0.1
self.y *= -1
def bounce_tables(self):
self.move_speed = 0.1
self.x *= -1
def touch_empty_space(self):
if self.xcor() >= 390 or self.xcor() <= -390:
return True
def start_game_again(self):
self.move_speed = 0.1
self.goto(0, 0)
self.bounce_tables() |
"""
gaussian_blur_image.py
This code will use the function gaussianblur(src, ksize, sigmaX)
to blur an image with an intesity of the gaussan kernel, which
is affected by an equation where the sigma affects the blurriness.
When only the x sigma is specified, the y sigma is given the same
value. Same parameters apply as in blur() except the sigma. If both
sigmas are zeros, they are computed from ksize.width and ksize.heigh.
author: Miguel Benavides, Laura Martinez
date created: 26 Marz 2018
universidad de monterrey
"""
# import required libraries
import numpy as np
import matplotlib.pyplot as plt
import cv2
# read image
img_name = 'cavalo_motorizado.jpg'
img = cv2.imread(img_name)
# verify that image `img` exist
if img is None:
print('ERROR: image ', img_name, 'could not be read')
exit()
# blur image using `cv2.blur()`
kernel_size = (11,11)
blurred_image = cv2.GaussianBlur(img, kernel_size, 0)
# plot input and blurred images
plt.figure(1)
plt.imshow(img)
plt.title('Input image')
plt.xticks([])
plt.yticks([])
plt.figure(2)
plt.imshow(blurred_image)
plt.title('Output image using cv2.blur(%i,%i)' % (kernel_size[0], kernel_size[1]))
plt.xticks([])
plt.yticks([])
plt.show()
|
dict = {'name': 'Bob', 'ref': 'Python', 'sys': 'Win'}
print('Dictionary: ', dict)
print( '\nReference:', dict['ref'])
print( '\nKeys:', dict.keys())
del dict['name']
dict['user'] = 'Tom'
print('Dictionary: ', dict)
print( '\nIs there a name key?:', 'name' in dict)
|
# Initialize a variable with a user-specified value
user = input( 'I am Python. What is your name? : ')
# Output a string and a variable value
print( 'Welcome', user)
# Initialize another variable with a user-specified value
lang = input( 'Favourite programming language? : ')
# Output a string and a variable value
print( lang , 'Is' , 'Fun' ,sep = ' * ' , end = '!\n')
|
"""A back-end module to use with Google Authenticator mobile app, written in Python 3
An implementation of two factor authentication provided by Google Authenticator mobile app
More info on the app: http://en.wikipedia.org/wiki/Google_Authenticator
Allows to set up the app to work with your user accounts via manual input or QR code, and also to verify codes supplied
by users. Both HOTP (incremented counter based) and TOTP (time based) authentication modes are supported.
RFC4226 implementation code based on https://github.com/gingerlime/hotpie/blob/master/hotpie.py
Author: Yuriy Akopov (akopov@hotmail.co.uk)
Date: 2013-07-05
Usage example:
import google_authenticator
# when a new user is registered or signed up for 2 factor authentication, returned value should be stored
secret = google_authenticator.new_secret()
# build url for QR code image so user can set up their Google Authenticator
url = google_authenticator.qr_url(google_authenticator.MODE_TOTP, secret, 'John Doe', 'Acme', 200)
# then on login attempt, where code is supposedly Google Authenticator code supplied by user
# mode should be the same as supplied to qr_url above
if google_authenticator.auth(google_authenticator.MODE_TOTP, secret, code):
your_login_func() # authentication successful
If run directly, module will unit test itself.
"""
import base64
import random
import time
import hmac
import hashlib
import struct
from urllib.parse import quote as urlquote, urlencode
"""authentication modes"""
MODE_TOTP = 'totp' # changing part of the seed is going to be current time
MODE_HOTP = 'hotp' # changing part of the seed is going to be counter incremented on every login attempt
_modes = (MODE_TOTP, MODE_HOTP)
_TOTP_PRECISION = 30 # length of the "one tick" interval (in which system produces the same code) for TOTP
_SECRET_LENGTH = 16 # length of the secret code required by Google Authenticator app
_CODE_LENGTH = 6 # length of codes produced by Google Authenticator app
def new_secret():
"""Generates and returns a random secret key which should be used when a new user is created in the outside code and stored with it.
It is needs to initialise user's Google Authenticator app and then every time user needs to be authenticated.
As required by Google Authenticator app, the secret is generated 16 base32 alphabet characters long
"""
secret = b''.join(random.choice(base64._b32alphabet) for x in range(_SECRET_LENGTH))
return secret.decode()
def qr_url(mode, secret, label_user, label_issuer='', size=100):
""""Returns URL to Google Chart API producing a QR code image to initialise user's Google Authenticator app
:param mode: authentication mode
:type mode: string, value should be either MODE_TOTP or MODE_HOTP
:param secret: secret key of the user which needs to be authenticated
:type secret: string received from new_secret() or another 16-chars long base32 string
:param label_user: identifier to appear in user's app against the generated code
:type label_user: string with no colons in it
:param label_issuer: additional non-mandatory part of the identifier (will apper in the app separated with a colon)
:type label_issuer: string with no colons in it
:param size: size of the QR code image in pixels (it's square so one dimension is enough)
:type size: positive integer
"""
if not(mode in _modes):
raise ValueError('Invalid mode')
if (len(label_user) == 0):
raise ValueError('Label that identifies the account being authenticated is required to be displayed in Google Authenticator')
if ((':' in label_user) or (':' in label_issuer)):
raise ValueError('Labels to be diplayed in the app cannot contain a colon')
"""Building URI for Google basing on which it can build a QR code for user to initialise their Google Authenticator app
It's what we will encode in our QR code
Format is explained at http://code.google.com/p/google-authenticator/wiki/KeyUriFormat
"""
label = [label_user]
params = {'secret': secret}
if len(label_issuer):
label.insert(0, label_issuer)
params['issuer'] = label_issuer
if mode == MODE_HOTP:
params['counter'] = 0 # if user will be authenticated by counter, start it with zero
uri = 'otpauth://' + mode + '/' + urlquote(':'.join(label)) + '?' + urlencode(params)
"""Google Chart instructions are ready, building the image request URL - it's https because sensitive information (secret) is supplied"""
return 'https://chart.googleapis.com/chart?' + urlencode({'cht': 'qr', 'chs': size, 'chl': uri})
def _truncate(hmac_sha1, digits = _CODE_LENGTH):
"""Converts an HMAC-SHA-1 value into an HOTP value as defined in Section 5.3.
http://tools.ietf.org/html/rfc4226#section-5.3
"""
offset = int(hmac_sha1[-1], 16)
binary = int(hmac_sha1[(offset * 2):((offset * 2) + 8)], 16) & 0x7fffffff
return str(binary)[-digits:]
def _code(secret, c, digits=_CODE_LENGTH):
"""Returns HOTP code for the given secret part of the key and counter value
To get TOTP code, supply timestamp divided by 30 sec as c
"""
# this bit is often missed - secret is expected to be base32-encoded string, and should be decoded before hashing
secret_bytes = base64.b32decode(secret)
# converting a number into an array of bytes representing it as if it was 8 bytes long (same bits, different context)
c_bytes = struct.pack('>Q', c)
# hashing binary secret and number
hmac_sha1 = hmac.new(key=secret_bytes, msg=c_bytes, digestmod=hashlib.sha1).hexdigest()
# converting hash to digits and cutting out the requested number of tralining ones (as they change most often)
return _truncate(hmac_sha1, digits)
def auth(mode, secret, code, var = None, tolerance = 2):
"""Compares the code supplied by user with the expected, returns boolean value with the authentication result
*In HOTP mode, don't forget to increase your stored counter value var!*
:param mode: authentication mode
:type mode: string, value should be either MODE_TOTP or MODE_HOTP
:param secret: secret key of the user which needs to be authenticated
:type secret: string received from new_secret() or another 16-chars long base32 string
:param code: code supplied by user (generated by their Google Authenticator app)
:type code: numeric string
:param var: varying part of the secret key
in HOTP mode counter value is expected (0 if None)
in TOTP mode timestamp is expected (current system timestamp if None)
:type var: int
:param tolerance: keys is which interval of the var value are still accepted
in HOTP mode means number of of attempts to allow *after* the supplied counter value
in TOTP mode means number of 30 (_TOTP_PRECISION) sec intervals to allow *before* and *after* the supplied time
(e.g. 2 means one minute back and forth)
:type tolerance: int
"""
if mode == MODE_HOTP:
"""Using timestamp as a varying part of the key"""
c = 1 if var == None else var # Google Authenticator starts its counter with 1, not 0
"""with HOTP we assume that user counter could go ahead of the server one, but the opposite is not possible"""
tolerance_from = c
tolerance_to = c + tolerance # if user was clicking 'next code' in their app without actually logging in
elif mode == MODE_TOTP:
"""Using counter value as a varying part of the key"""
ts = int(time.time()) if var == None else var # use current timestamp by default
"""TOTP measures time in 30 sec intervals and tolerance means by how many of those intervals we allow
user clock to be different from ours"""
ticks = int(ts / _TOTP_PRECISION)
tolerance_from = ticks - tolerance
tolerance_to = ticks + tolerance
else:
raise ValueError('Unsupported mode')
for c in range(tolerance_from, (tolerance_to + 1)):
if code == _code(secret, c):
return True
return False
import unittest
from urllib.request import urlopen
class ClientTest(unittest.TestCase):
"""Unit test for the functionality implemented in this module
"""
def setUp(self):
self.secret = 'WO2CHK7ULXM5AIGT'
def test_secret(self):
secret = new_secret()
self.assertEqual(len(secret), _SECRET_LENGTH, 'Invalid generated secret length')
for c in secret:
self.assertTrue(c.encode() in base64._b32alphabet.values(), 'Invalid character ' + c + ' generated secret')
def test_qr_code(self):
try:
url = qr_url(MODE_HOTP, 'test', 'Yuriy', 'Acme', 100) # testing all parameters
urlopen(url)
url = qr_url(MODE_TOTP, 'test', 'Yuriy') # testing minimal parameters
urlopen(url)
except Exception:
self.fail('Error while retrieving the QR codes')
def test_hotp(self):
valid_codes = {1: '238295', 2: '821933', 3: '648071'}
for c in valid_codes:
# checking if codes are equal
self.assertEqual(_code(self.secret, c), valid_codes[c])
# checking if tolerance works when the counter value is precise
self.assertTrue(auth(MODE_HOTP, self.secret, valid_codes[c], c, 1))
# checking if tolerance works when the counter value is within tolerance
self.assertTrue(auth(MODE_HOTP, self.secret, valid_codes[2], 1, 1))
# checking if tolerance works when the counter value is outside of tolerance#
self.assertFalse(auth(MODE_HOTP, self.secret, valid_codes[3], 1, 1))
# checking for a failure on an invalid code with bigger tolerance
self.assertFalse(auth(MODE_HOTP, self.secret, '123456', 1, 10))
def test_totp(self):
valid_codes = {1373197332: '180958', 1373197362: '944666', 1373197393: '177781'}
for ts in valid_codes:
ticks = int(ts / _TOTP_PRECISION)
# checking if codes are equal
self.assertEqual(_code(self.secret, ticks), valid_codes[ts])
# checking if tolerance works when the counter value is precise
self.assertTrue(auth(MODE_TOTP, self.secret, valid_codes[ts], ts, 1))
# checking if tolerance works when the counter value is within tolerance
self.assertTrue(auth(MODE_TOTP, self.secret, valid_codes[1373197362], 1373197332, 1))
# checking if tolerance works when the counter value is outside of tolerance#
self.assertFalse(auth(MODE_TOTP, self.secret, valid_codes[1373197393], 1373197332, 1))
# checking for failure on an invalid code with bigger tolerance
self.assertFalse(auth(MODE_TOTP, self.secret, '123456', 1373197332, 10))
pass
if __name__ == '__main__':
unittest.main() |
#return all partitions of a string
def partitions(string):
l=len(string)
i=0;
while(i<l):
str1 = string[0:i+1]
str2 = string[i+1:]
print (str1," ",str2)
partitions(str1)
#partitions(str2)
i += 1
string = input()
partitions(string)
|
"""
Given a list lst and a number N, create a new list that contains each
number of lst at most N times without reordering. For example if N = 2,
and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next
[1,2] since this would lead to 1 and 2 being in the result 3 times, and
then take 3, which leads to [1,2,3,1,2,3].
Example
delete_nth ([1,1,1,1],2) # return [1,1]
delete_nth ([20,37,20,21],1) # return [20,37,21]
"""
def delete_nth(order, max_e):
# Get a new list that we will return.
result = []
# Get a dictionary to count the occurrences.
occurrences = {}
# Loop through all provided numbers.
for n in order:
# Get the count of the current number, or assign it to 0.
count = occurrences.setdefault(n, 0)
# If we reached the max occurrence for that number, skip it.
if count >= max_e:
continue
# Add the current number to the list.
result.append(n)
# Increase the occurrences.
occurrences[n] += 1
# Return the list.
return result
|
"""
Description:
Your task is to create a function that does four basic mathematical operations.
The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.
Examples:
basic_op('+', 4, 7) # Output: 11
basic_op('-', 15, 18) # Output: -3
basic_op('*', 5, 5) # Output: 25
basic_op('/', 49, 7) # Output: 7
"""
def basic_op(operator, value1, value2):
result = None
if operator == "+":
result = value1 + value2
elif operator == "-":
result = value1 - value2
elif operator == "*":
result = value1 * value2
elif operator == "/":
result = value1 / value2
return result
|
def lovefunc(flower1, flower2):
if flower1 % 2 == 0 and flower2 % 2 != 0:
return True
elif flower1 % 2 != 0 and flower2 % 2 == 0:
return True
return False
def lovefunc2(flower1, flower2):
return (flower1 + flower2) % 2
|
def open_or_senior(data):
result = []
for i in data:
if i[0] >= 55 and i[1] > 7:
result.append("Senior")
else:
result.append("Open")
return result
# List comprehensions are ridiculous.
def openOrSenior(data):
return ["Senior" if age >= 55 and handicap >= 8 else "Open" for (age, handicap) in data]
|
"""
There is an array with some numbers. All numbers are equal except for one. Try to find it!
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
It’s guaranteed that array contains at least 3 numbers.
"""
def find_uniq(arr):
# Sorts the given array.
arr.sort()
# Returns the first value if it's less than the last two, otherwise the last must be unique.
return arr[0] if(arr[0] < arr[-1] and arr[0] < arr[-2]) else arr[-1]
|
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
self.char2Ind = {}
for i in range(1,10):
self.char2Ind[str(i)] = 1 << (i-1)
r,c,s = [0] * 9, [0]*9, [0]*9 # row,col,sub
for i in range(9):
for j in range(9):
if board[i][j] == ".":
continue
num = self.char2Ind[board[i][j]]
r[i] |= num
c[j] |= num
s[i//3 * 3 + j//3] |= num
self.solveSudoKuHelp(board,r,c,s)
def solveSudoKuHelp(self,board,r,c,s):
for i in range(9):
for j in range(9):
if board[i][j] == ".":
for char_ in "123456789":
num = self.char2Ind[char_]
if (num & (~(r[i] | c[j] | s[i//3*3 + j//3]))) != 0:
board[i][j] = char_
r[i] |= num
c[j] |= num
s[i//3*3 + j//3] |= num
if self.solveSudoKuHelp(board,r,c,s):
return True
board[i][j] = "."
r[i] &= (~num)
c[j] &= (~num)
s[i//3*3 + j//3] &= (~num)
return False
return True
x = ["..9748...","7........",".2.1.9...","..7...24.",".64.1.59.",".98...3..","...8.3.2.","........6","...2759.."]
s = Solution()
ans = s.solveSudoKu(x) |
# 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 postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
head = TreeNode(-1)
head.left = root
cur = head
while(cur != None):
if(cur.left == None):
cur = cur.right
else:
pre = cur
node = cur.left
while(node != None and node != cur):
pre = node
node = node.right
if(node == None):
pre.right = cur
cur = cur.left
else:
res.extend(self.reverseVisit(cur.left,node))
cur = cur.right
return res
def reverseVisit(self,start,end):
res = []
rStart = self.reverse_(start,end)
node = rStart
while(node != end):
res.append(node.val)
node = node.right
self.reverse_(rStart,end)
return res
def reverse_(self,start,end):
pre = end
cur = start
while(cur != end):
next_ = cur.right
cur.right = pre
pre = cur
cur = next_
return pre
|
# Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
# Empty graph
if node == None: return
# Do the work in two rounds. In the first round, we clone all the
# new nodes only with label. And let their neighbors array empty.
# In the second round, we will assign the neighbors of cloned
# node with the reference to new cloned ones.
# Clone nodes only with label
cloned = {}
currentLayer = [node]
while len(currentLayer) != 0:
nextLayer = []
for toClone in currentLayer:
if toClone in cloned: continue
temp = UndirectedGraphNode(toClone.label)
nextLayer.extend(toClone.neighbors)
cloned[toClone] = temp
currentLayer = nextLayer
# Assign the neighbors of new cloned nodes.
for oldNode in cloned:
newNode = cloned[oldNode]
newNode.neighbors = [cloned[neighbor] for neighbor
in oldNode.neighbors]
return cloned[node] |
class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
self.s1 = s1
self.s2 = s2
self.s3 = s3
if len(s3) != (len(s1) + len(s2)):
return False
res = self.isInterleaveHelp(0,0,0)
return res
def isInterleaveHelp(self,start1,start2,start3):
if start3 == len(self.s3):
return True
if start1 < len(self.s1) and self.s3[start3] == self.s1[start1]:
if self.isInterleaveHelp(start1 + 1,start2,start3+1):
return True
if start2 < len(self.s2) and self.s3[start3] == self.s2[start2]:
if self.isInterleaveHelp(start1,start2+1,start3+1):
return True
return False |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
# to facilate express and compute,change the char to num
nums = []
charToNum = {"(":1, ")":2, "[":3, "]":4, "{":5, "}":6}
for i in range(len(s)):
nums.append(charToNum[s[i]])
for num in nums:
if num % 2 == 1:
stack.append(num)
else:
if len(stack) > 0 and stack.pop() == num - 1:
pass
else:
return False
if len(stack) == 0:
return True
return False
|
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
res = []
if len(intervals) == 0:
return res
intervals = sorted(intervals,cmp = self.intervals_cmp)
interval = intervals[0]
for i in range(1,len(intervals)):
tmp = intervals[i]
if tmp.start <= interval.end:
if tmp.end > interval.end:
interval.end = tmp.end
else:
res.append(interval)
interval = tmp
res.append(interval)
return res
def intervals_cmp(self,x,y):
if x.start < y.start:
return -1
elif x.start == y.start:
if x.end < y.end:
return -1
elif x.end == y.end:
return 0
return 1
|
def greatestCommonFactorForTwo(a, b):
if b == 0:
return a
else:
return greatestCommonFactorForTwo(b, (a%b))
def greatestCommonFactorForN(arr = []):
number = arr[0]
for i in range(len(arr)):
number = greatestCommonFactorForTwo(number, i)
return number
def lcmForTwo(a, b):
return (a * b)/greatestCommonFactorForTwo(a,b)
def lcm(arr):
number = arr[0]
for i in arr:
number = lcmForTwo(number, i)
return number
print(lcm([2,3,4,5,6]))
|
# !/bin/python3
# Program Name - candiesV2.py
# Written by - Ella Blackledge
# Date - 09/21/2018
#
# Problem Statement:
#
# Alice is a kindergarten teacher. She wants to give some candies to
# the children in her class. All the children sit in a line and each
# of them has a rating score according to his or her performance
# in the class. Alice wants to give at least 1 candy to each child.
# If two children sit next to each other, then the one
# with the higher rating must get more candies. Alice wants to minimize
# the total number of candies she must buy.
#
# Example:
# Students' ratings are [4, 6, 4, 5, 6, 2].
# She gives the students candy in the following amounts: [1, 2, 1, 2, 3, 1].
# She must buy a minimum of 10 candies.
#
# Solution:
# If we require that any increasing subsequence {IS} followed
# by a decreasing subsequence {DS} must have size |IS| > |DS|,
# then this problem has a trivial solution.
# Consider this sequence: {4,5,6,7,7,5,4,3}.
# The corresponding candies sequence is {1,2,3,4,4,3,2,1}.
# Since we only need to return the sum of elements in the sequence,
# this is a valid alternative: {1,2,3,4,1,2,3,4}, and it can be found
# in a single pass through the scores.
#
# This solution breaks down when a non-decreasing sequence is immediately followed by
# a decreasing sequence of a larger size: for a sequence {4,5,6,7,5,4,3,2,1}
# the candies array is {1,2,3,6,5,4,3,2,1}. We can use the
# technique described above, but 4 (the last candy element of the increasing sequence)
# must be reaplaced by 6. To achieve this in a single pass, we can add 4,
# and then later compensate for the shortage by adding 2 (6-4).
import math
import os
import random
import re
import sys
def candies(n, arr):
"""Given a list of students' ratings, return the number
of candies"""
# the accumulator for the total number of candies
TotalCandies = 1
# candies counter for each element
candies = 1
# number of elements in the last encountered increasing sequence
saved_cand = sys.maxsize
direc = "UP"
prev_dir = "DOWN"
for i in range (1, n):
direc = direction(arr[i-1], arr[i])
# end of the decreasing subsequence
if direc != "DOWN" and prev_dir == "DOWN":
TotalCandies += max (0, candies + 1 - saved_cand)
saved_cand = 1
if direc == "FLAT":
candies = 1
saved_cand = 1
elif direc == prev_dir:
candies += 1
elif direc == "UP": # start of a new increasing subsequence
candies = 2
else: # dir == "DOWN" start of a new decreasing subsequence
saved_cand = candies # saved the size of the previous subsequence
candies = 1
TotalCandies += candies
prev_dir = direc
if prev_dir == "DOWN":
TotalCandies += max (0, candies - saved_cand + 1)
return TotalCandies
def direction (old, curr):
if old > curr:
return "DOWN"
elif old < curr:
return "UP"
else:
return "FLAT"
def MainFromFile(fname):
# read input from from file and print to stdout
f = open (fname, "r")
n = int(f.readline())
arr = []
for _ in range(n):
arr_item = int(f.readline())
arr.append(arr_item)
result = candies(n, arr)
print(str(result) + '\n')
f.close()
def HackerRankMain():
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = []
for _ in range(n):
arr_item = int(input())
arr.append(arr_item)
result = candies(n, arr)
fptr.write(str(result) + '\n')
fptr.close()
if __name__ == '__main__':
# One of the two lines below must be commented out
MainFromFile("C:/HackerRank/candies/input01.txt")
#HackerRankMain() |
# -*- coding: utf-8 -*-
# 2019.01/03
from random import *
def is_updown(num, target):
if num < target:
print('Go Up!')
return 1
elif num > target:
print('Go Down!')
return 1
else:
print('Good Job~!')
return 0
answer = randint(1, 100)
count = 1
while True:
n = input('Number : ')
token = is_updown(int(n), answer)
if token != 0:
count += token
else:
print('You gave the answer %d in %d times' % (answer, count))
break
### 과제 1 : 다항식의 미분식을 계산
### input : '1-4x^2+3x^3' 의 미분식 계산...
### 과제 2 : 리스트에서 오름차순으로 정렬될때 까지 횟수 카운트
### input : [3, 5, 8, 1, ...] 임의의 리스트
### 과제 3 : 임의의 정수의 i번째 bit와 j번째 bit 사이의 읽어내는 함수
|
#-*- coding: utf-8 -*-
import sys
import math
import functools
# classes
class ComPlex:
'''Complex Class Definition'''
def __init__(self, x=0, y=0):
self.re = x;
self.im = y;
def Real(self): return self.re;
def Imag(self): return self.im;
def Conjugate(self):
return ComPlex(self.re, -self.im);
def Modulus(self):
return math.sqrt(self.re*self.re + self.im*self.im);
def __add__(self, z):
x = self.re + z.re;
y = self.im + z.im;
return ComPlex(x, y);
def __mul__(self, z):
x = self.re*z.re - self.im*z.im;
y = self.re*z.im + self.im*z.re;
return ComPlex(x, y);
def __truediv__(self, z):
d2 = z.re*z.re + z.im*z.im;
w = self*z.Conjugate();
w.re /= d2;
w.im /= d2;
return w;
def __str__(self):
if self.im < 0:
sgn = ' - ';
y = -self.im;
else:
sgn = ' + ';
y = self.im;
return '{0}{1}{2}i'.format(self.re, sgn, y);
def Show(self, arg=''):
if self.im < 0:
sgn = ' - ';
y = -self.im;
else:
sgn = ' + ';
y = self.im;
print(arg, end=' ');
print( str(self.re)+sgn+str(y)+' i' );
return self;
class Vector:
'''Define Vectors'''
def __init__(self,*comps):
self.vec = [];
for val in comps:
self.vec.append(float(val));
self.dim = len(comps);
def SetVector(self, vsrc):
self.dim = len(vsrc);
self.vec = vsrc;
return self;
def GetVector(self):
return self.vec;
def Coordinate(self, k):
if k < self.dim:
return self.vec[k];
else:
return 0;
def Norm(self):
d = 0;
for vk in self.vec:
d += vk*vk;
return math.sqrt(d);
def Scalar(self, scl):
v = [scl*vk for vk in self.vec];
return Vector().SetVector(v);
def __add__(self, rvec):
v = [vk for vk in self.vec];
for k in range(self.dim):
v[k] += rvec.Coordinate(k);
return Vector().SetVector(v);
def __sub__(self, rvec):
v = [vk for vk in self.vec];
for k in range(self.dim):
v[k] -= rvec.Coordinate(k);
return Vector().SetVector(v);
def __mul__(self, rvec):
only = 3;
v = [self.Coordinate(k) for k in range(only)];
w = [rvec.Coordinate(k) for k in range(only)];
vxw = [ 0 for k in range(only)];
for k in range(only):
k1 = (k+1)%only;
k2 = (k+2)%only;
vxw[k] = v[k1]*w[k2] - v[k2]*w[k1];
return Vector().SetVector(vxw);
def __str__(self):
pstr = self.StringVector();
return pstr;
def __call__(self, cmnt=''):
print(cmnt,self);
def StringVector(self):
vstr = '<';
for vk in self.vec:
vstr += ' '+str(vk)+' ';
vstr += '>';
return vstr;
def Dot(self, rvec):
inner = 0;
for k in range(self.dim):
inner += self.Coordinate(k)*rvec.Coordinate(k);
return inner;
def Unitary(self):
d = self.Norm();
unit = self.Scalar(1/d);
return unit;
def Projector(self, plane0):
n0 = plane0.Unitary();
xonp = self - n0.Scalar(self.Dot(n0));
return xonp;
def Show(self,comment):
print(comment, end=' ');
print('(dim=%d)' % self.dim)
print(self.vec);
return self;
class Tri3D:
'''Triangle in 3D'''
num = 3;
def __init__(self, v0=None, v1=None, v2=None, nvec=None):
self.vertex = {0:v0, 1:v1, 2:v2};
self.normal = nvec;
def __str__(self):
pstr = ['','','',''];
for k in range(self.num):
pstr[k] += 'v'+str(k)+'=';
pstr[k] += self.GetVertex(k).StringVector();
pstr[self.num] += 'n='+self.GetNormal().StringVector();
return '\n'.join(pstr);
def __call__(self, closed=True):
yield self[0];
yield self[1];
yield self[2];
if closed == True:
yield self[0];
def __getitem__(self, offs):
return self.vertex[offs];
def __setitem__(self, offs, value):
self.vertex[offs] = value;
def SetVertex(self, offset, vector):
try:
self.vertex[offset] = vector.vec;
except ValueError:
print('No %d-th vertex' % offset);
return self;
def GetVertex(self, offset):
if offset < 3:
return Vector().SetVector(self.vertex[offset]);
else:
return Vector().SetVector([0,0,0]);
def SetNormal(self, nvec=None):
if nvec == None:
vec0 = self.GetVertex(0);
vec1 = self.GetVertex(1);
vec2 = self.GetVertex(2);
nv = ( vec1-vec0 )*( vec2-vec0 );
self.normal = nv.Unitary().GetVector();
else:
self.normal = nvec.Unitary().GetVector();
return self;
def GetNormal(self):
return Vector().SetVector(self.normal);
def CalArea(self):
x0 = self.GetVertex(0);
x1 = self.GetVertex(1);
x2 = self.GetVertex(2);
vxw = ( x1-x0 )*( x2-x0 );
return vxw.Norm()/2;
def Show(self, cmnt):
print(cmnt);
self.GetVertex(0)('v0=');
self.GetVertex(1)('v1=');
self.GetVertex(2)('v2=');
self.GetNormal()('n=');
return self;
def Dump(self, name, beam=None):
with open(name,'w+') as output:
'''
close를 쓰지 않아도 됨
열고 있는동안 아래 내용 실행, 끝나면 자동으로 close
'''
headline = '# light beam = '+str(beam)+'\n';
output.write(headline);
for k, v in self.vertex.items():
svec = [ ' '+str(vk)+' ' for vk in v ];
pt = ' '.join(svec);
output.write('%s\n' % pt);
svec = [ ' '+str(vk)+' ' for vk in self.vertex[0] ];
output.write('%s\n' % ' '.join(svec) );
output.write('\n');
return self;
class AugTri3D(Tri3D):
def __init__(self, vec0=None, vec1=None, vec2=None, vecn=None):
self.area = 0;
if vec0 != None: v0 = vec0.GetVector();
else: v0 = [];
if vec1 != None: v1 = vec1.GetVector();
else: v1 = [];
if vec2 != None: v2 = vec2.GetVector();
else: v2 = [];
if vecn != None:
unit = vecn.Unitary();
n = unit.GetVector();
else: n = [];
super(AugTri3D,self).__init__(v0,v1,v2,n);
def SetArea(self):
self.area = self.CalArea();
return self;
def GetArea(self):
return self.area;
def CalProj(self, beam):
w = {};
for k in range(self.num):
w[k] = self.GetVertex(k).Projector(beam);
return AugTri3D(w[0],w[1],w[2], beam);
if __name__ == '__main__':
v0 = Vector(1,0,0);
v1 = Vector(0,1,0);
v2 = Vector(0,0,1);
n = Vector(1,1,1);
v0('v0 = '); v1('v1 = '); v2('v2 = '); n('n = ');
T0 = AugTri3D().SetVertex(0, v2).SetVertex(1, v1).SetVertex(2, v0).SetNormal(n);
print(T0[0])
v0.SetVector([4,0,0]);
v1.SetVector([0,2,0]);
v2.SetVector([4,0,3]);
T1 = AugTri3D(v0,v1,v2).SetNormal();
T0.Show('T0: ')
T0.Dump('T0.out');
print('|T0| = ',T0.SetArea().GetArea());
T1.Show('T1: ')
T1.Dump('T1.out');
print('|T1| = ',T1.SetArea().GetArea());
light = Vector(1,1,1);
projT0 = T0.CalProj(light);
print('|projT0| = ',projT0.SetArea().GetArea());
projT0.Dump('projT0.out',light);
projT1 = T1.CalProj(light);
print('|pT1| = ',projT1.SetArea().GetArea());
projT1.Dump('projT1.out',light);
|
# -*- coding: utf-8 -*-
"""
TODO
"""
from commands.Command import command
import keyboard #pylint: disable=E0401
FORWARD = 'w'
BACKWARD = 's'
LEFT = 'a'
RIGHT = 'd'
STOP = 'esc'
FORWARD_NEWLINE = 'w\n'
BACKWARD_NEWLINE = 's\n'
LEFT_NEWLINE = 'a\n'
RIGHT_NEWLINE = 'd\n'
FORWARD_BYTE = FORWARD_NEWLINE.encode("UTF-8")
BACKWARD_BYTE = BACKWARD_NEWLINE.encode("UTF-8")
LEFT_BYTE = LEFT_NEWLINE.encode("UTF-8")
RIGHT_BYTE = RIGHT_NEWLINE.encode("UTF-8")
def mode_man(connection):
"""
TODO
"""
answer = command(connection, b'man\n', None)
answer = int(answer)
print(answer)
if answer == 0:
print("Manueller Modus aktiviert")
else:
print("Manueller Modus wurde nicht aktiviert")
while True:
if keyboard.is_pressed(FORWARD):
command(connection, FORWARD_BYTE, 0)
print("gesendet w")
elif keyboard.is_pressed(BACKWARD):
command(connection, BACKWARD_BYTE, 0)
print("gesendet s")
elif keyboard.is_pressed(RIGHT):
command(connection, RIGHT_BYTE, 0)
print("gesendet d")
elif keyboard.is_pressed(LEFT):
command(connection, LEFT_BYTE, 0)
print("gesendet a")
elif keyboard.is_pressed(STOP):
print("break")
break
else:
command(connection, b'0\n', 0)
|
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# You may assume that the array is non-empty and the majority element always exist in the array.
# Example 1:
# Input: [3,2,3]
# Output: 3
# Example 2:
# Input: [2,2,1,1,1,2,2]
# Output: 2
def majorityElement(nums: List[int]) -> int:
majority = len(nums)/2
dict1 = {}
for i in nums:
if i in dict1:
dict1[i] += 1
else:
dict1[i] = 1
if dict1[i] > majority:
return i |
#!/usr/bin/env python
# -*- coding_utf-8 -*-
"""
Author: Zhenghan Lee
Date:
"""
def is_bianxing(str1,str2):
dic = {}
for i in str1:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
for j in str2:
dic[j] -= 1
if dic[j]<0:
return False
return True
def add_(str1):
sign = 0
sum = 0
num = ''
for i in str1:
if ord(i) == ord('-'):
sign += 1
else:
n = ord(i) - ord('0')
if n <= 9 and n >=0:
num += i
else:
if num == '':
pass
else:
sum = (-1) ** sign * int(num) + sum
num =''
sign = 0
#print(sum)
if num != '':
sum += (-1) ** sign * int(num)
if __name__ == '__main__':
#print(is_bianxing('123','2331'))
add_('A-1B--2c--D6E33')
add_('012c-1') |
# This decorator function does nothing.
def do_nothing(function):
return function
# This is a function that adds two numbers.
def add(x, y):
return x + y
# The decorator modifies the add function to... do nothing.
@do_nothing
def add(x, y):
return x + y
print('Result of calling the add function with the do nothing decorator: ',
add(3, 4))
# The trace decorator prints out a trace of which function was called,
# and with which arguments and keyword arguments.
def trace(function):
def wrapper(*args, **kwargs):
print('trace: call function {}() with arguments {} and keyword arguments {}'
.format(function.__name__, args, kwargs))
result = function(*args, *kwargs)
print('returned {}'.format(result))
return result
return wrapper
# Now the add function not only adds, but also prints out a trace.
@trace
def add(x, y):
return x + y
add(3, 4) |
from math import *
import random
grid_list = [
[1,2,3,4,5,6],
[7,8,9,10,11,12],
[13,14,15,16,17,18],
[20,21,22,23,24,25],
]
monthConversion = {
"jan": "January",
"feb": "February",
"mar": "March",
"apr": "April",
}
x = {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
}
print(x.get("a"))
def letters():
number = 0
for letters in "efjcnefcjoenbcoencejncfcknfecencekcnfecknefconewcmndcoencledsncekcnk":
number += 1
print(str(number) + ")" + " " + letters)
letters()
|
from colored import fg,bg, attr
import random
'''
This short program will count the letters in the words and only print those that are greater then 14
'''
words = ["elephant","monkey","buildings","people"]
color = fg('green')
for count in words:
if len(count) > 14:
bigWord = ("This word " + count.upper() + " has more then 14 letters in it.")
print(bigWord)
elif len(count) < 14:
bigWord = ("Nothing here")
print(color + bigWord)
i = 1
while (i < 256):
color = fg(i)
print(color + "All the colors of the rainbow" )
i += 1
|
import random
from math import *
# this program looks for a secret word. You only get 3 try's.
secrete_word = "monkey"
guess = ""
guess_limit = 3
attempts = 0
out_of_guesses = False
while guess != secrete_word and not (out_of_guesses):
if attempts < guess_limit:
guess = input("Enter the secrete word please: ")
attempts += 1
else:
out_of_guesses = True
if out_of_guesses and guess != secrete_word:
print("Out of guesses, you loose!")
else:
print("you win!")
|
from random import *
import time
import os
import math
# change this value to experiment with spawning
ONE_SPAWNING_PROBABILITY = 0.85
TWO_SPAWNING_PROBABILITY = 1.75
probs = {
0: 0.60,
1: 0.25,
2: 0.15
}
# TODO: add error checking
class Board:
"""
Matrix that holds integer values interpreted as cells.
Attributes
----------
values : List
A list of ints.
width : int
Number of columns.
height : int
Number of rows.
len : int
Total number of values.
"""
# attributes
__slots__ = ['_values', '_width', '_height', '_len', '_range', '_file_loaded']
def __init__(self, source = '', width = 0, height = 0, random = True, n_range = 1):
self._values = []
self._len = 0
self._range = n_range
self._file_loaded = False
if source != '':
# load information from file
file = self.load_from_file(source)
self._width = len(file[0])
self._height = len(file)
self._file_loaded = True
self.fill_values_from_file(file)
else:
# create a board filled with values
self._width = width
self._height = height
if width > 0 and height > 0:
if random:
self.fill_values_randomly(n_range)
else:
self.fill_values(0)
def fill_values(self, value = 0):
"""
Fills a board with the value given.
Parameters
----------
value : int, default: 0
Returns
-------
values : List
"""
if self.is_empty():
# add rows and fill them with values
for row in range(self._height):
# add a new row
self.append([])
for column in range(self._width):
# append value to the row
self._values[row].append(value)
self._len += 1
else:
# change each value with the given
for row in range(self._height):
for column in range(self._width):
self._values[row][column] = value
# make sure the board was filled
assert not self.is_empty(), 'No elements were added'
return self._values
def fill_values_randomly(self, n_range):
"""
Fills a board with either a 0 or a 1.
Returns
-------
values : List
"""
for row in range(self._height):
# add a new row
self.append([])
for column in range(self._width):
# assign random values to every number and append that to the row
rand_number = uniform(0, n_range)
if rand_number > ONE_SPAWNING_PROBABILITY and rand_number < 1:
rand_number = 1
elif rand_number >= TWO_SPAWNING_PROBABILITY:
rand_number = 2
else:
rand_number = 0
# experimental
# ceil = math.ceil(rand_number)
# if rand_number > ceil - (0.25 - ((ceil - 1) * (0.25 / ceil))):
# rand_number = ceil
# else:
# rand_number = 0
self._values[row].append(rand_number)
self._len += 1
# make sure the board was filled
assert not self.is_empty(), 'No elements were added'
return self._values
def fill_values_from_file(self, file):
"""
Fills a board with the information given by a file.
Parameters
----------
file : string
Returns
-------
values : List
"""
for row in range(self._height):
self.append([])
for column in range(self._width):
self._values[row].append(int(file[row][column])) # cast the value as an int
self._len += 1
# make sure the board was filled
assert not self.is_empty(), 'No elements were added'
return self._values
def load_from_file(self, file):
"""
Loads and returns a file.
Parameters
----------
file : string
Returns
-------
f : File
"""
f = open(file, 'r').read().split()
return f
def change_pos_value(self, row, column, value):
"""
Changes the value of the given cell with another value.
Parameters
----------
row : int
column : int
value : int
"""
self._values[row][column] = value
def append(self, value):
self._values.append(value)
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@property
def values(self):
return self._values
@property
def range(self):
return self._range
def loaded_from_file(self):
return self._file_loaded == True
def is_empty(self):
return self._len == 0
def clear(self):
self._values.clear()
def __len__(self):
return self._len
def __repr__(self):
return ('[' + ', '.join(repr(x) for x in self._values) + ']') |
"""
project.py
------------
Cartoon Network inspired graphic program
Utilizing the original cartoon network animation logo
as inspiration in accordance with what we learn in
lecture 10 and lecture 11 - bouncing balls and moving images
"""
import tkinter
import time
import random
import math
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from PIL import ImageTk
from simpleimage import SimpleImage
CANVAS_WIDTH = 600 # Width of drawing canvas in pixels
CANVAS_HEIGHT = 600 # Height of drawing canvas in pixels
BALL_SIZE = 50
def main():
canvas = make_canvas(CANVAS_WIDTH, CANVAS_HEIGHT, 'Cartoon Network Throwback')
# top middle left square with text
r = canvas.create_rectangle(0, 134, 166, 300, outline='black')
canvas.create_text(230, 205, font='Sans 200 bold', text="C", fill='black')
# bottom middle right square with text
rect = canvas.create_rectangle(600, 300, 766, 466, outline='black', fill='SlateGray1')
canvas.create_text(380, 370, font='Sans 200 bold', text="N", fill='white')
# Title text
title = canvas.create_text(300, 0, font='Sans 20 bold',text="CARTOON NETWORK", fill='black')
# moves left square to the center
while get_left_x(canvas,r) < CANVAS_WIDTH/4:
# update world
canvas.move(r, 5, 0)
# redraw canvas
canvas.update()
#pause
time.sleep(1/50)
# move right square to the center
while get_right_x(canvas, rect) > 466:
# update world
canvas.move(rect, -15, 0)
#redraw canvas
canvas.update()
#pause
time.sleep(1/50)
# move title to the center and jump
while get_top_y(canvas, title) < 300:
# update world
canvas.move(title, 0, 15)
# redraw canvas
canvas.update()
# pause
time.sleep(1 / 50)
# load the .gif image image
gif1 = ImageTk.PhotoImage(Image.open("we bare bears movement.gif"))
gif = canvas.create_image(10, 290, image=gif1)
image1 = ImageTk.PhotoImage(Image.open("agm.png"))
image = canvas.create_image(400, -200, image=image1)
ed = ImageTk.PhotoImage(Image.open("eee.png"))
ed1 = canvas.create_image(200, 800, image=ed)
while get_left_x(canvas, gif) < 800:
# update world
canvas.move(gif, 20, 0)
# redraw canvas
canvas.update()
# pause
time.sleep(1 / 50)
while get_top_y(canvas, image) < 200:
# update world
canvas.move(image, 0, 30)
# redraw canvas
canvas.update()
# pause
time.sleep(1 / 50)
while get_top_y(canvas, ed1) > 400:
# update world
canvas.move(ed1, 0, -30)
# redraw canvas
canvas.update()
# pause
time.sleep(1 / 50)
# create ball bouncing
canvas.create_oval(0, 0, BALL_SIZE, BALL_SIZE, tags="Bob", outline='black')
canvas.create_oval(125, 125, 175, 175, tags="Bob", outline='black')
canvas.create_oval(400, 200, 450, 250, tags="Bob", outline='black')
canvas.create_oval(150, 400, 200, 450, tags="Bob", outline='black')
canvas.create_oval(300, 0, 350, 50, tags="Bob", outline='black')
canvas.create_oval(550, 0, 600, 50, tags="Bob", outline='black')
canvas.create_oval(500, 500, 550, 550, tags="Bob", outline='black')
canvas.create_oval(25, 400, 75, 450, tags="Bob", outline='black')
canvas.create_oval(175, 225, 225, 275, tags="Bob", outline='black')
canvas.create_oval(400, 425, 450, 475, tags="Bob", outline='black')
dx = 0.5
dy = 20
while True:
# update world
canvas.move("Bob", dx,dy)
# redraw canvas
if hit_left_wall(canvas, "Bob") or hit_right_wall(canvas, "Bob"):
dx *= -1
if hit_top_wall(canvas, "Bob") or hit_bottom_wall(canvas, "Bob"):
dy *= -2
canvas.update()
# pause
time.sleep(1 / 50.)
change_color(canvas, "Bob")
# change the color of the N box
change_color(canvas, rect)
canvas.update()
# pause
time.sleep(1 / 50.)
canvas.mainloop()
def change_color(canvas, object):
'''
When you call this method, the provided shape will change color to a
randomly chosen color.
:param canvas: the canvas where the shape exists
:param shape: the shape you want to have its color changed
'''
# 1. get a random color
color = random.choice(['SlateGray1', 'salmon', 'red', 'yellow', 'plum', 'snow3', 'VioletRed1',
'RosyBrown', 'white smoke', 'tomato3', 'tan1', 'SkyBlue1', 'SeaGreen1', 'RosyBrown4'])
# 2. use the tkinter method to change the shape's color
canvas.itemconfig(object, fill=color, outline=color) # change color
def hit_left_wall(canvas, object):
return get_left_x(canvas, object) <= 1
def hit_top_wall(canvas, object):
return get_top_y(canvas, object) <= 1
def hit_right_wall(canvas, object):
return get_right_x(canvas, object) >= CANVAS_WIDTH
def hit_bottom_wall(canvas, object):
return get_bottom_y(canvas, object) >= CANVAS_HEIGHT
######## These helper methods use "lists" ###########
### Which is a concept you will learn Monday ###########
def get_left_x(canvas, object):
return canvas.coords(object)[0]
def get_top_y(canvas, object):
return canvas.coords(object)[1]
def get_right_x(canvas, object):
return canvas.coords(object)[2]
def get_bottom_y(canvas, object):
return canvas.coords(object)[3]
def mouse_moved(event):
print('x = ' + str(event.x), 'y = ' + str(event.y))
def make_canvas(width, height, title):
"""
DO NOT MODIFY
Creates and returns a drawing canvas
of the given int size with a blue border,
ready for drawing.
"""
top = tkinter.Tk()
top.minsize(width=width, height=height)
top.title(title)
canvas = tkinter.Canvas(top, width=width + 1, height=height + 1)
canvas.pack()
canvas.bind("<Motion>", mouse_moved)
return canvas
if __name__ == '__main__':
main()
canvas.postscript(file='filename.ps', colormode='color') |
class SortStack():
def __init__(self):
self.sort_stack = []
self.helper_stack = []
def push(self, value):
if self.sort_stack:
while self.sort_stack and value > self.sort_stack[-1]:
self.helper_stack.append(self.sort_stack.pop())
self.sort_stack.append(value)
while self.helper_stack:
self.sort_stack.append(self.helper_stack.pop())
else:
return self.sort_stack.append(value)
def pop(self):
return self.sort_stack.pop()
if __name__ == '__main__':
stack = SortStack()
stack.push(10)
stack.push(5)
stack.push(7)
stack.push(13)
stack.push(9)
stack.push(4)
stack.push(4)
stack.push(20)
print(stack.sort_stack) |
class ThreeInOne():
def __init__(self, size):
self.size = size
self.stackArray = [None] * self.size
self.ends = [0,1,2]
def push(self, stack_number, value):
for index in range(self.size-2, self.ends[stack_number], -1):
self.stackArray[index + 1] = self.stackArray[index]
self.stackArray[self.ends[stack_number]] = value
for index in range(stack_number, 3):
self.ends[index] += 1
def pop(self, stack_number):
value = self.stackArray[self.ends[stack_number]-1]
print('value ' + str(value))
for index in range(self.ends[stack_number] - 1, self.size - 2):
self.stackArray[index] = self.stackArray[index + 1]
print('printing Array')
self.printArray()
for index in range(stack_number, 3):
self.ends[index] -= 1
return value
def printArray(self):
for element in self.stackArray:
print(element)
if __name__ == '__main__':
stack = ThreeInOne(15)
stack.push(0,14)
stack.push(0,4)
stack.push(0,7)
stack.push(1,8)
stack.push(2,10)
stack.pop(0)
stack.pop(0)
stack.printArray()
print(stack.ends) |
class Node():
def __init__(self, value, children=None):
self.value = value
self.visited = False
self.children = []
if children:
self.children = children
def addChild(self, child):
self.children.append(child)
def addChildren(self, children):
for child in children:
self.addChild(child)
def removeChild(self, node):
self.children.remove(node)
class BinaryTreeNode():
def __init__(self, value, left=None, right=None, parent=None):
self.value = value
self.left = left
self.right = right
self.parent = parent
def addLeft(self, child):
self.left = child
def addRight(self, child):
self.right = child
def removeLeft(self):
self.left = None
def removeRight(self):
self.right = None
def initiateBinaryTree():
# Initiate binary tree:
# 10
# / \
# 5 7
# / \ \
# 12 15 9
# / \
# 4 8
root = BinaryTreeNode(10)
root = root
root.left = BinaryTreeNode(5, parent=root)
root.right = BinaryTreeNode(7, parent=root)
root.left.left = BinaryTreeNode(12, parent=root.left)
root.left.left.left = BinaryTreeNode(4, parent=root.left.left)
root.left.left.right = BinaryTreeNode(8, parent=root.left.left)
root.left.right = BinaryTreeNode(15, parent=root.left)
root.right.right = BinaryTreeNode(9, parent=root.right)
return root
def printBinaryTree(tree):
level = [tree]
children = []
while level:
printList = [node.value for node in level]
print(printList)
for node in level:
if node.left:
children.append(node.left)
if node.right:
children.append(node.right)
level = children
children = []
def initiateBinarySearchTree(values=[1,3,4,6,9,12,15,19,22,25], parent=None):
if values:
node = BinaryTreeNode(values[len(values) // 2], parent=parent)
if values[:len(values) // 2]:
node.left = initiateBinarySearchTree(values[:len(values) // 2], node)
if values[len(values) // 2 + 1:]:
node.right = initiateBinarySearchTree(values[len(values) // 2 + 1:], node)
return node
class Graph():
def __init__(self):
self.nodes = []
def addNode(self, node):
self.nodes.append(node)
def addNodes(self, nodes):
for node in nodes:
self.addNode(node)
def removeNode(self, node):
self.nodes.remove(node)
def addEdge(self, s, t):
s.children.append(t)
def printGraph(self):
for node in self.nodes:
children = []
for child in node.children:
children.append(child.value)
print('node ' + str(node.value) + ' with children ' + str(children))
def initiateGraph():
# Initiate graph from page 107
node0 = Node(0)
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node0.addChildren([node1, node4, node5])
node1.addChildren([node3, node4])
node2.addChildren([node1])
node3.addChildren([node2, node4])
graph = Graph()
graph.addNodes([node0, node1, node2, node3, node4, node5])
return graph
def initiateBinarySearchTreeGraph(graph, values):
if values:
node = Node(values[len(values) // 2])
graph.addNode(node)
if values[:len(values) // 2]:
node.children.append(initiateBinarySearchTreeGraph(graph, values[:len(values) // 2]))
if values[len(values) // 2 + 1:]:
node.children.append(initiateBinarySearchTreeGraph(graph, values[len(values) // 2 + 1:]))
return node
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 2 14:56:55 2021
@author: mahir
"""
from tkinter import *
#rules
def printRules():
rules=Tk()
x=10
rules.title('TIC TAC TOE: Rules')
rules['bg']='black'
Label(rules, text=' Snake ', font=('Helvetica',18), bg='black', fg='white').grid(row=0, column=0)
Label(rules, text=' This game of snake was designed by Mahir Kaya, a coder at ROOT CODE', font=('Helvetica',18), bg='black', fg='white').grid(row=1, column=0)
Label(rules, text=' ', font=('Helvetica',18), bg='black', fg='white').grid(row=2, column=0)
Label(rules, text='You will play the game using keyboard keys up, down, right and left', font=('Helvetica',18), bg='black', fg='white').grid(row=3, column=0)
Label(rules, text=' ', font=('Helvetica',18), bg='black', fg='white').grid(row=4, column=0)
Label(rules, text=' First, you need to set the row and column numbers from left bottom', font=('Helvetica',18), bg='black', fg='white').grid(row=5, column=0)
Label(rules, text=' ', font=('Helvetica',16), bg='black', fg='white').grid(row=6, column=0)
Label(rules, text='Recommended number of Rows and Columns: 15', font=('Helvetica',18), bg='black', fg='white').grid(row=7, column=0)
Label(rules, text=' ', font=('Helvetica',16), bg='black', fg='white').grid(row=8, column=0)
Label(rules, text='Your job is to eat as many apples as you can', font=('Helvetica',18), bg='black', fg='white').grid(row=9, column=0)
Label(rules, text=' ', font=('Helvetica',16), bg='black', fg='white').grid(row=10, column=0)
Label(rules, text='Then, when the game is over, your score which is', font=('Helvetica',18), bg='black', fg='white').grid(row=13, column=0)
Label(rules, text='how many apples you ate, will be reported to you', font=('Helvetica',18), bg='black', fg='white').grid(row=15, column=0)
Label(rules, text=' ', font=('Helvetica',16), bg='black', fg='white').grid(row=16, column=0)
Label(rules, text='If you want to go back to the main page, click the button "Back"', font=('Helvetica',18), bg='black', fg='white').grid(row=17, column=0)
Label(rules, text=' ', font=('Helvetica',16), bg='black', fg='white').grid(row=18, column=0)
Label(rules, text='ENJOY', font=('Helvetica',18), bg='black', fg='white').grid(row=19, column=0)
def a():
rules.destroy()
from IntroSnake import intro
intro(0)
Button(rules, text='back', command=a, fg='black', bg='black').grid(row=20, column=0)
mainloop()
|
x=list(input('enter string:'))
x.sort(reverse=True)
print("".join(map(str,x)))
|
l1=[1,2,3,6,8,4]
l2=[2,4,1,3,8]
if len(l1)==len(l2):
print('all element is present')
else:
for x in l1:
if x not in l2:
print(x,'not present in l2')
'''
print(sum(l1)-sum(l2))
|
import sys
input_filename = sys.argv[1]
file = open(input_filename,'r')
stream = file.read()
index = 0
group_level = 0
score = 0
garbage = False
amount_of_garbage = 0
while index < len(stream) and stream[index] != "\n":
char = stream[index]
if char == '{' and not garbage:
group_level += 1
elif char == '}' and not garbage:
score += group_level
group_level -= 1
elif char == '<' and not garbage:
garbage = True
elif char == '>':
garbage = False
elif char == '!':
index += 1
elif garbage:
amount_of_garbage += 1
index += 1
print('part 1: '+str(score))
print('part 2: '+str(amount_of_garbage))
|
#!/usr/local/bin/python
import sys
from math import floor
no_of_elves = int(sys.argv[1])
def solve_circle(elves):
offset = 2
no_of_elves = len(elves)
if no_of_elves % 2 == 1:
offset = 1
digital_half = int(floor(no_of_elves/2))
index = digital_half
next_elves = []
for i in range(no_of_elves):
elf = (i+index) % no_of_elves
if (i-offset) % 3 == 0 or (elf + 1 == digital_half and (no_of_elves % 3 == 1 or no_of_elves % 3 == 2)):
next_elves.append(elves[elf])
next_elves = sorted(next_elves)
return next_elves
elves = range(1, no_of_elves+1)
while len(elves) > 1:
elves = solve_circle(elves)
print(elves)
|
#!/usr/local/bin/python
import sys
import math
import re
import operator
import copy
file = open(argv[1],'r')
# Parsing
grid = []
for i,line in enumerate(file):
grid.append([])
for char in line:
if char == '#':
grid[i].append(1)
else:
grid[i].append(0)
def printGrid():
for x in range(100):
line = ''
for y in range(100):
if grid[x][y] == 1:
line += '#'
else:
line += '.'
print line
# Iterate through Conway cycles
for i in range(100):
next_grid = copy.deepcopy(grid)
for x in range(100):
for y in range(100):
cell_fitness = 0
for neighbour_x in range(x-1, x+2):
if neighbour_x < 0 or neighbour_x > 99:
continue
for neighbour_y in range(y-1, y+2):
if neighbour_y < 0 or neighbour_y > 99:
continue
if neighbour_x == x and neighbour_y == y:
continue
cell_fitness += grid[neighbour_x][neighbour_y]
if grid[x][y] == 1: # Alive!
# If two or three neighbours are alive I stay alive
if cell_fitness < 2 or cell_fitness > 3:
next_grid[x][y] = 0
else: # Dead :(
# If three neighbours are alive, I resurrect!
if cell_fitness == 3:
next_grid[x][y] = 1
# Force the corners to be always on
next_grid[0][0] = 1
next_grid[0][99] = 1
next_grid[99][0] = 1
next_grid[99][99] = 1
grid = next_grid
printGrid()
# Count number of alive cells
total = 0
for x in range(100):
for y in range(100):
total += grid[x][y]
print total
|
#!/usr/local/bin/python
import sys
part = int(sys.argv[1])
input_filename = sys.argv[2]
file = open(input_filename,'r')
instructions = list(map(int, file.read().splitlines()))
pc = 0
steps = 0
while pc >= 0 and pc < len(instructions):
oldpc = pc
pc += instructions[pc]
if part == 1 or instructions[oldpc] < 3:
instructions[oldpc] += 1
else:
instructions[oldpc] -= 1
steps += 1
print(pc)
print(steps) |
import os
def print_grid(grid):
for row in grid:
print(''.join(map(str, row)))
def manhattan_distance(a, b):
return abs(b[0] - a[0]) + abs(b[1] - a[1])
class CircularList:
def __init__(self):
self.l = list()
def __init__(self, initlist):
self.l = initlist
def __str__(self):
return str(self.l)
def find(self, elem):
return self.l.index(elem)
def add(self, elem, pos):
pos = pos % len(self.l)
self.l.insert(pos, elem)
def remove(self, elem):
return self.l.remove(elem)
def get(self, pos):
return self.l[pos % len(self.l)]
def vadd(vec1, vec2):
return (sum(x) for x in zip(vec1, vec2)) |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the climbingLeaderboard function below.
def binarySearch (arr, l, r, x):
if r >= l:
mid = int(l + (r - l)/2)
if arr[mid] == x:
return mid
elif arr[mid] < x:
return binarySearch(arr, l, mid-1, x)
else:
return binarySearch(arr, mid + 1, r, x)
else:
return l
def climbingLeaderboard(scores, alice):
sco = sorted(list(set(scores)))[::-1]
res = []
for i in range(len(alice)):
if alice[i] >= sco[0]:
res.append(1)
elif alice[i] < sco[len(sco)-1]:
res.append(len(sco)+1)
else:
res.append(binarySearch(sco, 0, len(sco), alice[i])+1)
return res
return res
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
scores_count = int(input())
scores = list(map(int, input().rstrip().split()))
alice_count = int(input())
alice = list(map(int, input().rstrip().split()))
result = climbingLeaderboard(scores, alice)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the stones function below.
def stones(n, a, b):
x = []
l = 0
h = n-1
for i in range(n):
temp = a*h + b*l
x.append(temp)
l+=1
h-=1
x = list(set(x))
x.sort()
return x
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
T = int(input())
for T_itr in range(T):
n = int(input())
a = int(input())
b = int(input())
result = stones(n, a, b)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the gameOfThrones function below.
def gameOfThrones(s):
arr = s
temp=[]
while len(arr)>0:
temp.append(arr[0])
arr = arr.replace(arr[0], "")
count=[]
print(temp)
for j in temp:
c =0
for k in range(len(s)):
if j == s[k]:
c+=1
count.append(c)
print (count)
odd=0
for i in count:
if i % 2 != 0:
odd+=1
if odd < 2:
return "YES"
else:
return "NO"
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = gameOfThrones(s)
fptr.write(result + '\n')
fptr.close()
|
import getpass
user_credentials = ['begueradj', 'password']
def get_user_credentials():
username = input('Username: ')
password = getpass.getpass('Password: ')
return username, password
def check_user_credentials(user_credentials):
username, password = get_user_credentials()
return user_credentials[0] == username and user_credentials[1] == password
if __name__ == "__main__":
login_attempts = 1
correct_credentials = check_user_credentials(user_credentials)
while not correct_credentials and login_attempts < 3:
print('\nWrong credentials, try again:')
correct_credentials = check_user_credentials(user_credentials)
login_attempts += 1
if correct_credentials:
print('Welcome! Do whatever work you need here ...')
else:
print('Game over!')
|
# -------------- Exercise 3 ----------------------------------------------------
# Write a function that computes cosine of the angle between two d-dimensional vectors.
# -------------- Code ---------------------------------------------------------
# importing to project numpy library
import numpy as np
# filling vectors array with vector coordinates points
def CosOfAngle(d):
# declaring array of vectors
vectors = []
#input
while True:
# if input string is digit, convert it into intiger
try:
#d = int(input('Enter dimension of 2 vectors: ')) -> we can also input number of dimensions - d - from keyboard
for i in range(2):
vector = []
for j in range(d):
vector.append(int(input('Enter a ' + str(j+1) + ' dimension point of vector '+ str(i+1) +' : ')))
vectors.append(vector)
break
# if not print an error
except ValueError:
print('That was no valid number. Try again...')
# dot product of two vectors
dotPrd = np.dot(vectors[0], vectors[1])
# vectors magnitude
vectorMag = []
for i in range(2):
vectorMag.append(np.linalg.norm(vectors[i]))
# cos of angle
cosAlfa = dotPrd/(vectorMag[0]*vectorMag[1])
# returning array of dimension and cos
#return [d, cosAlfa] if we input d from 'keyboard'
return cosAlfa
#number of dimensions of two vectors
d = 2
# the output of CosOfAngle function for d dimensions of two vectors
output = CosOfAngle(d)
# when we want put the number of dimensions - d - from keyboard then we must write in print str(output[0]) for d and str(output[1]) for cosOfAngle
print('Cosine of the angle between two ' + str(d) +' dimensional vectors is: ' + str(output)) |
# -------------- Exercise 5 ----------------------------------------------------
#Write a program that for two lists x and y (possibly of different sizes) returns a list of
#elements that are common between the lists.
# -------------- Code ---------------------------------------------------------
# two lists of diffrent sizes
x = [1,2,3,'a','b','c']
y = [3,4,5,2,'d','f','a','b','g']
# returning common elements of each set in 2 ways
def isCommon(a, b):
return ( set(a) & set(b) )
# printing the returned list from isCommon(a,b) function
print(isCommon(x,y))
## printing common elements of each set in 2 ways
print( set(x) & set(y) )
print( set(x).intersection(y) )
|
import random
import pygame
class Food(object):
"""
A Food object.
Members:
x, y: store the position of the food.
size: size of the food.
"""
def __init__(self, x, y, size=10):
""" Initialize block at given x, y position """
self.x = x
self.y = y
self.size = size
def generate_food(self, width, height):
""" Generate food at random location within the width and height """
self.x = round(random.randrange(0, width-210) / 10.0) * 10
self.y = round(random.randrange(0, height) / 10.0) * 10
return (self.x, self.y)
def draw(self, game_display, color):
""" Draws the food at x y position """
pygame.draw.rect(game_display, color, (self.x, self.y, self.size, self.size))
def get_pos(self):
""" Returns the position of food as a tuple """
return (self.x, self.y)
def get_rect(self):
""" Return rectangle object of the food for collision detection """
return pygame.Rect(self.x, self.y, self.size, self.size)
|
def sorting(dic):
return " ".join([key for key, val in sorted(dic.items(), key=lambda x: x[1])])
if __name__ == '__main__':
n = int(input())
dic = {}
for i in range(n):
student = input().split()
dic[student[0]] = int(student[1])
print(sorting(dic))
|
import json
def register():
print("You must register to view student information.")
qerar = input("Press 1 to continue, otherwise press 2 : ")
if qerar == "1":
WritingTeacher()
else:
print("Bye!")
def WritingTeacher():
def readData(_filename):
with open(_filename, "r") as conn:
return json.load(conn)
data = readData("database.json")
print("data : ", data)
def getDataFromUser():
print("Register teacher : ")
name = input("name : ")
surname = input("surname : ")
username = input("username : ")
password = int(input("password : "))
teacher = {
"name": name,
"surname": surname,
"username": username,
"password": password
}
data['teachers'].append(teacher)
getDataFromUser()
with open("database.json", "w") as conn:
json.dump(data, conn)
|
#Comma Code
spam = ['apples', 'bananas', 'tofu', 'cats']#define the lists that will need to be used to create the sentence, or multiple lists if desired
schedule = ['IT75' , 'IT100' , 'IT105' , 'IT110'] #secondary list to further test function
def corrected(list): #corrected will be defined as a function to be applied to the list, this will enable the function to be used on lists named other than spam.
counter = 0 #start a counter to keep track of number of loops.
newlist = '' #establishes newlist as an empty list, so that the items in spam can be inputed.
while counter < len(list) - 2: #run the while loop for all instances in the list except the last two as they need to be treated differently.
newlist = newlist + list[counter] + ', ' #adds to newlist and makes it equal to what it adds. Here it is adding whatever item the list counter is on in addition to a comma afterwards.
counter = counter + 1 #add 1 to the counter, and restart loop until the length condition is met.
newlist = newlist + list[-2] + ' ,and ' #the second to last item within the list, [-2], is added to the newlist with the addition of ,and to make the sentence work.
newlist = newlist + list[-1] + '.' #the last item in the list achieved by going backwards [-1], has a period added afterwards to close out the sentence.
return newlist #the newlist is the output of the function corrected being applied to the list.
print(corrected(spam)) #prints the function corrected applied to the list spam.
print('My schedule this semester includes: ' + corrected(schedule)) #prints secondary list after the writing.
|
def read_lines():
with open('students.txt') as f:
new_names = f.read()
list_of_words = new_names.split()
new_dict = dict()
for key in list_of_words:
new_dict[key] = ''
print (new_dict)
read_lines()
|
a = int(input("Nhap so thu 1: "))
b = int(input("Nhap so thu 2: "))
print("\nSo da nhap a: "+str(a)+" b:"+str(b))
print("\nPhep cong: "+str(a+b))
print("\nPhep tru: "+str(a-b))
print("\nPhep nhan: "+str(a*b))
print("\nPhep chia: "+str(a/b)) |
print("-----------Tinh thue cho nhan vien-----------")
a = int(input("Nhap so gio lam viec: "))
b = int(input("Luong theo gio: "))
if a > 40 :
tienThemGio = (a - 40)*b*1.5
luongTruocThue = 40 * b + tienThemGio
print("Muc luong truoc thue: " + str(luongTruocThue))
print("\nMuc luong sau thue: " + str(luongTruocThue * 0.9))
else:
print("Muc luong truoc thue: "+str(a*b))
print("\nMuc luong sau thue: "+str((a*b)* 0.9))
|
"""
Module contains class which parses CLI parameters.
"""
import argparse
class ArgParser:
"""Class for parsing CLI arguments
Attributes:
args (Namespace): Parsed arguments
"""
def __init__(self):
parse = argparse.ArgumentParser()
parse.add_argument("-c", "--config", type=str, required=False, help="Set path to config file")
self.args = parse.parse_args()
def get_config(self):
"""Method for getting argument for configuration.
Returns:
str: Path to configuration
"""
return self.args.config
|
import random
a = random.randrange(1, 1001)
b = 0
t = 0
while True:
print("try: " + str(t+1))
t=t+1
b = int(input())
if a > b:
print("answer is more big")
elif a == b:
print("the answer!")
break
else:
print("answer is more small")
print("the end")
|
#! /usr/bin/env python
# -*- coding:utf-8 -*-
from structure.stack import Stack
prece = {
'*': 3,
'/': 3,
'+': 2,
'-': 2,
'(': 1
}
def infix2postfix(exp):
opstack = Stack()
items = exp.split(' ')
res = list()
for item in items:
if item not in '+-*/()':
res.append(item)
elif item == '(':
opstack.push(item)
elif item == ')':
o = opstack.pop()
while o != '(':
res.append(o)
o = opstack.pop()
else:
while not opstack.is_empty() and prece[opstack.peek()] >= prece[item]:
res.append(opstack.pop())
opstack.push(item)
while not opstack.is_empty():
res.append(opstack.pop())
return ' '.join(res)
if __name__ == '__main__':
exp = 'A * B - C'
print infix2postfix(exp)
|
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
class Queue:
def __init__(self):
self.queue = list()
def is_empty(self):
return self.size() == 0
def enqueue(self, item):
self.queue.insert(0, item)
def dequeue(self):
return self.queue.pop()
def size(self):
return len(self.queue)
def josephus(index):
Q = Queue()
for x in range(ord('A'), ord('Z')+1):
Q.enqueue(chr(x))
print(Q.queue)
# pick a start pos to start counting
from random import randint
start = randint(1, Q.size())
while start > 1:
Q.enqueue(Q.dequeue())
start -= 1
pos = 1
while Q.size() > 1:
for x in range(index-1):
Q.enqueue(Q.dequeue())
Q.dequeue()
print(Q.queue)
return Q.dequeue()
if __name__ == '__main__':
print(josephus(4)) |
from threading import Thread
from threading import Lock
i=0
lock = Lock()
def thread1():
global i
for j in range(0,99999):
lock.acquire()
i += 1
lock.release()
def thread2():
global i
for j in range(0,99998):
lock.acquire()
i -= 1
lock.release()
def main():
mainThread_1 = Thread(target = thread1, args = (),)
mainThread_1.start()
mainThread_2 = Thread(target = thread2,args=(),)
mainThread_2.start()
mainThread_1.join()
mainThread_2.join()
print(i)
main()
|
def miller_rabin(n, k):
"""
Miller Rabin primality test for n
Will fail when n is a carmichael number
:param n: an integer greater than 1
:param k: number of random trials
:return: True if "probably prime", False otherwise
"""
if n % 2 == 0: # return false if even number
return False
elif n == 2 or n == 3:
return True
# First factorise n-1
s = 0
t = n - 1
while t % 2 == 0:
t = t//2
s += 1
for i in range(k):
a = rnd.randrange(2, n-1)
#if fast_expo(a, n-1, n) != 1:
if pow(a, n-1, n) != 1:
return False
else:
#old = fast_expo(a, t, n) # get a^((2^0)*t) first
old = pow(a, t, n)
for j in range(1, s):
new = pow(old, 2, n)
if new == 1 and (old != n-1 and old != 1):
return False
else:
old = new
return True # Finally passed all the tests so probably prime
|
##########################
# 输入右斜杠是转义字符
##########################
#print('\n\\\t\\')
################################
# 如果有很多的转义字符需要输出
################################3
#print(r'\\\n\\\abc')
###################################
# 换行的转义字符是 \n #2016-02-16
###################################
#print('a\nb')
# 如果一行文本中存在需要多次换行建议下面方法输入
#print('''line1
#line2
#line3'''k)
##################################
#python 的布尔值,注意是有大小写区分
###################################
#True,False
#print('3==3 with', 3==3)
#print('3==2 with', 3==2)
################################
#python运算符 or,and,not (小写)
###############################
#print('True and False with ',True and False)
#print('True and Ture with ',True and True)
#print('False and False with ',False and False)
#print('not False with ',not False)
####################################
#python的空值 ,None 表示 ,注意大小写
######################################
#i=None
#print(i)
###################
#python变量的定义
#说明
#python 不需要进行变量的声明就可以赋值,所以属于静态语言
###################
#----- 定义数字变量
#i=1
#j=1.00
#print(i)
#print(j)
#print (i+j)
#----- 定义字符变量
c = 'hello world!'
print(c)
r = 'hello python!'
print (c+' '+r)
abc = 'test'
print (abc)
|
### 1 使用@property 进行类的属性定义并进行属性验证
#class Student(object):
#
# @property
# def sex(self):
# return self.sex
#
# @sex.setter
# def sex(self,value):
# if value >= 100 or value <=0 :
# raise ValueError("年龄只能是1到99之间")
# self._sex = value
#
#
#kui = Student()
#kui.sex = 1000 ###年龄不在区间内会提示错误。
#
#
#
#### 2 多重继承
#
#class Animal(object):
# pass
#
#class Mammal(Animal): ###哺乳动物
# def call(self):
# print ('Mammal')
# return self
#
#class Bird(Animal): ###鸟类
# def call(self):
# print ('Mammal')
# return self
#
#class Runnable(Animal): ##能跑动物类
# def call(self):
# print ('Runnable')
# return self
#
# def run(self):
# print('runing')
# return self
#
#class Flyable(Animal):
# def call(self):
# print('Flyable')
# return self
#
# def fly(self):
# print('flying')
# return self
#
#
#
#class Dog(Mammal,Runnable): ###
# pass
#
#b = Dog()
#b.call()
#b.run()
#
##############################
#
# 3 定义类入门
#
##############################
####定义类的说明与名称 __str__是给使用者看的, __rptr__是给开发人员看的。
#
#class Stu(object):
# def __init__(self,value):
# self.name = value
# def __str__(self):
# return 'CLASS Stu'
# def __rptr__(self):
# return 'Class stu stu'
#
# # 为了节省时间,可以将__str__直接复制给__rptr__
# # __rptr__ = __str__
#
#
#print(dir(Stu))
#u = Stu('abc')
#print(u)
#u
#
### __iter__的使用 实现斐波那契数列
### 实现时循环会将类作为迭代对象 ,不停调用本身,直到运行了StopIteration()
#class Fib(object):
# def __init__(self):
# self.a,self.b = 0,1
#
# def __iter__(self):
# return selfStopIteration
#
# def __next__(self):
# self.a,self.b = self.b ,self.a + self.b
# if self.a >= 10000:
# raise StopIteration()
# return self.a
#http://javtorrent.re/censored/145535/
#for n in Fib():
# print(n)
#
#
#### __getitem__的使用 如果希望通过像调用Listn那样调用,比如 Fib()[5],会提示错误,因为使用__iter__不能实现进行具体的位置调用
#### ———getitem--就可以实现
#class Fib(object):
# def __init__(self):
# self.a,self.b = 1,2
#
# def __getitem__(self,value):
# a ,b = 0,1
# for n in range(value):
# a,b = b,a+b
# return a
#
#print(Fib()[8])
#print(Fib()[9])
#
##for a in Fib():
# print(a)
# if a>100:
# raise StopIteration()
#
####### 枚举类 ####
###导入枚举类
#from enum import Enum
### 第一种方法定义了一个枚举类
#month = Enum('moh',('aa','bb'))
#print(month)
#print(month.aa.value)
#print(month.bb.value)
### 第二种方法定义一个枚举类
from enum import Enum
class week(Enum):
Sun = 0
Mon = 1
Tue = 2
Wed = 3
m = week.Sun
print(m)
print(m.value)
|
# -*- coding: utf-8 -*
###############################
#python 高级特性
################################
###########################
# 切片的应用 2016-08-18
############################
#获取列表的某一部分的值
#list = ["a","b","c"]
#print(list[0:3])
#如果是从第一个元素取值的开始的,第一个元素可以不填
#print(list[:3])
#从第二个元素开i
#print(list[1:3])
#切片也支持从后面的元素取值,可以通过负数实现
#print(list[-3:])
#取100个数中的前10个
#list2 = list(range(100))
#print(list2[:10])
# tuple 其实也是列表的一种,也可以切片,切片的时候注意是”中括号“
#tp = (1,2,3,4,5)
#print(tp[:3])
# 中间间隔获取列表中的值, 第三个数字表示间隔的元素个数
#list_user = list(range(100))
#获取单数
#print(list_user[1::2] )
#获取双数
#print(list_user[0::2] )
#print(list_user[::10] )
##进行倒数输出 说明:第三个参数如果为负数,可实现倒数的方式生成列表
#print(list_user[-1::-1])
#print(list_user[:-10:-1])
#
##字符看成是list的一种可以用来截取字符串
#str_user = "abcdefg"
#print(str_user[:3])
#print(str_user[::3])
#print(str_user[-2:])
###列表对象的引用和复制
#list_one = list("abcdefg")
#list_two = list_one #这一句操作时,其实只是把list_one的内存地址赋予了list_two,它们还是同一个内存地址
#list_three = list_two[:]
#print(list_two)
#
#list_two[1:2] = (3,4)
#print(list_one)
#print(list_two)
#print(list_three)
#print(id(list_one))
#print(id(list_two))
#print(id(list_three))
#
#######################################
### 迭代 对象的使用 # 2016-08-22
#######################################
#
#dict_u = {'a':1,'b':2,'c':3, 'd':4}
#
# #知识点:dict并不是按照list方式进行存储,所以输出时并没有按照顺序输出
#for i in dict_u: #输出所有KEY值
# print(i);
#
#for i in dict_u.values(): # 输出所有value值,注意这里是values,有s
# print(i)
#
#
#for i in dict_u.items():
# print(i)
#
### 迭代对象 : 字符串
#str_u = "huangkui"
#for i in str_u:
#print(i);
### 判断对象是否为 迭代对象
#
#from collections import Iterable
#print(isinstance('abc',Iterable))
#print(isinstance(['a','b','c'],Iterable))
#print(isinstance(1234,Iterable))
#
### 迭代对象如果希望像 JAVA 那样下标循环,可以使用 enumerate 函数
### 把迭代对象转换成 ”索引,元素“对
#
#for i,j in enumerate('abc'):
# print(i,j)
#
#
### 如果一个dict元素对有多个值
#
#dict_u = [(1,'a'),(2,'b'),(3,'c')]
#
#for i,j in dict_u:
# print(i,j)
#
#################################
### 列表生成式 2016-08-22
################################
#利用函数 生成列表
#print( list(range(10)))
#print( list(range(1,11)))
## 生成[1*1,2*2.....10*10]的列表
#list_u = []
#for i in list(range(1,11)):
# list_u.append(i*i)
#print(list_u)
##另一种PYTHON的写法
#list_u = [i*i for i in list(range(1,11))]
#print(list_u)
## 两个FOR循环嵌套的列表生成式
## 知识点: 循环时第一个for先运行第一个循环,后一个FOR循环是嵌套在第一个FOR循环中的遍历结束后,在继续回到第一个FOR继续循环
#list_u =[i*j for i in list(range(1,11)) for j in list(range(5,8))]
#list_b =[i*j for i in list(range(5,8)) for j in list(range(1,11))]
#print(list_u)
#print(list_b)
#
## 用法举例1 : 检索输出当地目录 2016-08-23
#import os
#print([ i for i in os.listdir('.')])
## 用法举例2:对dict 两个KEY和VALUE同时迭代
#dict_u = {1:'a',2:'b',3:'c',4:'d'}
#print([ str(x) + ' = ' + str(y) for x,y in dict_u.items()])
### 练习题
###列表中有字符与数字,如果进行大小写转换时,数字转换时会出现错误。
###修正语法后进行处理
list_u = ['APPLE','BANBER','CAR',4,5,'DOOR']
###普通写法
print([i.lower() for i in list_u if isinstance(i,str) == True] )
### == True 其实可以省略,因为函数返回值就是布尔型
print([i.lower() for i in list_u if isinstance(i,str)] )
|
def first_user_input():
choice = input("Select an option 1, 2, 3, 4, 5 or (Q)uit: ")
return choice
def user_description():
description = input("Enter task description to search for: ")
return description
def time_taken():
time = int(input("Enter task duration: "))
return time
def add_already_made_task():
task = input("Please enter task description: ")
return task |
#!/usr/bin/env python3
class Polynomial():
""" Class for basic mathematical operations with polynomials
Operations : Add, Pow, derivative, at_value """
def __init__(self, *args, **kwargs):
""" There are several ways to create class instances
pol1 = Polynomial([1,-3,0,2])
pol2 = Polynomial(1,-3,0,2)
pol3 = Polynomial(x0=1,x3=2,x1=-3)
"""
self.polynom = list()
if args and isinstance(args[0], list):
self.polynom = args[0]
elif args:
self.polynom = list(args)
else:
for key, value in kwargs.items():
numbers = int(key.split("x")[1]) # get index for exmaple x7=1 => 7
for i in range(1 + numbers - len(self.polynom)): #
self.polynom.append(0) # append 0 to get to the right index
self.polynom[numbers] = value #set value to the index
for i in range(len(self.polynom) - 1, 0, -1): #delete excess 0 in the highest powers
if self.polynom[i] == 0: #if item is 0
del self.polynom[i] #delete it
else:
break # else break if item is not 0
def __str__(self):
"""
Method for print polynom in correct way
Input: pol1 = Polynomial([1,-3,0,2])
Input: pol2 = Polynomial(1,-3,0,2)
Input: pol3 = Polynomial(x0=1,x3=2,x1=-3)
Output: 2x^3 - 3x + 1
"""
temp_string = ""
length_of_polynom = len(self.polynom)
if length_of_polynom != 1: # if len of polynomial is not 1
for i in reversed(range(len(self.polynom))): # reverse the list [1,-3,0,2] into [2,0,-3,1] because 2 is 2x^3
if self.polynom[i] == 0: # if some item is 0 then continue
continue
if temp_string: # sign treatment
if self.polynom[i] > 0:
temp_string += " + "
else:
temp_string += " - "
if i == 1: #if x^1
if abs(self.polynom[1]) != 1: #if koeficinet is not 1 -> 2x
temp_string += "{0}x".format(str(abs(self.polynom[1]))) # 2x^1 -> 2x
else:
temp_string += "x" # if koeficient is 1 - 1x^1 -> x
elif i > 1: # if x^2 or more
if abs(self.polynom[i]) != 1: #if koeficinet is not 1
temp_string += "{0}x^{1}".format(str(abs(self.polynom[i])), i) # 2x^2
else: # if koeficinet is 1
temp_string += "x^{0}".format(i) # 1x^2 => x^2
else: # if x^0
temp_string += "{0}".format(str(abs(self.polynom[0]))) # if 2x^0 -> 2
return temp_string
else:# if len of polynom is 1, this is not polynom just number
temp_string += str(self.polynom[0]) # set this number
return temp_string # example: Polynomial(2) return 2
return temp_string
def __eq__(self, other):
"""Overrides default implementation of __eq__
pol1 = Polynomial([1,-3,0,2])
pol2 = Polynomial(1,-3,0,2)
Input: pol1 == pol2
Output: True
"""
if isinstance(self, other.__class__):
return self.polynom == other.polynom
return False
def __add__(self, other):
""" Method for sum two polynomials
Input: Polynomial(1,-3,0,2) + Polynomial(0, 2, 1)
Output: 2x^3 + x^2 - x + 1
"""
temp_list = []
length_of_self_polynom = len(self.polynom)
length_of_other_polynom = len(other.polynom)
if length_of_self_polynom > length_of_other_polynom:
temp_list = self.polynom.copy() # make a copy
for i in range(length_of_other_polynom):
temp_list[i] += other.polynom[i]
else:
temp_list = other.polynom.copy()
for i in range(length_of_self_polynom):
temp_list[i] += self.polynom[i]
return Polynomial(temp_list)
def __mul__(self, other):
""" Method for mul two polynomials
Overrides default implementation of __mul__
auxiliary function for pow function
"""
polynom_mul = [0] * (len(self.polynom) + len(other.polynom) + 1)
for i in range(len(self.polynom)):
for j in range(len(other.polynom)):
polynom_mul[i + j] += self.polynom[i] * other.polynom[j]
return Polynomial(polynom_mul)
def __pow__(self, power):
"""
Methods for pow polynom and number
Input: Polynomial(-1, 1) ** 2
Output: x^2 - 2x + 1
"""
if power < 0: # if power is negative then return error
raise ValueError("ERRO: Negative power")
elif power == 1: #if power is 1 then return original polynom (1,-3,0,2)**1 => 2x^3 - 3x + 1
return self
elif power == 0: #if power is 0 then return 1 because everything powered by 0 is 1 example : 2^0 => 1 , (1,-3,0,2)**0 => 1
return 1
else: # if power is more than 1
temp = self
for i in range(1,power):
temp *= self
return temp
def derivative(self):
"""
Methods for polynomial derivation
pol1 = Polynomial([1,-3,0,2])
Input: pol1.derivative()
Output: 6x^2 - 3
"""
temp = self.polynom.copy()
if len(self.polynom) != 1:
for i in range(len(self.polynom)):
temp[i] *= i
temp.pop(0) #pop first item from list because is equal 0
return Polynomial(temp)
else: # devrivation constants is 0 y = 2x + 1 ==> y´ = 2 , y = 3 => y´ = 0
return 0
def at_value(self, x, y=None):
"""
Method return value of polynomial for given x
pol1 = Polynomial([1,-3,0,2]) => 2x^3 -3x + 1
Just x set:
Input: pol1.at_value(2) => 2*2^3 - 3*2 + 1
Output: 11
If x,y set:
Input: pol1.at_value(2,3) => 2*3^3 - 3*3 + 1 => 46 (46 - 11) = 35
Output: 35
"""
x_result = 0
y_result = 0
for i in range(len(self.polynom)):
x_result += self.polynom[i] * (x ** i)# 2*2^3 - 3*2 + 1 ==> 11
if y is None:
return x_result # 11
else: # if y is set
for i in range(len(self.polynom)):
y_result += self.polynom[i] * (y ** i) #2*3^3 - 3*3 + 1 ==> 46
return y_result - x_result # (46 - 11) = 35
def test():
assert str(Polynomial(0,1,0,-1,4,-2,0,1,3,0)) == "3x^8 + x^7 - 2x^5 + 4x^4 - x^3 + x"
assert str(Polynomial([-5,1,0,-1,4,-2,0,1,3,0])) == "3x^8 + x^7 - 2x^5 + 4x^4 - x^3 + x - 5"
assert str(Polynomial(x7=1, x4=4, x8=3, x9=0, x0=0, x5=-2, x3= -1, x1=1)) == "3x^8 + x^7 - 2x^5 + 4x^4 - x^3 + x"
assert str(Polynomial(x2=0)) == "0"
assert str(Polynomial(x0=0)) == "0"
assert Polynomial(x0=2, x1=0, x3=0, x2=3) == Polynomial(2,0,3)
assert Polynomial(x2=0) == Polynomial(x0=0)
assert str(Polynomial(x0=1)+Polynomial(x1=1)) == "x + 1"
assert str(Polynomial([-1,1,1,0])+Polynomial(1,-1,1)) == "2x^2"
pol1 = Polynomial(x2=3, x0=1)
pol2 = Polynomial(x1=1, x3=0)
assert str(pol1+pol2) == "3x^2 + x + 1"
assert str(pol1+pol2) == "3x^2 + x + 1"
assert str(Polynomial(x0=-1,x1=1)**1) == "x - 1"
assert str(Polynomial(x0=-1,x1=1)**2) == "x^2 - 2x + 1"
pol3 = Polynomial(x0=-1,x1=1)
assert str(pol3**4) == "x^4 - 4x^3 + 6x^2 - 4x + 1"
assert str(pol3**4) == "x^4 - 4x^3 + 6x^2 - 4x + 1"
assert str(Polynomial(x0=2).derivative()) == "0"
assert str(Polynomial(x3=2,x1=3,x0=2).derivative()) == "6x^2 + 3"
assert str(Polynomial(x3=2,x1=3,x0=2).derivative().derivative()) == "12x"
pol4 = Polynomial(x3=2,x1=3,x0=2)
assert str(pol4.derivative()) == "6x^2 + 3"
assert str(pol4.derivative()) == "6x^2 + 3"
assert Polynomial(-2,3,4,-5).at_value(0) == -2
assert Polynomial(x2=3, x0=-1, x1=-2).at_value(3) == 20
assert Polynomial(x2=3, x0=-1, x1=-2).at_value(3,5) == 44
pol5 = Polynomial([1,0,-2])
assert pol5.at_value(-2.4) == -10.52
assert pol5.at_value(-2.4) == -10.52
assert pol5.at_value(-1,3.6) == -23.92
assert pol5.at_value(-1,3.6) == -23.92
if __name__ == '__main__':
test()
|
import webbrowser
class Movie():
"""This class store movie related information"""
def __init__(self, title, story_line, poster, movie_trailer, review):
"""this function will be called when a movie object is created
keyword argument:
self -- as a reference which called the constructor
title -- a movie title
story_line -- a movie story line
poster -- a movie poster
trailer -- a movie trailer
review -- a movie review
"""
self.title = title
self.story_line = story_line
self.trailer_youtube_url = movie_trailer
self.poster_image_url = poster
self.review = review
def show_trailer(self):
""" this function will open specific trailer
a movie"""
webbrowser.open(self.movie_trailer_url)
|
'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
total = 0
if "th" not in word:
return total
else:
total += 1 + count_th(word.replace("th", "lol", 1))
return total
print(count_th(""))
print(count_th("abcthxyz"))
print(count_th("abcthefthghith"))
print(count_th("thhtthht"))
print(count_th("THtHThth"))
# Source: https://www.tutorialspoint.com/python/string_replace.htm |
# -*- coding: utf-8 -*-
print "Hello this is km to mile converter"
while True:
km = int(raw_input("Enter Km: "))
convertion = 0.621371
miles = km * convertion
print "The distance in miles is:",miles
more = raw_input("Another conversion (y/n):".lower())
if more == "n":
break
print "end" |
# 创建字典
like_numbers = {
'yang yahu': [666, 777, 888, 999, 111, 222, 333, 444, 555],
'gao xiangzhou': [777, 675, 256, 342, 278, 999],
'yang yuhang': [888, 111, 125, 567, 789],
'li jianfeng': [999, 123, 234, 345, 456, 567, 678],
'yuan li': [256, 356, 456, 567, 678],
}
# 打印名字及喜欢的数字
for name, numbers in like_numbers.items():
print(f"\n{name.title()} likes these numbers: ")
for number in numbers:
print(f"\t{number}")
|
# 编写函数
def make_shirt(size, typeface):
"""显示T恤的尺寸和标志"""
print(f"\nThe size of the T-shirt is: {size} and the words of the T-shirt are: {typeface.title()}.")
make_shirt('XXL', 'I love you!')
make_shirt(size='XXL', typeface='I love you!') |
def find_file(filename):
"""
尝试读取文件,将其内容打印到屏幕上。
并在文件不存在时,捕获异常,打印一
条友好的消息。
"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
pass
else:
print(contents.rstrip())
# 文件列表
filenames = ['/home/yyh/Documents/Python_Crash_Course/Python-Crash-Course/VSCode_work/chapter10/data/cats.txt',
'/home/yyh/Documents/Python_Crash_Course/Python-Crash-Course/VSCode_work/chapter10/data/dogs.txt']
# 调用函数
for filename in filenames:
find_file(filename) |
# 创建字典
rivers = {'nile': 'egypt',
'Yangtze river': 'china',
'Yellow river': 'china',
}
# 为每条河流打印一条消息
for river, country in rivers.items():
print(f"The {river.title()} runs through {country.title()}.")
# 打印每条河流的名字
for river in rivers.keys():
print(river.title())
# 另一种表达
#for river in rivers:
# print(river.title())
# 打印每个国家的名字
for country in set(rivers.values()):
print(country.title()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.