text
stringlengths 37
1.41M
|
---|
import matplotlib.pyplot as plt
import numpy as np
import urllib2
# http_proxy enironment variable needs to be created first = http://username:password@proxyserver:proxyport
proxy = urllib2.ProxyHandler()
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)
# Grab the source CSV file directly from the US census website
input_file = urllib2.urlopen('http://www.census.gov/popest/data/national/totals/2011/files/NST_EST2011_ALLDATA.csv')
first_row = input_file.readline().strip()
column_names_list = first_row.split(",")
col_value = column_names_list.index("CENSUS2010POP")
col_name = column_names_list.index("NAME")
is_state_col = column_names_list.index("STATE")
pop_dict = {}
while input_file:
row = input_file.readline().strip()
row_data_list = row.split(",")
if row == "":
break
else:
if row_data_list[is_state_col] == '0':
pass
else:
value = int(row_data_list[col_value])/1e6
name = row_data_list[col_name]
pop_dict[name] = value
input_file.close()
# Since we can't actually sort a dictionary, instead, create a list of tuples such as...
# [(key1, value1), (key2, value2), ... (key_n, value_n)] and sort it by value desc
pop_tuple_by_value = sorted(pop_dict.items(), key=lambda x: x[1], reverse=True)
"""
print "Creating a list of tuples, sorted by key ascending..."
pop_tuple_by_key = sorted(pop_dict.items(), key=lambda x: x[0])
print pop_tuple_by_key"""
# Now store the state names and their respective population values in separate lists
state_name = []
state_pop = []
for key,value in pop_tuple_by_value:
state_name.append(key)
state_pop.append(value)
# But we just want the top 10 states
top10_state_name = []
top10_state_pop = []
for i in range(10):
top10_state_name.append(state_name[i])
top10_state_pop.append(state_pop[i])
# For horizontal bar chart, if you want longer bars to be shown at top, need to reverse the lists
top10_state_name.reverse()
top10_state_pop.reverse()
# horizontal bar chart
fig = plt.figure(1)
plt.barh(range(len(top10_state_name)), top10_state_pop, align='center')
#xlim(0,int(max(cens2000pop_data)+2))
plt.xlim(0,int(max(top10_state_pop)+2))
plt.xticks(np.arange(int(max(top10_state_pop)+2)), rotation=90, size='small')
plt.yticks(np.arange(len(top10_state_name)), top10_state_name)
plt.title('Top 10 US States By Population')
plt.xlabel("Population in Millions")
plt.ylabel("State Name")
plt.axis('auto')
plt.grid(True)
plt.show()
"""
# vertical bar chart
figure(1)
bar(range(len(top10_state_name)), top10_state_pop, align='center')
#xlim(0,int(max(cens2000pop_data)+2))
ylim(0,int(max(top10_state_pop)+2))
yticks(arange(int(max(top10_state_pop)+2)))
xticks(arange(len(top10_state_name)), top10_state_name)
title('Top 10 US States By Population')
xlabel("State Name")
ylabel("Population in Millions")
#axis('auto')
grid()"""
|
# This script only works if the input file is ANSI/ASCII text. It will not work if it is UTF-16
# If the input file is UTF-16, then use codecs module: codecs.open(myFile,mode='r',encoding='UTF-16')
import re # import the regular expressions package
# Enter the regular expression pattern here:
pattern = re.compile("[tT][oO][nN][eE][rR]")
input_file = open("d:\\_python26\\_mycode\\regex\\InputFile.txt",'r') # Open this file for read access only
output_file = open("d:\\_python26\\_mycode\\regex\\output.txt",'w') # Open/create this file for write access only
first_row = input_file.readline().strip() # strip() removes any possible "white" spaces, carriage returns, or newlines
# Get the number of commas in the the header row so that when we read in the data which may include text fields that
# can contain commas, we don't accidentally create too many columns when doing the split() method below
num_commas = first_row.count(",")
column_name = first_row+",\"MiningResult\""
output_file.write(column_name+"\n")
column_names_list = first_row.split(",")
while input_file:
# strip() removes any possible "white" spaces, carriage returns, or newlines at the beginning or end of the input line
line = input_file.readline().strip()
if line == "": # If we reach EOF, then end while loop
break
else:
# Now create a Python list containing the data elements separated by a comma. num_commas ensures that we have
# same number of columns as the header row
row_data = line.split(",",num_commas)
search_column = row_data[column_names_list.index("\"IncidentDescription\"")]
out_string = str(row_data)
# Since row_data/out_string is a Python list containing strings, there will be brackets and single quotes.
# Therefore, need to remove the left/right brackets, any single quotes or back slashes.
out_string = out_string.replace("[",'').replace("]",'').replace("'",'').replace("\\",'')
# str() adds a space between the comma and double quote
# which can cause problems when importing into certain applications (, ") -> (,")
out_string = out_string.replace(", \"",",\"")
# test to see if the search column has the pattern we're looking for
test = pattern.search(search_column)
if test:
output_file.write(out_string+",\"Match found\""+"\n")
else:
output_file.write(out_string+",\"\""+"\n")
print "Text miner has completed its process."
input_file.close()
output_file.close()
|
import pygame
from game.consts import WHITE
class Ball(pygame.sprite.Sprite):
def __init__(self, x, y, width=20, height=20):
super(Ball, self).__init__()
self.surf = pygame.Surface((width, height))
self.rect = self.surf.get_rect(left=x, top=y, width=width, height=height)
pygame.draw.circle(self.surf, WHITE, [5, 5], 3)
@staticmethod
def get_balls():
all_balls = pygame.sprite.Group()
for x in range(10, 390, 15):
for y in range(10, 390, 15):
# [50, 250, 100, 6],
# [100, 250, 6, 50],
# [250, 250, 100, 6],
# [300, 250, 6, 50],
if 55 <= y <= 60 or (145 <= x <= 250 and 100 <= y <= 190) or (50 <= x <= 150 and 250 <= y <= 255)\
or (250 <= x <= 350 and 250 <= y <= 255) or (x == 100 and 250 <= y <= 300)\
or (x == 295 and 250 <= y <= 300):
continue
ball = Ball(x, y)
all_balls.add(ball)
return all_balls
|
class Bird :
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print('Aaah')
self.hungry =False
class SongBird(Bird) :
def __init__(self):
# Bird.__init__(self)
super().__init__()
self.sound = 'kkkk'
def sing(self):
print(self.sound)
songbird = SongBird()
songbird.sing()
songbird.eat()
|
while True :
try :
x = int (input('Enter the first number :'))
y = int(input('enter the second number :'))
value = x/y
print('x/y is ' ,value)
except Exception as e :
print('invalid input . please try again ')
print(e)
else:
break
finally:
print('llllllllll')
from warnings import warn ,filterwarnings
# warn('handdfadfaffasdfa' ) # 警告;
filterwarnings('ignore')
warn('hanwenmao')
|
for letter in 'letter':
print ('dang qian zi mu ' ,letter)
seq = ['22','3333','4444'] # 序列
print('hanhanhan'.join(seq))
seq2 = ('22','33','44','55') #元祖
print('文茂'.join(seq2))
seq3 ={'22':1 ,'33':2 ,'44':3} # 字典
print('wenmao'.join(seq3))
|
#coding: utf-8
import re
import urllib, os
print """
===================================
Bienvenido al motor de busqueda MOS
===================================
Instrucciones de uso
Coloca las url de dos paginas que quieras
comparar luego coloca la palabra para tu
busqueda Si solo ponele recuerda que tienes
que quitarle la "https://" y listo disfruta del programa.
"""
class encontrar(object):
def pagina(self):
respuesta = 0
while (respuesta==0):
while True:
self.web=raw_input("Ingrese la primera pagina: https://")
self.we =raw_input("Ingrese la segunda pagina: https://")
self.pa =raw_input("Ingrese lo que desea buscar:")
https = "https://"
req = urllib.urlopen(https + self.web)
r = urllib.urlopen(https + self.we)
b = req.read()
bb = r.read()
p = len(re.findall(self.pa,b))
p1 = len(re.findall(self.pa,bb))
if p > p1:
print "la pagina recomendada es: ",self.web
print "cantidad de palabras encontradas: ", p
break
elif p == 0:
print "palabra no encontrada"
elif p1 ==0:
print "palabra no encrontrada"
else:
print "la pagina recomendada es: ",self.we
print "cantidad de palabras encontradas: ", p1
os.system("clear")
a = raw_input ("Desea salir? si/no ")
b = a.lower()
if b == "si":
respuesta = 0
elif b == "no":
break
respuesta = 1
else:
print "Debe ingresar una opción valida"
#c = encontrar()
p = encontrar()
#c.encontrar()
p.pagina()
#ys
|
# This code prints the current state of the board
def display_board(board):
boardlist = list(board)
table = f'\t|\t|\n {boardlist[6]}\t| {boardlist[7]}\t| {boardlist[8]}\n________|_______|________\n\t|\t|\n {boardlist[3]}\t| {boardlist[4]}\t| {boardlist[5]}\n________|_______|________\n\t|\t|\n {boardlist[0]}\t| {boardlist[1]}\t| {boardlist[2]}\n\t|\t|'
print(table)
def player_input():
# Set up Player1 and Player2 variables
Player1 = 0
Player2 = 0
while Player1 != 'X' or Player1 != 'O':
# Assign Player1 and Player2 to X or O. Give choice, force valid input
Player1 = input('Oy, shorty, you wanna be X or O? ')
if Player1 == 'X':
Player2 = 'O'
break
if Player1 == 'O':
Player2 = 'X'
break
else:
print('I said X or O numbnuts')
continue
def place_marker(board, marker, position):
# This code places either an X or O onto a position on the board
if marker == 'X':
board[position] = 'X'
if marker == 'O':
board[position] = 'O'
def win_check(board, mark):
# This code checks for the winner
while True:
if (board[0] == mark) and (board[1] == mark) and (board[2] == mark):
return True
break
if (board[3] == mark) and (board[4] == mark) and (board[5] == mark):
return True
break
if (board[6] == mark) and (board[7] == mark) and (board[8] == mark):
return True
break
if (board[0] == mark) and (board[3] == mark) and (board[6] == mark):
return True
break
if (board[1] == mark) and (board[4] == mark) and (board[7] == mark):
return True
break
if (board[2] == mark) and (board[5] == mark) and (board[8] == mark):
return True
break
if (board[0] == mark) and (board[4] == mark) and (board[8] == mark):
return True
break
if (board[2] == mark) and (board[4] == mark) and (board[6] == mark):
return True
break
break
import random
def choose_first():
# This code assigns a player to go first, the assignment of X or O could
# come after this to prevent confusion
first = random.randint(0,1)
if first == 0:
print('X goes first')
if first == 1:
print('O goes first')
return first
def space_check(board, position):
# Checks to see if there is actually space to enter a value
if board[position] == 'X':
return False
if board[position] == 'O':
return False
else:
return True
def full_board_check(board):
# Checks if the board is full
if '' in board:
return False
else:
return True
def player_choice(board):
# This is how a player inputs their desired position
while True:
print('Choose a number between 1 and 9!')
markposition = int(input()) - 1
if 0 <= (markposition) <= 8:
if space_check(theboard, markposition) is True:
return markposition
break
else:
print('That space is full')
continue
else:
print('Hah, I thought of that. Enter 1-9!')
continue
def replay():
# Depending on answer this will start the loop again, or finish it
print('Would you like to play again? y/n')
answer = input('')
if answer == 'y':
return True
if answer == 'n':
return False
print('Welcome to Tic Tac Toe!')
print('The winner is the person to get three of their symbol in a row!')
print('To enter your symbol into a space, look at the diagram below')
print('\t|\t|\n 7\t| 8\t| 9\n________|_______|________\n\t|\t|\n 4\t| 5\t| 6\n________|_______|________\n\t|\t|\n 1\t| 2\t| 3\n\t|\t|')
while True:
player_input()
first = choose_first()
theboard = ['','','','','','','','','']
display_board(theboard)
game_on = True
if first == 0:
while True:
place_marker(theboard, 'X', player_choice(theboard))
print('\n'*100)
display_board(theboard)
if win_check(theboard, 'X') == True:
print('X is the winner! You suck O.')
break
if full_board_check(theboard) == True:
print("It's a tie!")
break
place_marker(theboard, 'O', player_choice(theboard))
print('\n'*100)
display_board(theboard)
if win_check(theboard, 'O') == True:
print('O is the winner! You suck X.')
break
if full_board_check(theboard) == True:
print("It's a tie!")
break
else:
while True:
place_marker(theboard, 'O', player_choice(theboard))
print('\n'*100)
display_board(theboard)
if win_check(theboard, 'O') == True:
print('O is the winner! You suck X.')
break
if full_board_check(theboard) == True:
print("It's a tie!")
break
place_marker(theboard, 'X', player_choice(theboard))
print('\n'*100)
display_board(theboard)
if win_check(theboard, 'X') == True:
print('X is the winner! You suck O.')
break
if full_board_check(theboard) == True:
print("It's a tie!")
break
if replay() == True:
continue
else:
break
|
# -*- coding: utf-8 -*-
class AlphaMode(object):
"""
Class for the different stages of the game
AlphaMode.current_size is the size of the screen
AlphaMode.client_states is the upper class calling the state
"""
def __init__(self, screen_size, client_states):
self.current_size = screen_size
self.client_states = client_states
def resize(self, event):
"""
Passes a resize event to the current mode
:param event: the resize event
:return: nothing
"""
pass
def prepare(self):
"""
Prepares the screen on startup and screen resize
:return: nothing
"""
pass
def render(self, dest):
"""
Render the screen on a destionation surface
:param dest: the destination surface
:return: nothing
"""
pass
def iterate(self):
"""
Iterate some events on the modes
:return:
"""
pass
def notify(self, message):
"""
Notifies the mode for events
:param message: the message
:return: nothing
"""
pass
|
## @file triangle_adt.py
# @author Daniel Guoussev-Donskoi
# @brief A class that simulates a triangle, and several related methods
# @details A class simulating a triangle is initialised, with 3 variables
# @details The class assumes a, b and c are valid positive integer inputs
# representing it's sides
# @date January 21st, 2020
import math
from enum import Enum
#@brief A class that enumerates the 4 types of triangle in the requirements
#@details The 4 types are, equilateral, isoceles, scalene and right
class TriType(Enum):
equilat = "equilat"
isoceles = "isoceles"
scalene = "scalene"
right = "right"
class TriangleT:
#@brief Constructor for TriangleT
#@param a,b,c: 3 integer sides of triangle
def __init__(self, a, b ,c):
self.__a = a
self.__b = b
self.__c = c
#@brief Function to return sides of a TriangleT object
#@return final: Returns as tuple of integer sides of the TriangleT object
def get_sides(self):
a = self.__a
b = self.__b
c = self.__c
final = (a,b,c)
return final
#@brief Function to check if two triangles are equal
#@return Returns a boolean based on whether the two triangle objects are the same or not
def equal(self,other):
a = self.__a
b = self.__b
c = self.__c
d = other.__a
e = other.__b
f = other.__c
if ((a == d) & (b == e) & (c == f)):
return True
else:
return False
#@brief Function to return the perimeter of a triangle, as the sum of it's sides
#@return Returns an integer in final, that is the sum of the sides of a TriangleT object
def perim(self):
a = self.__a
b = self.__b
c = self.__c
final = a + b + c
return final
#@brief Function to calculate the area of a triangle using Heron's formula
#@return Returns an integer in area, that is the calculated area of the TriangleT object
def area(self):
a = self.__a
b = self.__b
c = self.__c
s= (a + b + c ) / 2
areabeforesqrt = (s * (s - a) * (s - b) * (s - c))
area = (areabeforesqrt ** 0.5)
return area
#@brief Function to determine if a triangle forms a triangle, using the inequality theorem
#@return Returns True if the sides form a valid triangle, False if they do not
def is_valid(self):
a = self.__a
b = self.__b
c = self.__c
if (a + b > c ) & ( a + c > b ) & ( b + c > a ):
return True
else:
return False
#@brief Function to determine which of the enumerated types a TriangleT type falls under
#@details The triangle can be a TriType of types equilateral, right, isoceles or scalene
#@details In the event a triangle is both right and isoceles, it is treated as right
#@return Returns an enumerated TriType object
def tri_type(self):
a = self.__a
b = self.__b
c = self.__c
if (a == b == c):
return TriType.equilat
elif ( a ** 2 + b **2 == c ** 2):
return TriType.right
elif ( a == b != c ) or (b == c != a) or (a == c != b):
return TriType.isoceles
else:
return TriType.scalene
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Yu Chen
#
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def binary_insert(root, node):
if root is None:
root = node
else:
if root.val > node.val:
if root.left == None:
root.left = node
else:
binary_insert(root.left, node)
else:
if root.right == None:
root.right = node
else:
binary_insert(root.right, node)
class Solution:
# @param p, a tree node
# @param q, a tree node
# @return a boolean
def is_same_tree(self, p, q):
if p == None and q == None:
return True
if p and q and p.val == q.val:
return self.is_same_tree(p.left, q.left) and self.is_same_tree(
p.right, q.right)
return False
|
# class Solution:
# # @param {integer} x
# # @return {boolean}
# def isPalindrome(self, x):
# source = str(x)
# length = len(source)
# for i in xrange(length/2):
# if (source[i] == source[length-1-i]):
# continue
# else:
# return False
# return True
# x = 12321
# sol = Solution()
# print sol.isPalindrome(x)
class Solution:
# @param {integer} x
# @return {boolean}
def isPalindrome(self, x):
old = x
new = 0
while (x != 0):
digit = x % 10
x /= 10
new = (new * 10 + digit)
if (new == old):
return True
else:
return False
x = 12344321
sol = Solution()
print sol.isPalindrome(x)
|
import archivos
opcion=0
archivo="foto.jpeg"
archivos.generarClave()
clave=archivos.cargarClave()
while opcion !=5:
print("\nSeleccione una opción\n")
print("1.-Leer Archivo\n2.-Agregar texto al archivo\n3.-Encriptar\n4.-Desencriptar\n5.-Salir")
opcion=int(input("Ingresa una opción: "))
if opcion==1:
print("El contenido del archivo es: ")
archivos.leerArchivo(archivo)
elif opcion==2:
linea=input("Introduce el texto que desea agregar al archivo: ")
archivos.escribirArchivo(linea,archivo)
elif opcion==3:
print("Encriptando archivo...")
archivos.encriptar(archivo,clave)
print("Archivo encriptado")
elif opcion==4:
print("Desencriptando archivo...")
archivos.desencriptar(archivo,clave)
print("Archivo desencriptado")
elif opcion==5:
exit()
else:
print("\nOpción incorrecta")
|
a=int(input())
for b in range(1,6)
print((a*b))
|
import sys,string
def isPalin(s) :
if s == s[::-1] : return True
else : return False
a = input()
b = list(a)
n = len(a)
for i in range(0,n) :
L2 = b[:]
L2.pop(i)
s2 = ''.join(L2)
if isPalin(s2) :
print('YES')
sys.exit()
print('NO')
|
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 3 14:24:54 2015
@author: yys
"""
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums = sorted(nums)
res = []
i = 0
l = len(nums)
if l == 0:
return res
while nums[i] <= 0 and i < l-1:
# i denotes start and j denotes end, move k from i to j
j = l-1
while nums[j] >= 0 and j > 0:
n = -(nums[i]+nums[j])
for k in xrange(i+1,j):
if nums[k] == n and [nums[i],nums[k],nums[j]] not in res:
res.append([nums[i],nums[k],nums[j]])
break
j -= 1
while nums[j] == nums[j+1] and j > 0:
j -= 1
i += 1
while nums[i] == nums[i-1] and i < l-1:
i += 1
return res
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 29 22:49:27 2015
@author: yys
"""
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def mergeKLists(lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
import heapq
queue = [(l.val, l) for l in lists if l]
heapq.heapify(queue)
dummy = ListNode(-1)
tail = dummy
while queue:
val, node = queue[0]
if node.next:
heapq.heapreplace(queue, (node.next.val, node.next))
else:
heapq.heappop(queue)
tail.next = node
tail = tail.next
return dummy.next
|
import time
import numpy as np
initial_state = tuple(input('input board state in the form (1,2,3),(4,5,6),(7,8,0) : '))
start_time = time.time()
goal_state = ((1,2,3),(4,5,6),(7,8,0))
moves_state = {"0": initial_state} # dictionary that pairs possible moves to game states
def check_solvable(game_state): # checks if the game state is solvable
inversions = []
game_state = list(np.array(game_state).flatten()) # flatten the 2d list
game_state.remove(0) # remove 0 from the list
for i in range(len(game_state)):
boolean_ary = (game_state[i] > game_state[i:]) # is current value greater then following values
inversion_indices = np.where(boolean_ary == True) # indices where this is true
inversions.append(len(inversion_indices[0])) # add these inversions to the list of inversions
num_inversions = np.sum(np.array(inversions)) # sum all the inversions
print('There are ' + str(num_inversions) + ' inversions')
if num_inversions % 2 != 0:
print('Game is unsolvable!')
return False
else:
return True
def effect_of_move(state, move): # returns the state of the game after a move has been preformed
state = np.array(state) # convert tuple to numpy array
index0 = np.where(state == 0) # find the index of 0 "the empty tile space"
if move == 'U': # empty space is moved upwards
index_move_tile = index0[0]-1, index0[1] # index of tile above empty space
elif move == 'D': # empty space is moved downwards
index_move_tile = index0[0]+1, index0[1] # index of tile below empty space
elif move == 'L': # empty space is moved left
index_move_tile = index0[0], index0[1]-1 # index of time to the left of empty space
elif move == 'R': # empty space is moved right
index_move_tile = index0[0], index0[1]+1 # index of tile to the right of empty space
state[index0] = state[index_move_tile] # place tile into empty space
state[index_move_tile] = 0 # create new empty space in place of the moved tile
return tuple(map(tuple, state)) # returns new state after the move was preformed, returns a tuple
def physically_allowable_moves(state): # returns list of allowable moves
moves = list()
state = np.array(state) # converts state to numpy array
index0 = np.where(state == 0) # index of the empty tile
if index0[1] < 2: # places allowable moves into move list
moves.append('R')
if index0[1] > 0:
moves.append('L')
if index0[0] > 0:
moves.append('U')
if index0[0] < 2:
moves.append('D')
return moves # returns list of allowable moves
def new_child_states_to_dict(state, key): # adds all possible new child states to dictionary from given state
moves = physically_allowable_moves(state) # get list of allowable moves from current state
previous_move = key[-1] # remove previous move from available moves
if previous_move == 'U':
moves.remove('D')
if previous_move == 'D':
moves.remove('U')
if previous_move == 'L':
moves.remove('R')
if previous_move == 'R':
moves.remove('L')
for move in moves: # for all new possible moves
new_state = effect_of_move(state, move) # find the new state after each possible move
if new_state not in moves_state.values(): # place any new states into the dictionary
moves_state[key + move] = new_state
def output_solution(plan): # outputs the steps needed to solve the game in a text file
file_object = open('nodePath.txt','w')
steps = []
moves = str(plan[0])
for i in range(len(moves)):
steps.append(moves)
moves = moves[:-1]
steps = steps[::-1]
i = 0
for step in steps:
state = moves_state[step]
file_object.write('--------- move: ' + str(i) + '\n')
file_object.write("|"+str(state[0][0]) +' '+str(state[0][1])+ ' ' +str(state[0][2])+"|"+'\n')
file_object.write("|" + str(state[1][0]) + ' ' + str(state[1][1]) + ' ' + str(state[1][2]) + "|"+'\n')
file_object.write("|" + str(state[2][0]) + ' ' + str(state[2][1]) + ' ' + str(state[2][2]) + "|"+'\n')
i = i+1
file_object.close()
def output_all_states(): # outputs all game states into a text file
file_object = open('Nodes.txt','w')
all_keys = moves_state.keys()
all_keys = sorted(all_keys)
for key in all_keys:
state = moves_state[key]
file_object.write('--------- moves: ' + str(key) + '\n')
file_object.write("|" + str(state[0][0]) + ' ' + str(state[0][1]) + ' ' + str(state[0][2])+"|" + '\n')
file_object.write("|" + str(state[1][0]) + ' ' + str(state[1][1]) + ' ' + str(state[1][2]) + "|"+'\n')
file_object.write("|" + str(state[2][0]) + ' ' + str(state[2][1]) + ' ' + str(state[2][2]) + "|"+'\n')
file_object.close()
def output_node_info():
file_object = open('NodesInfo.txt', 'w')
file_object1 = open('ordered_NodesInfo.txt', 'w')
all_keys = moves_state.keys()
all_keys = sorted(all_keys)
file_object.write(str(len(all_keys)) + ' states where explored to find the solution' + '\n')
i = 0
for key in all_keys:
parent_index = 0
if len(key) >=2:
parent_key = key[:-1]
parent_index = int((np.where(np.array(all_keys)==parent_key))[0])
file_object.write(str(i)+' '+str(parent_index)+'\n')
file_object1.write(str(key)+'\n')
i = i+1
file_object.close()
if not check_solvable(initial_state): # exit if game is unsolvable
exit()
while goal_state not in moves_state.values(): # continue to run until a solution is found
keys_to_explore = [x for x in moves_state if (len(x)) == len(max(moves_state, key=len))] # Only explore new states
# that extend from the longest previous sequence of moves. Prevents exploration into terminal child states
print(str(len(keys_to_explore)) + ' states will be explored : ' + 'at least ' +
str(len(max(keys_to_explore, key=len))) + ' moves will be needed')
for key in keys_to_explore: # find new child states
new_child_states_to_dict(moves_state[key], key)
plan = [plan for plan, state in moves_state.items() if state == goal_state] # pulls the solution from the dictionary
print "--------------------------------------------------------------------"
print("Puzzle solved in " + str(time.time()-start_time) + ' seconds')
print('Here is the solution!!')
print(plan)
# create text files
output_solution(plan)
output_all_states()
output_node_info()
|
##################################################################
# Notes: #
# You can import packages when you need, such as structures. #
# Feel free to write helper functions, but please don't use many #
# helper functions. #
##################################################################
from collections import deque
def dfs(testmap):
#dimension of the map
width = len(testmap)
length = len(testmap[0])
#record the index of starting location and ending location
index_2 = []
index_3 = []
for ms in testmap:
if 2 in ms:
index_2.append(testmap.index(ms))
index_2.append(ms.index(2))
if 3 in ms:
index_3.append(testmap.index(ms))
index_3.append(ms.index(3))
#starting location
stack = [[index_2[0], index_2[1]]]
while len(stack) > 0:
flag = False
current_index = stack[-1]
testmap[current_index[0]][current_index[1]] = 4
if ((current_index[0] == index_3[0]) & (current_index[1] == index_3[1])):
for item in stack:
if testmap[item[0]][item[1]] == 4:
testmap[item[0]][item[1]] = 5
break
#push adjacent elements into stack
if current_index[0] - 1 >= 0: #up
if (testmap[current_index[0] - 1][current_index[1]] == 0 or testmap[current_index[0] - 1][current_index[1]] == 3):
stack.append([current_index[0] - 1, current_index[1]])
flag = True
if current_index[1] - 1 >= 0: #left
if (testmap[current_index[0]][current_index[1] - 1] == 0) or (testmap[current_index[0]][current_index[1] - 1] == 3):
stack.append([current_index[0], current_index[1] - 1])
flag = True
if current_index[0] + 1 < width: #down
if (testmap[current_index[0] + 1][current_index[1]] == 0) or (testmap[current_index[0] + 1][current_index[1]] == 3):
stack.append([current_index[0] + 1, current_index[1]])
flag = True
if current_index[1] + 1 < length: #right
if (testmap[current_index[0]][current_index[1] + 1] == 0) or (testmap[current_index[0]][current_index[1] + 1] == 3):
stack.append([current_index[0], current_index[1] + 1])
flag = True
if flag == False:
stack.pop()
return testmap
def bfs(testmap):
#dimension of the map
width = len(testmap)
length = len(testmap[0])
#record the index of starting location and ending location
index_2 = []
index_3 = []
for ms in testmap:
if 2 in ms:
index_2.append(testmap.index(ms))
index_2.append(ms.index(2))
if 3 in ms:
index_3.append(testmap.index(ms))
index_3.append(ms.index(3))
#starting location
queue = deque([[index_2[0], index_2[1]]])
path = {}
while len(queue) > 0:
current_index = queue.popleft()
testmap[current_index[0]][current_index[1]] = 4
if ((current_index[0] == index_3[0]) & (current_index[1] == index_3[1])):
while current_index != index_2:
if testmap[current_index[0]][current_index[1]] == 4:
testmap[current_index[0]][current_index[1]] = 5
current_index = path[str(current_index[0]) + str(current_index[1])]
testmap[index_2[0]][index_2[1]] = 5
break
#push adjacent elements into queue
if current_index[1] + 1 < length: #right
if (testmap[current_index[0]][current_index[1] + 1] == 0) or (testmap[current_index[0]][current_index[1] + 1] == 3):
queue.append([current_index[0], current_index[1] + 1])
path[str(current_index[0]) + str(current_index[1] + 1)] = [current_index[0], current_index[1]]
if current_index[0] + 1 < width: #down
if (testmap[current_index[0] + 1][current_index[1]] == 0) or (testmap[current_index[0] + 1][current_index[1]] == 3):
queue.append([current_index[0] + 1, current_index[1]])
path[str(current_index[0] + 1) + str(current_index[1])] = [current_index[0], current_index[1]]
if current_index[1] - 1 >= 0: #left
if (testmap[current_index[0]][current_index[1] - 1] == 0) or (testmap[current_index[0]][current_index[1] - 1] == 3):
queue.append([current_index[0], current_index[1] - 1])
path[str(current_index[0]) + str(current_index[1] - 1)] = [current_index[0], current_index[1]]
if current_index[0] - 1 >= 0: #up
if (testmap[current_index[0] - 1][current_index[1]] == 0 or testmap[current_index[0] - 1][current_index[1]] == 3):
queue.append([current_index[0] - 1, current_index[1]])
path[str(current_index[0] - 1) + str(current_index[1])] = [current_index[0], current_index[1]]
return testmap
def a_star_search (dis_map, time_map, start,end):
scores = {}
open_nodes = {} #nodes not been expanded
close_nodes = {} #nodes been expanded
all_nodes = {}
pre_time = 0 #time from the first start node to the current start node
#time_from_start = {}
h = dis_map[end] #distance from each node to the end node
close_nodes[start] = h[start] #initialize the first start node, add to close_nodes
while True:
# f = g + h
g = {}
f = {}
#nodes that are available from the start node
time = time_map[start]
for each in time:
if time[each] != None:
g[each] = time[each]
for each in g:
f[each] = g[each] + h[each] + pre_time
all_nodes[each] = f[each]
open_nodes[each] = f[each]
if start == end:
break
scores[start] = f
for each in close_nodes:
if each in open_nodes:
open_nodes.pop(each)
min_value_item = min(zip(open_nodes.values(),open_nodes.keys()))
start = min_value_item[1]
close_nodes[start] = open_nodes[start]
open_nodes.pop(start)
pre_time = all_nodes[start] - h[start]
return scores
|
# 用户输入的内容
person = int(input('请输入: 剪刀(0) 石头(1) 布(2):'))
# 计算机输入的内容
import random
# random.randint(0, 10) # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 [0, 10] 0<=x<=10
computer = random.randint(0, 2)
print(computer)
# 站在用户的角度上
# 用户赢:
# 0 --> 2 1 ---> 0 2 ---> 1
# 假如说玩家胜利(剪刀 = 布 或者 石头 = 剪刀 或者 布 = 石头)
# 用户和电脑打平:
# 用户和电脑相等
# 用户输:
# 除了上面的那些情况,都是输
if (person == 0 and computer == 2) or (person == 1 and computer == 0) or (person == 2 and computer == 1):
print('用户赢')
elif person == computer:
print('用户和电脑打平')
else:
print('用户输')
|
def main():
a = "20,50,80"
# 分割字符串
print(a.split(","))
# 删除尾部的字符串
print(a.rstrip("80"))
# 判断一个变量的类型
# if type(a) == str:
# print("123")
if isinstance(a, str):
print("123")
if __name__ == '__main__':
main()
|
# - del:根据下标进行删除, 也可以删除掉整个列表对象,提前释放内存
# - pop:删除最后一个元素, 也可以删除单个指定元素 把删除的元素返回回来
# - remove:根据元素的值进行删除 如果要删除的元素值不再列表,会崩溃
# - clear: 清空这个列表 把列表中的元素删除干净,但是列表还在
# del
my_list = ['hello', 23, 3.14, 23, True, 23]
# print(my_list[2])
del my_list[2]
print(my_list)
# 特殊:
# del my_list
# print(my_list)
# pop
my_list1 = ['hello', 23, 3.14, 23, True]
# ret是删除的元素
ret = my_list1.pop()
print(ret)
print(my_list1)
# 指定删除元素
ret1 = my_list1.pop(2)
print(ret1)
print(my_list1)
# remove
my_list2 = ['hello', 23, 3.14, 23, True]
my_list2.remove(23)
print(my_list2)
# clear
# 清除
my_list3 = ['hello', 23, 3.14, 23, True]
my_list3.clear()
print(my_list3)
|
# 类型
# int 有符号的整形
# float 浮点型
# 布尔(bool) True False
# string (字符串) 简写: str
# 需求: 定义一个人的信息: 姓名 年龄 身高 是否是男的
# 姓名:
# 用的字符串类型: 格式: '内容部分' 或者 "内容部分"
# python里面有一个内置函数, 帮我们检测变量里面存放的数据类型
# type(变量名或者数值)
name = '小明'
# <class 'str'>
print(type(name))
# 年龄
age = 18
# <class 'int'>
print(type(age))
# 身高
height = 178.5
# <class 'float'>
print(type(height))
# 是否是男的
is_man = True
# <class 'bool'>
print(type(is_man))
age = 23
print(type('hello python'))
|
# print(num)
# NameError: name 'num' is notdefined
# NameError: 异常的类型
# name 'num' is notdefined 异常的描述
# NameError
# FileNotFoundError
# 捕获多种异常
# try:
# open('hm.txt', 'r')
# print(num)
# except (NameError, FileNotFoundError):
# print('发生异常了')
# 捕获所有的异常:
# try:
# # open('hm.txt', 'r')
# print(num)
# except:
# print('发生异常了')
try:
# open('hm.txt', 'r')
print(num)
except Exception:
print('发生异常了')
|
# 1) find
# Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
# mystr = 'hello world'
# ret1 = mystr.find('meihao')
# print(ret1)
# 2) index
# Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。
# ret2 = mystr.index('meihao')
# print(ret2)
# 3) count
# Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置
# mystr1 = 'hello world hello'
# ret3 = mystr1.count('l')
# print(ret3)
# 4) replace
# Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
# mystr2 = 'hello world hello'
# ret4 = mystr2.replace('hello', 'nihao', 1)
# print(ret4)
# 5) split
# Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
mystr3 = 'hello world hello'
ret5 = mystr3.split()
# print(ret5)
#
# mystr4 = 'hello world hello'
# ret6 = mystr4.split('l')
# print(ret6)
# 6) capitalize
# Python capitalize()将字符串的第一个字母变成大写,其他字母变小写。对于 8 位字节编码需要根据本地环境。
# name = 'hello wORld python'
# ret7 = name.capitalize()
# print(ret7)
# 7) title
# Python title() 方法返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())。
# name = 'hello wORld python'
# ret8 = name.title()
# print(ret8)
# 8) startswith
# Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。
# name = 'hello wORld python'
# ret9 = name.startswith('hllo ')
# print(ret9)
# 9) endswith
# Python endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。
# name = 'hello wORld python'
# ret10 = name.endswith('python')
# print(ret10)
# 10) lower
# Python lower() 方法转换字符串中所有大写字符为小写。
# name = 'Hello wORld python'
# ret10 = name.lower()
# print(ret10)
# 11) upper
# name = 'hello woeifdofojiwfdiwfe'
# ret10 = name.upper()
# print(ret10)
# 12) ljust : left 左 right 右
# name = 'hello python'
# ret10 = name.ljust(30, '*')
# print(ret10)
# 13) rjust
# name = 'hello python'
# ret10 = name.rjust(30, '*')
# print(ret10)
# center
name = 'hello'
newName = name.center(20, '8')
print(newName)
|
# 1) 添加元素
#
# append, extend, insert
# 列表是可变的, 字符串是不可变的
# 定义一个列表
my_list = ['hello', 2.3, 2323, True]
# append
my_list.append('world')
print(my_list)
my_list.append(['1', '2'])
print(my_list)
print('='*40)
# extend
my_list1 = ['hello', 2.3, 2323, True]
my_list1.extend('world')
print(my_list1)
# 下面的用法是错误的: 因为int不能遍历:
# TypeError: 'int' object is not iterable
# my_list1.extend(123)
# print(my_list1)
my_list1.extend(['1', '2'])
print(my_list1)
# insert
my_list2 = ['hello', 2.3, 2323, True]
my_list2.insert(2, 'world')
print(my_list2)
|
def add2Num(a, b):
result = a + b
print(result)
# print(a + b)
num1 = add2Num(10, 12)
print(num1)
|
# 导包 unittest、三角形函数、读取xml数据类
import unittest
from UT.Day02.Code.sjx import Sjx
from UT.Day02.ReadData.read_xml import Read_Xml
# 实例化三角形
sjxClass=Sjx()
# 实例化读取xml类
readXmlClass=Read_Xml()
class Test_Xml(unittest.TestCase):
def test001(self):
for i in range(readXmlClass.get_len("bian")):
# 目的测试三角形程序
result=sjxClass.sjx(int(readXmlClass.readXml("bian",i,"b1")),
int(readXmlClass.readXml("bian", i, "b2")),
int(readXmlClass.readXml("bian", i, "b3")))
# 添加断言,判断三角形程序返回的结果是否符合我们预期结果
self.assertEqual(result,readXmlClass.readXml("bian", i, "expect"))
print(readXmlClass.readXml("bian",i,"b1"),
readXmlClass.readXml("bian", i, "b2"),
readXmlClass.readXml("bian", i, "b3"),
readXmlClass.readXml("bian", i, "expect"),"--》验证通过")
|
my_list = ['哈哈' for x in range(10)]
print(my_list)
my_list1 = ['%d' % (i + 1) for i in range(5)]
my_list1 = [str(i+1) for i in range(5)]
print(my_list1)
|
# 字典
# name age
# 保存信息:
# 小明: {'name':'xiaoming', 'age':23}
# 小红: {'name':'xiaohong', 'age':23}
dict = {'xiaoming':{'name':'xiaoming', 'age':23}, 'xiaohong':{'name':'xiaohong', 'age':23}}
# 删除信息:
# del
# del dict['xiaoming']
# print(dict)
# 修改:
dict['xiaoming']['age'] = 32
# 查看
age = dict['xiaoming']['age']
|
def function():
print('function')
def func():
print('func')
# 加法的练习:
def add2num():
num1 = 10
num2 = 12
result = num1 + num2
print(result)
add2num()
func()
func()
func()
def hah():
name = 'wangwen'
age = 19
print('名字是:%s'%name)
print('年龄是:%s'%age)
hah()
def print_func():
'''
打印输出一句话
'''
print('这是个函数')
help(len)
help(print_func)
|
__author__ = "Jorge Melguizo"
__copyright__ = "Copyright 2018, Trolls Detector"
class Node():
key = 0
def __init__(self, key):
self.key = key
#self.word = word
self.left = None
self.right = None
class AVLTree():
def __init__(self, *args):
self.node = None
self.height = -1
self.balance = 0
if len(args) == 1:
for i in args[0]:
self.insert(i)
def height(self):
if self.node:
return self.node.height
else:
return 0
def is_leaf(self):
return (self.height == 0)
def insert(self, key):
tree = self.node
newnode = Node(key)
if tree == None:
self.node = newnode
self.node.left = AVLTree()
self.node.right = AVLTree()
elif key < tree.key:
self.node.left.insert(key)
elif key > tree.key:
self.node.right.insert(key)
#else:
#print("Word [" + str(key) + "] already in tree.")
self.sway()
'''
Rebalance tree
'''
def sway(self):
# key inserted. Let's check if we're balanced
self.update_heights(False)
self.update_balances(False)
while self.balance < -1 or self.balance > 1:
if self.balance > 1:
if self.node.left.balance < 0:
self.node.left.left_rotate() # we're in case II
self.update_heights()
self.update_balances()
self.right_rotate()
self.update_heights()
self.update_balances()
if self.balance < -1:
if self.node.right.balance > 0:
self.node.right.sway() # we're in case III
self.update_heights()
self.update_balances()
self.left_rotate()
self.update_heights()
self.update_balances()
def right_rotate(self):
# Rotate left pivoting on self
A = self.node
B = self.node.left.node
T = B.right.node
self.node = B
B.right.node = A
A.left.node = T
def left_rotate(self):
# Rotate left pivoting on self
A = self.node
B = self.node.right.node
T = B.left.node
self.node = B
B.left.node = A
A.right.node = T
def update_heights(self, recurse=True):
if not self.node == None:
if recurse:
if self.node.left != None:
self.node.left.update_heights()
if self.node.right != None:
self.node.right.update_heights()
self.height = max(self.node.left.height,
self.node.right.height) + 1
else:
self.height = -1
def update_balances(self, recurse=True):
if not self.node == None:
if recurse:
if self.node.left != None:
self.node.left.update_balances()
if self.node.right != None:
self.node.right.update_balances()
self.balance = self.node.left.height - self.node.right.height
else:
self.balance = 0
def delete(self, key):
if self.node != None:
if self.node.key == key:
if self.node.left.node == None and self.node.right.node == None:
self.node = None # leaves can be killed at will
# if only one subtree, take that
elif self.node.left.node == None:
self.node = self.node.right.node
elif self.node.right.node == None:
self.node = self.node.left.node
# worst-case: both children present. Find logical successor
else:
replacement = self.successor(self.node)
if replacement != None: # sanity check
self.node.key = replacement.key
# replaced. Now delete the key from right child
self.node.right.delete(replacement.key)
self.sway()
return
elif key < self.node.key:
self.node.left.delete(key)
elif key > self.node.key:
self.node.right.delete(key)
self.sway()
else:
return
def predecessor(self, node):
node = node.left.node
if node != None:
while node.right != None:
if node.right.node == None:
return node
else:
node = node.right.node
return node
def successor(self, node):
node = node.right.node
if node != None: # just a sanity check
while node.left != None:
if node.left.node == None:
return node
else:
node = node.left.node
return node
def check_balanced(self):
if self == None or self.node == None:
return True
# We always need to make sure we are balanced
self.update_heights()
self.update_balances()
return ((abs(self.balance) < 2) and self.node.left.check_balanced() and self.node.right.check_balanced())
def insert_array(self, array):
for word in array:
self.insert(word)
''''
El algoritmo
'''''
def find_words_in_text(self, text, word_mark, empty_words_tree):
import Utils
found_list = []
text_words = text.split()
return_value = index_text_word = 0
while index_text_word < len(text_words):
end = 0
aux_tree = self
while end == 0:
if aux_tree.node != None and index_text_word < len(text_words):
word_in_tree = aux_tree.node.key.split()
#print(word_in_tree) #word we are searching
j = 0
if len(word_in_tree) != 0:
if Utils.stem(word_in_tree[j].lower()) == Utils.stem(text_words[index_text_word].lower()): # la hemos encontrado chic@s!
found_list.append(word_in_tree[j])
j = ok = end = 1
return_value += word_mark
while j < len(word_in_tree) and ok == 1:
if (index_text_word + j) < len(text_words):
if False == empty_words_tree.find_word(word_in_tree[j]):
#print('mirando: ---------------', text_words[index_text_word + j],word_in_tree[j], word_in_tree)
if Utils.stem(word_in_tree[j].lower()) == Utils.stem(text_words[index_text_word+j].lower()) :
#print('+subPalabra encontrada!', word_in_tree[j])
return_value += word_mark
else:
return_value -= word_mark
#print('-subPalabra eliminada!', word_in_tree, text_words[index_text_word])
ok = 0
else:
ok = 0
j += 1
elif text_words[index_text_word] < word_in_tree[0]:
aux_tree = aux_tree.node.left
elif text_words[index_text_word] > word_in_tree[0]:
aux_tree = aux_tree.node.right
else:
end = 1
else:
end = 1
index_text_word+=1
return return_value, found_list
''''
Encontrar una palabra
'''''
def find_word(self, word_to_find):
end= 0
aux_tree = self
while end == 0:
if aux_tree.node != None :
word_in_tree = aux_tree.node.key
if word_in_tree == word_to_find: # la hemos encontrado chic@s!
#print(word_to_find,'<------------')
return True
elif word_to_find < word_in_tree:
aux_tree = aux_tree.node.left
elif word_to_find > word_in_tree:
aux_tree = aux_tree.node.right
else:
end = 1
return False
|
# Run this code as command line code, main input: -r, -num, - o
import argparse
import cv2
import os
import numpy
# to rotate the image
def rotation(img,angle,num,arg):
img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
rows, cols = img.shape
centre = (cols/2,rows/2)
path = 'F:\GDP\G'
if arg:
for i in range(num):
M = cv2.getRotationMatrix2D(centre,angle*i,1)
dst = cv2.warpAffine(img,M,(cols,rows))
cv2.imwrite(os.path.join(path,'image_'+str(i)+'.jpg'),dst)
def Main():
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--rotation", help="random rotation of image from 0 to rotation angle", type=int, default=0)
parser.add_argument("-num","--numItr", help="Number of Iteration", type =int)
parser.add_argument("-o","--output",help="output the result to a file", action = "store_true")
args = parser.parse_args()
rall_img = cv2.imread('binary_image.png')
rotation(rall_img,args.rotation,args.numItr,args.output)
if __name__ == '__main__':
Main()
print('The process is done.')
|
"""Houston control station file."""
import os
from control_station import ControlStation
def main():
"""Main script function."""
command_list = []
command = 'X'
while(command.upper() != ''):
command = input("Insert the command: (Empty enter to finish) \n")
if command.upper() != '':
command_list.insert(len(command_list), command)
station = ControlStation()
for command in command_list:
station.parse_command_line(command)
print("End of commands!")
print("Bye.")
if __name__ == "__main__":
os.system('clear')
main()
|
import pandas as pd
import numpy as np
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=labels)
print(df.info)#columns 資訊
print(df.describe())#所有統計數據
print("show first 3 data::",df.iloc[:3])#0、1、2
#df.head(3) any_method
print(df.loc[:,['animal','age']])#取出animal、age 兩列的資料
#df[['animal','age']]
print(df.loc[df.index[[3,4,8]],['animal','age']])
print(df[df['age'] > 3])
print(df[df['age'].isnull()])#取出age值缺失的行
print(df[(df['age']>2) & (df['age']<4)])#取出age在2,4間的行
df.loc['f','age'] = 1.5
print('visits sum:',df['visits'].sum())#計算某col總和
df.loc['k'] = [5.5,'doggy','no',1]#插入
df = df.drop('k')#刪除
print(df['animal'].value_counts())
#先按age降序排列,後按visits升序排列
df.sort_values(by=['age', 'visits'], ascending=[False, True])
df['priority'] = df['priority'].map({'yes':True,'no':False})
|
"""
Given an array of strings, return all groups of strings that are anagrams. Represent a group by a list of integers representing the index in the original list. Look at the sample case for clarification.
Anagram : a word, phrase, or name formed by rearranging the letters of another, such as 'spar', formed from 'rasp'
Note: All inputs will be in lower-case.
Example :
Input : cat dog god tca
Output : [[1, 4], [2, 3]]
cat and tca are anagrams which correspond to index 1 and 4.
dog and god are another set of anagrams which correspond to index 2 and 3.
The indices are 1 based ( the first element has index 1 instead of index 0).
"""
def anagrams(self, A):
hashmap = dict()
for i in range(0,len(A)):
x = sorted(list(A[i]))
x = str(''.join(x))
if x in hashmap:
hashmap[x].append(i+1)
else:
hashmap[x] = [i+1]
result = []
for key in hashmap.keys():
result.append(hashmap[key])
return result
print anagrams(['cat', 'dog', 'god', 'tca'])
|
#INFIX COMPUTATION: Enter a string like "1+2-(3/4)*5" and get the result
def operation(string):
#we have to use parser in this function
if string[1]=='+':
return str(float(string[0]) + float(string[2]))
elif string[1]=='-':
return str(float(string[0]) - float(string[2]))
elif string[1]=='/':
return str(float(string[0]) / float(string[2]))
elif string[1]=='*':
return str(float(string[0]) * float(string[2]))
#elif string[1]==".": #Find a way to handle this situation. One way is to enter the stack one by one i.e by using for loop
# result = []
# result.append("".join(string))
# return str(result[0])
else:
return "wrong operator:" + str(string[1])
def parentheses(stack):
if stack.count('(')==stack.count(')'):
for i in range(0,len(stack)):
if stack[i]=='(':
index = i
elif stack[i]==')':
start = index
stack[start] = operators(stack[start+1:i])
for x in range(start+1,i+1):
stack[x] = " "
break
else:
pass
while stack.count(" ")!=0:
del stack[stack.index(" ")]
if stack.count("(")!=0 and stack.count(")")!=0 and stack.count("(")==stack.count(")"):
stack = parentheses(stack)
else:
stack = operators(stack)
else:
print "Entered string does not have balanced parantheses"
return stack
def operators(stack):
for i in range(0,len(stack)):
if stack[i] in "+-*/.":
start = i
stack[start+1] = operation(stack[start-1:start+2])
for x in range(start-1,start+1):
stack[x] = " "
else:
pass
result = stack.pop()
return result
stack = list(raw_input("Enter the string to be calculated\n"))
stack = parentheses(stack)
print "\nResult of the entered string is: ", stack
print "\n"
|
def sqrt1(A):
if A==2 or A==1:
return 1
arr = [0]*(A+2)
for i in range(0,A+2):
arr[i] = i*i
start = 0
end = len(arr)-1
while(start+1<end):
mid = start + (end+start)/2
if(arr[mid]==A):
return mid
if(arr[mid]>A):
end = mid
elif(arr[mid]<A):
start = mid
return start
def sqrt2(A):
if A == 1:
return 1
low = 0
high = A/2 + 1
while low+1<high:
mid=low+(high-low)/2
square=mid**2
if square==A:
return mid
elif square<A:
low=mid
else:
high=mid
return low
print sqrt2(5)
|
def insertion_sort(arr):
for i in range(1,len(arr)):
value = arr[i]
hole = i
while(hole > 0 and arr[hole-1] > value):
arr[hole] = arr[hole-1]
hole -= 1
arr[hole] = value
print arr
arr = [1,5,3,8,6,54,2,4,23,532]
insertion_sort(arr)
|
# @param A : tuple of integers
# @return an integer
def singleNumber(A):
bits = [0]*32
for i in A:
C = list(bin(i))
C = C[2:]
C = C[::-1]
print C
index = 0
for i in C:
#print i,bits[index]
bits[index] = bits[index]^int(i)
index += 1
bits = bits[::-1]
print bits
result = ""
for i in bits:
result += str(i)
return int(result,2)
print singleNumber([1,1,2,2,44,33,44,56,78,56,33])
|
def binary_search(arr,start,end,searchItem):
if (start <= end):
middle = (start+end)//2
if (searchItem == arr[middle]):
print "Found at: " + str(middle)
elif (searchItem > arr[middle]):
binary_search(arr,middle+1,end,searchItem)
elif (searchItem < arr[middle]):
binary_search(arr,start,middle-1,searchItem)
arr = [1,4,7,8,5,88,45,75,36,874,67,32,78,31]
arr.sort()
print "\n"
print arr
print "\n"
binary_search(arr,0,len(arr)-1,7)
|
'''
COMP4290 Group Project
Team: On Course
Alexander Rowell (z5116848), Eleni Dimitriadis (z5191013), Emily Chen (z5098910)
George Fidler (z5160384), Kevin Ni (z5025098)
courseEnrollment.py
Implementation of the CourseEnrollment class, which represents an enrollment in
a course. This contains the course enrolled in and the term in which the course
will be taken.
'''
from . import course
from . import term
from . import api
class CourseEnrollment(object):
def __init__(self, course: 'course.Course', term: term.Term):
self.course = course
self.term = term
def __repr__(self) -> str:
return f'<CourseEnrollment course={self.course!r}, term={self.term!r}>'
def course_code(self) -> str:
return self.course.course_code
def course_name(self) -> str:
return self.course.name
def units(self) -> int:
return self.course.units
# override equality
def __eq__(self, other) -> bool: # For x == y
if (isinstance(other, CourseEnrollment) and
self.course == other.course and self.term == other.term):
return True
else:
return False
|
#!/usr/bin/python3
def no_c(my_string):
new_string = my_string[:]
for c in my_string:
if (c is 'c' or c is 'C'):
idx = new_string.index(c)
new_string = new_string[:idx]+new_string[idx + 1:]
return new_string
|
#!/usr/bin/python3
def complex_delete(a_dictionary, value):
if a_dictionary is None:
return None
keys = list(a_dictionary.keys())
for k in keys:
if a_dictionary[k] is value:
a_dictionary.pop(k, None)
return a_dictionary
|
#!/usr/bin/python3
def best_score(a_dictionary):
if a_dictionary is None or len(a_dictionary) is 0:
return None
best = next(iter(a_dictionary))
max = a_dictionary[best]
for k in a_dictionary.keys():
if a_dictionary[k] > max:
max = a_dictionary[k]
best = k
return best
|
#!/usr/bin/python3
"""
Singly linked list
class Node and class SinglyLinkedList
"""
class Node:
"""Node class"""
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
@property
def data(self):
return self.__data
@data.setter
def data(self, value):
if (type(value) is not int):
raise TypeError("data must be an integer")
self.__data = value
@property
def next_node(self):
return self.__next_node
@next_node.setter
def next_node(self, value):
if value is None:
self.__next_node = None
return
if (type(value) is not Node):
raise TypeError("next_node must be a Node object")
self.__next_node = value
class SinglyLinkedList:
"""List class"""
def __init__(self):
self.__head = None
def sorted_insert(self, value):
mynode = Node(value)
if self.__head is None:
self.__head = mynode
else:
h_node = self.__head
if value < h_node.data:
mynode.next_node = h_node
self.__head = mynode
else:
while (h_node.next_node is not None):
if value < h_node.next_node.data:
break
h_node = h_node.next_node
mynode.next_node = h_node.next_node
h_node.next_node = mynode
def __str__(self):
if self.__head is None:
return ""
text = ""
h_node = self.__head
text = text+str(h_node.data)
while(h_node.next_node is not None):
h_node = h_node.next_node
text = text+"\n"+str(h_node.data)
return text
|
#!/usr/bin/python3
def uppercase(str):
nstr = ""
for i in range(len(str)):
if (str[i].islower()):
nstr += chr(ord(str[i]) - 32)
else:
nstr += str[i]
print("{}".format(nstr))
|
from tkinter import*
root = Tk()
#creating a label widget
myLabel1=Label(root,text="Hello world!")
#putting it onto the screen
#myLabel.pack()
myLabel2=Label(root,text="My name is XYZ")
myLabel1.grid(row=0,column=0)
myLabel2.grid(row=1,column=0)
myLabel3=Label(root,text="Here we go....").grid(row=2,column=0)
root.mainloop()
|
# Thomas O'Brien ID 10354795
# Calculator UI program
# this program sets up a Class called Calculator that can be called from other programs to run calculations.
# The algroithm for each type of calculation is defined as a function that can be called from other programs.
# The maths function is imported to program so that itcan be used as required.
#
# Note: For division, an additional check is included to identify divide by zero errors.
# Note: For Tan an additional check is included to identify errors.
import math
class Calculator(object):
def add(self, x, y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
return x + y
else:
raise ValueError
def subtract(self, x, y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
return x - y
else:
raise ValueError
def multiply(self, x, y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
return x * y
else:
raise ValueError
def divide(self, x, y):
number_types = (int, long, float, complex)
#
# Note: for division, include divide by zero check to avoid errors.
#
if isinstance(x, number_types) and isinstance(y, number_types):
if y != 0:
return x / y
else:
print '\n\n***** divide by zero error *****'
else:
raise ValueError
def exponent(self, x, y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
return x ** y
else:
raise ValueError
def square_root(self, x):
number_types = (int, long, float, complex)
if isinstance(x, number_types):
return math.sqrt(x)
else:
raise ValueError
def square(self, x):
number_types = (int, long, float, complex)
if isinstance(x, number_types):
return x * x
else:
raise ValueError
def cube(self, x):
number_types = (int, long, float, complex)
if isinstance(x, number_types):
return x * x * x
else:
raise ValueError
def sin(self, x):
number_types = (int, long, float, complex)
if isinstance(x, number_types):
return math.sin(x)
else:
raise ValueError
def cos(self, x):
number_types = (int, long, float, complex)
if isinstance(x, number_types):
return math.cos(x)
else:
raise ValueError
#
# Note: for the Tan function you have to guard against errors as 90 and 270 would return an error.
# Use the modulus calculation (%) to exclude 90, 270 and multiple of those numbers except 0 and 180.
# You also need to convert numbers entered to Radians first or Python will give wrong answer for Tan
#
def tan(self, x):
number_types = (int, long, float, complex)
if isinstance(x, number_types):
if x % 180 == 0:
return 0
elif x % 90 == 0:
return 'Error'
else:
return math.tan(math.radians(x))
else:
raise ValueError
|
#!/usr/bin/python
# another toy rot toy for use with any char-replacement cipher
import sys
myROT = 13
if (len(sys.argv) > 1 and sys.argv[0] == '-r'):
snothing = sys.argv.pop(0)
myROT = sys.argv.pop(0)
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
# Reversed Alphbet
#b = "zyxwvutsrqponmlkjihgfedcba"
#ROT13
b = "nopqrstuvwxyzabcdefghijklmNOPQRSTUBWXYZABCDEFGHIJKLM"
# Gil Bates
#b = "ubcdefghijnlmkopqrstavwxyz"
#b = "abcedfgkijhlmnopqrsutvwxyz"
def crypto(text):
output = ""
for i in range(0,len(text)):
index = a.find(text[i])
if index > -1:
output += b[index]
else:
output += text[i]
return output
if len(sys.argv) > 1:
ciphertext = sys.argv[1]
else:
ciphertext = sys.stdin.read()
print(crypto(ciphertext))
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#*--Honeywell Hackathon--*
# In[280]:
import numpy as np
import os
import queue as Q
import time
from IPython.display import clear_output
# In[281]:
MALL_SIZE = 12
# In[327]:
# Random Mall Scenario
def display(mall_size,route,shops,final=None,initial=None,End=None,Shopping_list=None):
for r in range(-1,mall_size+1):
for c in range(-1,mall_size+1):
if End!=None and r == End[0] and c==End[1]:
print( 'E',end =" "),
elif final!=None and r == final[0] and c==final[1]:
print( 'T',end =" "),
elif initial!=None and r == initial[0] and c==initial[1]:
print( 'I',end =" "),
elif Shopping_list!=None and [r,c] in Shopping_list:
print( 'U',end =" "),
elif [r,c] in route:
print( '-',end =" "),
elif [r,c] in shops:
print( 'S',end =" "),
elif r == -1 or r == mall_size:
print( 'X',end =" "),
elif c == -1 or c == mall_size:
print( 'X',end =" "),
else:
print( ' ',end =" "),
print()
print()
def create_random_mall(n):
shops = []
path = []
for i in range(0,n,2):
for j in range(0,n-1):
shops.append([j,i])
path.append([n-1,i])
# path.append([i,0])
for i in range(1,n,2):
for j in range(0,n):
path.append([j,i])
return shops, path
Shops,Paths = create_random_mall(MALL_SIZE)
display(MALL_SIZE,Paths,Shops)
# In[328]:
No_Shops = len(Shops)
pick = np.random.randint(No_Shops,size = int(0.2*No_Shops))
S = np.array(Shops)
shopping_list = S[pick].tolist()
# print(shopping_list)
S_L = shopping_list.copy()
display(MALL_SIZE,Paths,Shops,Shopping_list = shopping_list)
Source = [np.random.randint(1,MALL_SIZE,1)[0], MALL_SIZE-1]
# In[330]:
#Entry to MAll is at any point on the right alley - picked randomly:
shopping_list = S_L.copy()
Source_o = Source
End = Source
MALL = np.zeros([MALL_SIZE,MALL_SIZE])
for i in Shops:
MALL[i[0]][i[1]]=1
#Dijkstras Shortes Path Algo to find nearest Shop:
while(len(shopping_list)>=0):
pq = Q.PriorityQueue()
dist = np.full([MALL_SIZE,MALL_SIZE],np.inf)
parent = np.zeros([MALL_SIZE,MALL_SIZE,2])
pq.put([0,Source])
dist[Source[0]][Source[1]] = 0
direction = [[1,0],[-1,0],[0,1],[0,-1]]
parent[Source[0]][Source[1]] = [-1,-1]
# parent[Source[0]][Source[1]][1] = -1
while not pq.empty():
n = pq.get()[1];
for d in direction:
x = n[0] + d[0]
y = n[1] + d[1]
if(x>=0 and y>=0 and x<MALL_SIZE and y<MALL_SIZE and dist[x][y] > dist[n[0]][n[1]] + 1):
dist[x][y] = dist[n[0]][n[1]] + 1
parent[x][y] = n
if(MALL[x][y]==0):
pq.put([dist[x][y],[x,y]])
if(len(shopping_list)==0):
Source = End
m = dist[End[0]][End[1]]
Route = []
n_s = Source
n_s = parent[int(n_s[0])][int(n_s[1])]
while(parent[int(n_s[0])][int(n_s[1])][0]!=-1 or parent[int(n_s[0])][int(n_s[1])][1]!=-1 ):
Route.append(n_s)
n_s = parent[int(n_s[0])][int(n_s[1])]
Route.append(n_s)
for i in range(0,len(Route)):
Route[i] = Route[i].tolist()
time.sleep(2)
clear_output(wait=True)
display(MALL_SIZE,Route,Shops,Source,Source_o,End)
print("Distance - ", m)
break;
# print(parent)
m = np.inf
# print(shopping_list)
for s in shopping_list:
if(m>dist[s[0]][s[1]]):
m = dist[s[0]][s[1]]
Source = s
Route = []
n_s = Source
n_s = parent[int(n_s[0])][int(n_s[1])]
if(n_s[0]!=-1 or n_s[1]!=-1):
while(parent[int(n_s[0])][int(n_s[1])][0]!=-1 or parent[int(n_s[0])][int(n_s[1])][1]!=-1 ):
Route.append(n_s)
n_s = parent[int(n_s[0])][int(n_s[1])]
Route.append(n_s)
for i in range(0,len(Route)):
Route[i] = Route[i].tolist()
time.sleep(2)
clear_output(wait=True)
display(MALL_SIZE,Route,Shops,Source,Source_o,Shopping_list=shopping_list)
shopping_list.remove(Source)
Source_o = Source
print("Distance - ", m)
# In[ ]:
# In[ ]:
#
|
from collections import OrderedDict
tc=int(input())
for i in range(tc):
a=input()
my_list=""
for j in range(0,len(a),2):
my_list+=((a[j]))
my_list+=(a[len(a)-1])
print(my_list)
|
"""
@jetou
@date : 2017/12/10
@algorithms: red_black_tree
"""
class Node:
def __init__(self, key, left=None, right=None, color=None, p=None):
self.color = color
self.key = key
self.left = left
self.right = right
self.p = p
if key == "Nil":
self.p = self
def tree_minimum(self, T, x):
while x.left != T.nil:
x = x.left
return x
def left_rotate(self, T, x):
y = x.right # suppose y is x's right node
x.right = y.left
if y.left != T.nil:
y.left.p = x
y.p = x.p
if x.p == T.nil: #if the father of x is an empty node, then set y as the root node
T.root = y
elif x == x.p.left: # if x is left child of its father, then set y to the left child of the father of x
x.p.left = y
else:
x.p.right = y
y.left = x
x.p = y
def right_rotate(self, T, x):
y = x.left
x.left = y.right
if x.right != T.nil:
y.right.p = x
y.p = x.p
if x.p == T.nil:
T.root = y
elif x == x.p.right:
x.p.right = y
else:
x.p.left = y
y.right = x
x.p = y
def rb_insert(self, T, z):
y = T.nil
x = T.root
while x != T.nil:
y = x
if z.key < x.key:
x = x.left
else:
x = x.right
z.p = y
if y == T.nil:
T.root = z
elif z.key < y.key:
y.left = z
else:
y.right = z
z.left = T.nil
z.right = T.nil
z.color = "Red"
self.rb_insert_fixup(T, z)
def rb_insert_fixup(self, T, z):
while z.p.color == "Red":
if z.p == z.p.p.left:
y = z.p.p.right
if y.color == "Red":
z.p.color = "Black"
y.color = "Black"
z.p.p.color = "Red"
z = z.p.p
elif z == z.p.right:
z = z.p
self.left_rotate(T, z)
z.p.color = "Black"
if z.p.p != T.nil:
z.p.p.color = "Red"
self.right_rotate(T, z.p.p)
else:
y = z.p.p.left
if y.color == "Red":
z.p.color = "Black"
y.color = "Black"
z.p.p.color = "Red"
z = z.p.p
elif z == z.p.left:
z = z.p
self.right_rotate(T, z)
z.p.color = "Black"
if z.p.p != T.nil:
z.p.p.color = "Red"
self.left_rotate(T, z.p.p)
T.root.color = "Black"
def rb_transplant(self, T, u, v):
if u.p == T.nil:
T.root = v
elif u == u.p.left:
u.p.left = v
else:
u.p.right = v
v.p = u.p
def rb_delete(self, T, z):
y = z
y_original_color = y.color
if z.left == T.nil:
x = z.right
self.rb_transplant(T, z, z.right)
elif z.right == T.nil:
x = z.left
self.rb_transplant(T, z, z.left)
else:
y = self.tree_minimum(z.right)
y_original_color = y.color
x = y.right
if y.p == z:
x.p = y
else:
self.rb_transplant(T, y, y.right)
y.right = z.right
y.right.p = y
self.rb_transplant(T, z, y)
y.left = z.left
y.left.p = y
y.color = z.color
if y_original_color == 'Black':
self.rb_delete_fixup(T, x)
def rb_delete_fixup(self, T, x):
while x != T.root and x.color == 'Black':
if x == x.p.left:
w = x.p.right
if w.color == 'Red':
w.color = 'Black'
x.p.color = 'Red'
self.left_rotate(T, x.p)
w = x.p.right
if w.left.color == 'Black' and w.right.color == 'Black':
w.color = 'Red'
x = x.p
else:
if w.right.color == 'Black':
w.left.color = 'Black'
w.color = 'Red'
self.right_rotate(T, w)
w = x.p.right
w.color = x.p.color
x.p.color = 'Black'
w.right.color = 'Black'
self.left_rotate(T, x.p)
x = T.root
else:
w = x.p.left
if w.color == 'Red':
w.color = 'Black'
x.p.color = 'Red'
self.right_rotate(T, x.p)
w = x.p.left
if w.right.color == 'Black' and w.left.color == 'Black':
w.color = 'Red'
x = x.p
else:
if w.left.color == 'Black':
w.right.color = 'Black'
w.color = 'Red'
self.left_rotate(T, w)
w = x.p.left
w.color = x.p.color
x.p.color = 'Black'
w.left.color = 'Black'
self.right_rotate(T, x.p)
x = T.root
x.color = 'Black'
def inorder_tree_walk(self, T, s, A):
if s == T.nil :
return
if s.left != T.nil:
self.inorder_tree_walk(T, s.left, A)
A.append(s)
if s.right != T.nil:
self.inorder_tree_walk(T, s.right, A)
class Tree:
def __init__(self):
nil = Node("Nil", color="Black")
self.root = nil
self.nil = nil
node = [11, 2, 14, 1, 7, 15, 5, 8, 4]
print node
T = Tree()
# T.root.rb_insert(T, Node(11))
# T.root.rb_insert(T, Node(13))
for j in node:
T.root.rb_insert(T, Node(j))
A = []
T.root.inorder_tree_walk(T, T.root, A)
for i in A:
T.root.rb_delete(T, i)
AA = []
T.root.inorder_tree_walk(T, T.root, AA)
print "AfterDeleting ", i.key, ".Nodes in tree:", [AAA.key for AAA in AA]
|
"""Description: brain even game functions."""
from random import randint
DESCRIPTION = 'Answer "yes" if number even otherwise answer "no".'
def is_even(number):
"""Is even."""
return (number % 2) == 0
def make_question():
"""Asks question.
:return: expression, result
"""
number = randint(0, 100)
even = 'yes' if is_even(number) else 'no'
return (number, even)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 10:32:19 2020
@author: davidnelson
This code attempts to adapt the following tutorial from The Programming
Historian to the Beehive data set.
https://programminghistorian.org/en/lessons/exploring-and-analyzing-network-data-with-python
"""
# step 0: drop index data DONE
# step 1: drop empty cross-references
# step 2: drop cross references to entries that have not yet been annotated
# step 3: create a regularized spreadsheet of topic and cross-references
# step 3.5: make everything lowercase
# step 4: create a match category for numerical entries (done)
# step 5: separate out match data and item tags (done)
# step 6: create target matches from cross reference data
# so if you have Topic: Apples, Xref: Tree|Fruit|Eve
# place each cross reference on its own line with the topic as source
# and the cross reference as target
# question: are we looking up id tags (which ARE unique) or topic/match data
# (assumed unique)?
# For use with networkx, we need a list of nodes and a list of edges
# the CSV of data and item tags are the nodes, the other CSV are the edges
import csv
import re
import networkx as nx
from operator import itemgetter
from networkx.algorithms import community
def find_numbers(entry):
'''
This function will determine if string input contains numbers or not.
'''
return any(char.isdigit() for char in entry)
with open('data/beehive-data-network.csv', 'r') as ip, open(
'beehive-keys.csv', 'w') as op:
reader = csv.DictReader(ip)
fields = ['topic', 'item']
writer = csv.DictWriter(op, fieldnames=fields)
writer.writeheader()
for row in reader:
entry = row['entry']
topic = row['topic']
item = row['item']
if find_numbers(entry) is True:
match = f'{entry} [{topic}]'
writer.writerow({'topic': match.lower(), 'item': item})
else:
writer.writerow({'topic': topic.lower(), 'item': item})
keys = {}
beehive_topics = []
with open('beehive-keys.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
keys.update({row['item']: row['topic']})
beehive_topics.append(row['topic'])
# load corrections for idiosyncratic xref data
corrections = {}
with open('data/alpha-corrections.csv', 'r') as ip:
corrections_reader = csv.DictReader(ip)
for row in corrections_reader:
corrections.update({row['input']: row['match']})
with open('data/beehive-data-network.csv', 'r') as ip, open(
'beehive-edges.csv', 'w') as op:
reader = csv.DictReader(ip)
fields = ['source', 'target']
writer = csv.DictWriter(op, fieldnames=fields)
writer.writeheader()
for row in reader:
entry = row['entry'].lower()
topic = row['topic'].lower()
xref = row['xref']
if find_numbers(entry) is True:
topic = f'{entry} [{topic}]'
if xref != '': # we don't want blank cross-references
if '|' in xref:
xref_list = xref.split('|')
for i in xref_list:
if find_numbers(i) is True:
xref_num = re.search(r'\d+', i).group()
if int(xref_num) < 497: # last numerical entry for now
writer.writerow(
{'source': topic, 'target': i.lower()})
elif i in corrections:
corrector = corrections[i]
correction = keys[corrector]
writer.writerow(
{'source': topic, 'target': correction})
elif i.lower() in beehive_topics:
writer.writerow(
{'source': topic, 'target': i.lower()})
else:
print(f'No match for {i}.')
else:
if find_numbers(xref) is True:
xref_num = re.search(r'\d+', xref).group()
if int(xref_num) < 497:
writer.writerow(
{'source': topic, 'target': xref.lower()})
elif xref in corrections:
corrector = corrections[xref]
correction = keys[corrector]
writer.writerow({'source': topic, 'target': correction})
elif xref.lower() in beehive_topics:
writer.writerow({'source': topic, 'target': xref.lower()})
else:
print(f'No match for {xref}')
with open('beehive-edges.csv', 'r') as edgecsv:
edgereader = csv.reader(edgecsv)
edges = [tuple(e) for e in edgereader][1:]
nodes_list = []
for e in edges:
for i in e:
nodes_list.append(i)
nodes = set(nodes_list)
print(len(nodes))
print(len(edges))
G = nx.DiGraph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
print(nx.info(G))
density = nx.density(G)
print(density)
necessity_pocket_path = nx.shortest_path(G,
source='necessity', target='pocket')
print('Shortest path from "Necessity" to "Pocket":', necessity_pocket_path)
# components = nx.connected_components(G)
# largest_component = max(components, key=len)
# subgraph = G.subgraph(largest_component)
# diameter = nx.diameter(subgraph)
# print('Network diameter of largest component:', diameter)
# nx.write_gexf(subgraph, 'beehive-sub.gexf')
triadic_closure = nx.transitivity(G)
print('Triadic closure:', triadic_closure)
degree_dict = dict(G.degree(G.nodes()))
nx.set_node_attributes(G, degree_dict, 'degree')
print(G.nodes['poverty'])
sorted_degree = sorted(degree_dict.items(), key=itemgetter(1), reverse=True)
print('Top 20 nodes by degree:')
for d in sorted_degree[:20]:
print(d)
betweenness_dict = nx.betweenness_centrality(G)
eigenvector_dict = nx.eigenvector_centrality(G)
nx.set_node_attributes(G, betweenness_dict, 'betweenness')
nx.set_node_attributes(G, eigenvector_dict, 'eigenvector')
sorted_betweenness = sorted(
betweenness_dict.items(), key=itemgetter(1), reverse=True)
print('Top 20 nodes by betweeness centrality:')
for b in sorted_betweenness[:20]:
print(b)
sorted_eigenvector = sorted(
eigenvector_dict.items(), key=itemgetter(1), reverse=True)
print('Top 20 nodes by eigenvector centrality:')
for e in sorted_eigenvector[:20]:
print(e)
# First get the top 20 nodes by betweenness as a list
top_betweenness = sorted_betweenness[:20]
# Then find and print their degree
for tb in top_betweenness: # Loop through top_betweenness
degree = degree_dict[tb[0]]
print("Name:", tb[0], "| Betweenness Centrality:", tb[1], "| Degree:", degree)
communities = community.greedy_modularity_communities(G)
modularity_dict = {}
for i, c in enumerate(communities):
for name in c:
modularity_dict[name] = i
nx.set_node_attributes(G, modularity_dict, 'modularity')
class0 = [n for n in G.nodes() if G.nodes[n]['modularity'] == 0]
class0_eigenvector = {n: G.nodes[n]['eigenvector'] for n in class0}
class0_sorted_by_eigenvector = sorted(
class0_eigenvector.items(), key=itemgetter(1), reverse=True)
print('Modularity class 0 sorted by eigenvector centrality:')
for node in class0_sorted_by_eigenvector[:5]:
print('Name:', node[0], '| Eigenvector Centrality:', node[1])
for i, c in enumerate(communities):
if len(c) > 2:
print(f'Class {str(i)}: {list(c)}')
nx.write_gexf(G, 'beehive-network.gexf')
|
def conditional_branch(abc):
"""
入力文に特定の文字が含まれている場合に条件にあった文を出力する。
注意:入力文が複数の条件を満たす場合は最初に記述された条件が適用される。
例:入力文:bac ---> 出力文:aが含まれています。
"""
if 'a' in abc:
print("aが含まれています。")
elif 'b' in abc:
print("bが含まれています。")
elif 'c' in abc:
print("cが含まれています。")
else:
print("aもbもcも含まれていません。")
if __name__ == '__main__':
conditional_branch(input())
|
# 简单的端口扫描工具
# 作者: Charles
# 公众号: Charles的皮卡丘
import time
import socket
import threading
# 端口扫描工具
class scanThread(threading.Thread):
def __init__(self, ip, port_min=0, port_max=65535):
threading.Thread.__init__(self)
assert isinstance(port_max, int) and isinstance(port_min, int)
self.ip = ip
self.port_min = max(0, port_min)
self.port_max = min(65535, port_max)
# 重写run
def run(self):
return self.__checker()
# 检测
def __checker(self):
for port in range(self.port_min, self.port_max+1):
self.__connect(port)
# 连接
def __connect(self, port):
socket.setdefaulttimeout(1)
s = socket.socket()
try:
t_start = time.time()
s.connect((self.ip, port))
t_end = time.time()
flag = True
except:
flag = False
s.close()
if flag:
connect_time = str(int((t_end - t_start) * 1000))
info = 'Find --> [IP]: %s, [PORT]: %s, [Connect Time]: %s' % (self.ip, port, connect_time)
print(info)
self.__save(info)
return flag
# 保存结果
def __save(self, content):
if content:
try:
with open('results.txt', 'a') as f:
f.write(content + '\n')
except:
time.sleep(0.1)
if __name__ == '__main__':
ip = input('Input IP(example <xxx.xxx.xxx.xxx>):\n')
port_min = input('Input Min Port(0 by default):\n')
try:
port_min = int(port_min)
except:
print('[Warning]: Enter min port error, use 0 by default...')
port_min = 0
port_max = input('Input Max Port(65535 by default):\n')
try:
port_max = int(port_max)
except:
print('[Warning]: Enter max port error, use 65535 by default...')
port_max = 65535
# 一个线程负责扫描num个端口
num = 8
interval = (port_max - port_min) // num
for i in range(interval):
scanThread(ip, i * num, (i + 1) * num).start()
|
class Human():
def __init__(self, name, weight):
print("__init__실행")
self.name = name
self.weight = weight
#def __str__(self):
# return "{} (몸무게 {}kg)".format(self.name, self.weight)
def eat(self):
self.weight += 0.1
print("{}가 먹어서 {}kg이 되었습니다.").format(self.name, self.weight)
person = Human("사람",60.5)
print(person)
|
#!/usr/bin/python3
import time
import interesting_number
import is_alphanumeric_only
import missing_letter
import move_zeros
import pig_latin
import valid_ip
def main():
# Init Variables Used To Test
letter_test = ["a", "b", "c", "e", "f"]
zeros_test = ['a', 3, 5, 0, 1, 1, 3, 5, 0, 0, 0, 7, 9]
interesting_test = [39, 400, 12345, 1329, 8769, 4135]
awesome_numbers = [4135]
latin_test = "This will become pig latin."
latin_result = None
ip_test = "127.0.0.1"
ip_result = None
res = -1
missing = None
zeros_end = None
s_list = ["abtVNmkl135KJb", "_stbb@3nkLKH", "AABcmtvw2356"]
# Missing Letter Test
print("--- Missing Letter Test ---\n")
missing = missing_letter.find_missing_letter(letter_test)
if (missing is None):
print("[!] No Missing Letter Found\n")
else:
print("[+] {0} Is The Missing Letter In {1}\n".format(missing, letter_test))
# Move Zeros Test
zeros_end = move_zeros.move_zeros(zeros_test)
print("--- Move Zeros Test ---\n\nOld: {0}\nNew: {1}\n".format(zeros_test, zeros_end))
# Pig Latin Test
print("--- Pig Latin Test ---\n")
latin_result = pig_latin.pig_it(latin_test)
print("Old: {0}\nNew: {1}\n".format(latin_test, latin_result))
# Valid IP Test
print("--- IP Validation Test ---\n")
ip_result = valid_ip.is_valid_IP(ip_test)
if (ip_result):
print("[+] {0} Is A Valid IP Address\n".format(ip_test))
else:
print("[-] {0} Is Not A Valid IP Address\n".format(ip_test))
# Interesting Number Test
print("--- Interesting Number Test ---\n")
print("Awesome Number List: {0}\n".format(awesome_numbers))
for number in interesting_test:
res = interesting_number.is_interesting(number, awesome_numbers)
if (res == 2):
print("[+] {0} Is An Interesting Number".format(number))
elif (res == 1):
print("[!] {0} Is Within Two Miles From An Interesting Number".format(number))
else:
print("[-] {0} Is Not An Interesting Number".format(number))
print("")
# Alphanumeric Only Test
print("--- Alphanumeric Only Test ---\n")
for s in s_list:
if (is_alphanumeric_only.alphanumeric(s)):
print("[+] {0} is an alphanumeric only string".format(s))
else:
print("[-] {0} is not an alphanumeric only string".format(s))
print("")
return
if __name__ == "__main__":
s = time.time()
main()
e = time.time()
exec_time = e - s
print("\n[INFO] Program Took {0} Seconds To Execute ...\n".format(exec_time))
|
class Board:
####how to access instace variables within a class
def __init__(self, arr):
self.state = arr
def swap(self,arr,x,y):
arr1 = list(arr)
arr1[x], arr1[y] = arr1[y], arr1[x]
return(arr1)
def neighbors(self):
neighbor = []
stt1 = list(self.state)
stt2 = list(self.state)
stt3 = list(self.state)
stt4 = list(self.state)
###swpping rules.
if self.state.index(0) == 0:
stt1 = self.swap(stt1,0,1)
neighbor.append(stt1)
stt2 = self.swap(stt2,0,3)
neighbor.append(stt2)
elif self.state.index(0) == 1:
stt1 = self.swap(stt1,1,4)
neighbor.append(stt1)
stt2 = self.swap(stt2,1,0)
neighbor.append(stt2)
stt3 = self.swap(stt3,1,2)
neighbor.append(stt3)
elif self.state.index(0) == 2:
stt1 = self.swap(stt1,2,5)
neighbor.append(stt1)
stt2 = self.swap(stt2,2,1)
neighbor.append(stt2)
elif self.state.index(0) == 3:
stt1 = self.swap(stt1,3,0)
neighbor.append(stt1)
stt2 = self.swap(stt2,3,4)
neighbor.append(stt2)
stt3 = self.swap(stt3,3,6)
neighbor.append(stt3)
elif self.state.index(0) == 4:
stt1 = self.swap(stt1,4,1)
neighbor.append(stt1)
stt2 = self.swap(stt2,4,3)
neighbor.append(stt2)
stt3 = self.swap(stt3,4,7)
neighbor.append(stt3)
stt4 = self.swap(stt4,4,5)
neighbor.append(stt4)
elif self.state.index(0) == 5:
stt1 = self.swap(stt1,5,2)
neighbor.append(stt1)
stt2 = self.swap(stt2,5,8)
neighbor.append(stt2)
stt3 = self.swap(stt3,5,4)
neighbor.append(stt3)
elif self.state.index(0) == 6:
stt1 = self.swap(stt1,6,3)
neighbor.append(stt1)
stt2 = self.swap(stt2,6,7)
neighbor.append(stt2)
elif self.state.index(0) == 7:
stt1 = self.swap(stt1,7,4)
neighbor.append(stt1)
stt2 = self.swap(stt2,7,6)
neighbor.append(stt2)
stt3 = self.swap(stt3,7,8)
neighbor.append(stt3)
elif self.state.index(0) == 8:
stt1 = self.swap(stt1,8,5)
neighbor.append(stt1)
stt2 = self.swap(stt2,8,7)
neighbor.append(stt2)
#print(self.swap(0, 1))
#print(stt1 == stt2)
return(neighbor)
### swapping rules
lyst = [1,2,5,3,4,0,6,8,7]
initial = Board(lyst)
#print("State: " + str(initial.state))
#print(initial.swap(0,1))
#print(initial.neighbors())
###class Solver:
|
import sys
class Node:
def __init__(self, name, toll):
self.name = name
self.toll = int(toll)
self.path = self.toll
self.next = None
self.visited = False
self.first = 0
self.second = 0
self.parents = set()
topo_list = []
def topo_sort(city_set):
topo_count = 1
for city in city_set.values():
if city.visited == False:
topo_count = explore(city_set, city, topo_count)
def explore(city_set, search_city, topo_count):
city = city_set[search_city.name]
if city.visited == False:
city.visited = True
city.first = topo_count
topo_count += 1
edge = city.next
while edge != None:
city_2 = city_set[edge.name]
if city_2.visited == False:
topo_count = explore(city_set, city_2, topo_count)
edge = edge.next
city.second = topo_count
topo_list.append(city)
topo_count += 1
return topo_count
count = 0
city_set = dict()
num_cities = int(sys.stdin.readline())
for line in sys.stdin:
count += 1
split_line = line.split()
city_node = Node(split_line[0], split_line[1])
city_set[split_line[0]] = city_node
if count >= num_cities:
break
count = 0
num_highways = int(sys.stdin.readline())
if num_highways != 0:
for line in sys.stdin:
if num_highways == 0:
break
count += 1
split_line = line.split()
source = city_set[split_line[0]]
dest = city_set[split_line[1]]
while source.next != None:
source = source.next
source.next = Node(dest.name, dest.toll)
city_set[split_line[1]].parents.add(split_line[0])
if count >= num_highways:
break
topo_sort(city_set)
count = 0
num_trips = int(sys.stdin.readline())
list_of_trips = []
def find_total(trip_list):
for trip_split in trip_list:
if trip_split[0] == trip_split[1]: #source = dest
print(0)
continue
allowed = set()
allowed.add(trip_split[1])
i = 0
while i < len(topo_list):
if topo_list[i].name == trip_split[1]:
break
i += 1
i += 1
allowed = allowed | topo_list[i].parents
while i < len(topo_list):
curr_node = topo_list[i]
if curr_node.name not in allowed:
i += 1
continue
allowed = allowed | curr_node.parents
edge = curr_node.next
while edge != None:
if edge not in allowed:
i += 1
if curr_node.name != trip_split[0]:
print('NO')
else:
print(curr_node.path)
for node_i in city_set.values():
node_i.path = node_i.toll
for trip in sys.stdin:
count += 1
trip_split = trip.split()
list_of_trips.append(trip_split)
if count >= num_trips:
break
find_total(list_of_trips)
exit()
|
import json
__all__ = ['load_json_from_file', 'load_json_from_string']
def load_json_from_file(file_path):
"""Load schema from a JSON file"""
try:
with open(file_path) as f:
json_data = json.load(f)
except ValueError as e:
raise ValueError('Given file {} is not a valid JSON file: {}'.format(file_path, e))
else:
return json_data
def load_json_from_string(string):
"""Load schema from JSON string"""
try:
json_data = json.loads(string)
except ValueError as e:
raise ValueError('Given string is not valid JSON: {}'.format(e))
else:
return json_data
|
#!/usr/bin/env python
# coding=utf-8
"""
In order to run this program, you need to
- install [tensorflow](https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html#virtualenv-installation).
- get an monitor to display the figure.
"""
import tensorflow as tf
import numpy as np
# Produce num_points [x_data, y_data]
num_points = 1000
vector_set = []
for i in xrange(num_points):
x1 = np.random.normal(0.0, 0.55)
y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)
vector_set.append([x1, y1])
x_data = [v[0] for v in vector_set]
y_data = [v[1] for v in vector_set]
# Use Linear regression (TensorFlow version) to solve this problem
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
# Plot the figure after each training_step
def animate(i):
fig.clear()
sess.run(train)
plt.plot(x_data, y_data, 'ro', label='Original data')
plt.plot(x_data, sess.run(W) * x_data + sess.run(b), 'b')
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
|
def year_balance(b, r, p):
for i in range(1, 13):
ub = b - p
b = ub + r * ub
return b
b = float(balance)
r = float(annualInterestRate) / 12.0
maxp = int(year_balance(b, r, 0.0) / 12)
for p in range(0, maxp + 10, 10):
if year_balance(b, r, p) <= 0:
print "Lowest Payment: %d" % p
break
|
mac_os = 300
if mac_os < 200:
print("you are less than 200")
if mac_os < 150:
print("you are less than 150")
elif mac_os < 100:
print("your number less than 100")
else:
print("your number is more")
elif mac_os > 200:
print("you are greater than 100")
if mac_os == 40:
print("you are in 40")
elif mac_os > 300:
print("you are less than 300")
else:
print("you are more number")
else:
print("you are done")
|
#/usr/bin/python
languages = {"python":".py",'shell':'.sh',"java":".java"}
print(languages,type(languages),id(languages),dict(enumerate(languages)),len(languages))
print("")
print("printing only keys:",languages.keys())
print("")
print("printing only values:",languages.values())
#print("calling only one key:",languages.keys("python")) #TypeError: keys() takes no arguments (1 given)
#print("printing specific value",languages.values(".py")) #TypeError: values() takes no arguments (1 given)
print("getting value:",languages.get("python"))
print("")
#Item Method
print("Item method:",languages.items()) #print in tuple method like [(),(),()]
|
#Note:part of elif we can check multiple expressions and conditions
#Note:suppose if condition fails then go to elif condition if again fails then go to next elif condition
course = input("what course are you doing ")
if course == "python":
print("you are doing python course and do more practise")
elif course == "java":
print("you are doing Java course and do more examples")
elif course == "DevOps":
print("You will become Devops engineer")
else:
print("you are already completed courses and gennious")
print("you are not doing any course")
print("----------------------------------")
value = 100
if value > 200: #Here condition is false
print("this is in block-1")
elif value >=200: #Here condition is false
print("this is block-2")
elif False:
print("this is block-3")
elif True: #Here True is Key Word
print("this is correct")
else:
print("this is final block")
|
import re
str = "we are staying in Bangalore,karnataka 08"
test = re.findall("Bangalore",str)
print(test)
#search
test1 = re.search("\d",str) #If no matches are found,then it will return as None
print(test1)
#split the string at every white-space character:
test2 = re.split("\s",str)
print(test2)
#split the string at every characters including letters and no's
test3 = re.split("\W",str)
print(test3)
#We can control the number of occurances by specifying maxsplit parameter
test4 = re.split("\s",str,2) #It will split 2 occurances
print(test4)
#The sub() function replaces the matches with the text of your choice
#Replaces the whitespace characters with digit 8.
test5 = re.sub("\s","8",str)
print(test5)
test6 = re.sub("we","Dharmala's",str)
print(test6)
#We can control the number of replacements by specifying the count parameter
test7 = re.sub("a","d",str,5) #Replace the first 5 occurrences:
print(test7)
#span() returns a tuple containing the start- and end positions of the match.
test8 = re.search(r"\bB\w+",str)
print(test8.span())
##string() --The string property returns the search string
test9 = re.search(r"\bB\w+",str)
print(test9.string)
#group()--Print the part of the string where there was a match
test10 = re.search(r"\bB\w+",str)
print(test10.group())
|
#/usr/bin/python
tup1 = ("dharmala","""manohar""",1982,2010,19.5) #we can use combination of strings and numbers
tup2 = 10,20,30,40,50 #need to use comma separator for tuple
print(tup1,tuple(enumerate(tup1)),type(tup1),id(tup1))
print("\n")
print(tup2,tuple(enumerate(tup2)),type(tup2),id(tup2))
print("\n")
print(tup1[-3],tup1[0:4]) #printing using slicing and range index
tup3 = ("manohar","""dharmala""",[1.2,3,4])
print(tup3,type(tup3))
#del tup1 # deleted tup1 and delete is built in function
#del tup1[0] #Typeerror:tuple object doesn't support item deletion and can't delete only element
print(tup1) #we can not get variable
list1 = [1,2,3,4]
print(list1,type(list1),list(enumerate(list1)))
tup4 = tuple(list1) #converting list into tuple
print(tup4,type(tup4),tuple(enumerate(tup4)))
tup5,tup6 = ("ram","sita","lakshman"),(1,2,3,4,5) #other way of defining tuple
print(tup5,tuple(enumerate(tup5)))
print(tup6,tuple(enumerate(tup6)))
|
#Iterate through the items and print the values:
thistuple = ("apple","mango","guava")
for x in thistuple:
print(x)
#Check if item exists
thistuple = ("apple","mango","guava")
if "apple" in thistuple:
print("yes,its exists")
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
|
"""
data = int(input("enter one number:"))
while data < 10:
print("enter the data:",data)
data = data +1
print("you are out of while loop:")
"""
password = ""
while password != 'redhat':
password = input("please enter admin password:").strip().lower()
if password == 'redhat':
print("you entered admin correct password\t")
elif password == 'admin123':
print("you entered similar to admin password\t")
elif password == 'linux123':
print("you entered linux admin password\t")
elif password:
print("you entered wrong password\t")
print("you are outof while loop")
|
#Default argument: Default argument is an argument and assumes a value if value not provided by function call argument
#if we prpvide values in caller in will accept otherwise it will take default values
#if we provide deafult value in function ,no need to call again
#Example:1
#Creating a function
def name1(firstname,middlename,lastname,age=30): #firstname,middlename,lastname are required argument and age is default
print("Firstname:",firstname)
print("Middlename:",middlename)
print("Lastname:",lastname)
print("age:",age)
return
#Calling a function
name1('Guido','Van',"Rossum",50)
print("")
#Example:2
#Creating a function
def name1(firstname,middlename,lastname,age=30):
print("Firstname:",firstname)
print("Middlename:",middlename)
print("Lastname:",lastname)
print("age:",age)
return
#Calling a function
name1('Guido','Van',"Rossum")
#name1('Guido','Van') #TypeError: name1() missing 1 required positional argument: 'lastname'
#Example:3
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
|
import re
#Example-1(Find out correct format phone no's using \w)
phonenos = "408-205-9015,408-215-9165,aaa-bbb-cccc"
phnno = re.findall("\w{3}-\w{3}-\w{4}",phonenos)
for phnno1 in phnno:
print(phnno1)
#Example-2(Find out correct format phone no's using \d)
phone = "408-205-9015,aaa-bbb-cccc"
phn = re.findall("\d{3}-\d{3}-\d{4}",phone)
if phn:
print("entered correct phone no")
else:
print("entered wrong phone no")
#Example-3(Find out given name is valid or not
rawstring = "Manohar Dharmala,DDDDDDD MMMMMMMMM"
rawst = re.findall("\w{2,20}\s\w{2,20}",rawstring)
for rawst1 in rawst:
print(rawst1)
#Example-4(Find out email address is valid or not)
rawstring1 = "[email protected] [email protected] [email protected]"
rawst2 = re.findall("\w{0,20}.\w+@\w{0,20}.com",rawstring1)
for email in rawst2:
print("Email address:",email)
'''
#Example-5(Find out phone no's from web page(Web Scraping))
from urllib.request import urlopen
url = "http://www.summet.com/dmsi/html/codesamples/addresses.html"
print(url)
print("1....")
response = urlopen(url)
print("2 ...",response)
html = response.read()
print(html)
htmlstr = html.decode()
pdata = re.findall("(\d{3}) \d{3}-\d{4}",htmlstr)
for item in pdata:
print(item)
'''
|
"""
Lambda"Keyword
syntax: lambda arag1 +arg2 : expression
"""
product = lambda arg1,arg2,arg3,arg4:arg1 + arg2 + arg3 + arg4
print(product(1,2,3,4))
#Scope of Variables
"""
1. Local Variables
2. Global Variables
"""
|
"""
1. Required Arguments
2. Default Arguments
3. Keyword Arguments
4. Variable-length Arguments
"""
#1. Required Argument
#Required Arguments which send correct positional order means function call and function definition should match exactly
def name(firstname,middlename,lastname):
'Required Arguments'
print("Firstname:",firstname)
print("Middlename:",middlename)
print("Lastname:",lastname,type(firstname))
return
name("Atchuta","Narasimha","Manohar")
name(1,2,3)
#2. Keyword Argument ,caller identifies the function based on Keyword ,here we need to provide key and pair value
def keywordargument(firstname,middlename,lastname):
'Keyword Arguments'
print("Firstname:",firstname)
print("Middlename:",middlename)
print("Lastname:",lastname)
#Calling a function
keywordargument(firstname="Guido",middlename="Van",lastname="Rossum")
#keywordargument(Firstname="Guido",Middlename="Van",lastname="Rossum") Need to give correect Argumentname when calling function
#3. Default Arguments
def defaultargument(firstname,middlename,lastname,age=40):
'Default Arguments'
print("Firstname:",firstname)
print("Middlename:",middlename)
print("Lastname:",lastname)
print("Age",age)
defaultargument("Anshul","Venkata","Dharmala",age=50)
defaultargument("Anshul","Venkata","Dharmala")
#4. Variable length Arguments
def variablelengtharguments(arg1,*arg2):
'Variable Length Arguments'
# * : Asterick is placed beforee the variable name
print(arg1)
for var in arg2:
print(var)
return
#calling a function
variablelengtharguments('aws',"azure","Devops")
#Example -2
def info(*arg3):
for var1 in arg3:
print(var1)
print(type(var1))
#Creating a variable
list1 = ["Aws","Azure","devops"]
#Calling a function
info(list1)
|
"""
name = "Guido Van Rossum"
print("Lower method:",name.lower()) #convert all chars in lower case.
print("")
print("Upper case method:",name.upper()) #conevrts all cahrs in upper case
print()
print("Replace method:",name.replace("Van","Ben")) #replace with other chars
print()
print("Split method:",name.split(","))
"""
name1 = "aws azure and aws openstack"
print ("find method:",name1.find('aws')) #searching substring left to right
print("rfind method:",name1.rfind('aws'),len(name1)) #Finding substring right to left
print("index method:",name1.index("azure"))
print("right index method:",name1.rindex("azure"))
print("split method1:",name1.split()) #it will split elements and string converts into list
name2 = name1.split()
print(type(name2))
print("split method2:",name1.split(" ")) #it will split based on spaces and based on parameters
name3 = "ram site @@@lakshman @@@ravana"
print("split method3:",name3.split("@@@")) #it will based on parameter(@@@)
print("split method4:",name1.split(" ",2)) #it will spilt into 2 maximum splits by using space parameter
print("split lines:",name1.splitlines()) #it will print as one element
name4 = "aws\nazure\naws"
print("split lines:",name4.splitlines()) #It will take as 3 elements
pyworld = """
aws
azure
openstack
vmware
"""
print("split lines:",pyworld.splitlines()) #no need to provide \n for next line in triple quotes
pyworld1 = "aws \
devops \
vmware \
openstack"
print("split lines1",pyworld1.splitlines()) #need to provide \ for next line in double quotes
|
"""
#Method-1
#creating a function
def course(parameters):
print(parameters) #part of course function
return parameters #No argument in return means NONE
#calling a function
a=course('python')
print(a)
#Method-2
def name(firstname):
print(firstname)
name('manohar')
"""
#Method-3
#Creating a function
def name1(name):
print(name)
return
#Creating a variable
firstname = "Manohar Dharmala"
#Calling a function
a = name1('Anshul Dharmala')
name1(firstname)
def mykids(*kids):
print("My son is :",kids[2])
mykids("ram","krishna","Anshul")
def my_function(**wifes):
print("My wife is:",wifes["lname"])
my_function(fname = "Deepu",lname="Deepika")
def my_country(country = "India"):
print("My country name is :" + country)
my_country("US")
my_country("England")
my_country()
|
'''
Matrix Search
Given a matrix of integers A of size N x M and an integer B. Write an efficient algorithm that searches for integar B in matrix A.
This matrix A has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than or equal to the last integer of the previous row.
Return 1 if B is present in A, else return 0.
NOTE: Rows are numbered from top to bottom and columns are numbered from left to right.
Problem Constraints
1 <= N, M <= 1000
1 <= A[i][j], B <= 106
Example Input
Input 1:
A = [
[1, 3, 5, 7]
[10, 11, 16, 20]
[23, 30, 34, 50]
]
B = 3
Input 2:
A = [
[5, 17, 100, 111]
[119, 120, 127, 131]
]
B = 3
Example Output
Output 1:
1
Output 2:
0
'''
class Solution:
# iterate i until you find a[i][m-1] >= b
# This row could have the element we need
# use binary search on the row
def searchMatrix(self, a, b):
n = len(a)
m = len(a[0])
for i in range(n):
while a[i][m-1] < b:
i += 1
if i == n:
return 0
l = 0
r = m-1
while(l<=r):
m = (l+r) // 2
if a[i][m] == b:
return 1
if a[i][m] > b:
r = m-1
else:
l = m+1
return 0
|
'''
Unique Binary Search Trees II
Given an integer A, how many structurally unique BST's (binary search trees) exist that can store values 1...A?
Problem Constraints
1 <= A <=18
Example Input
Input 1:
1
Input 2:
2
Example Output
Output 1:
1
Output 2:
2
'''
# We need to check with putting x elements on left and n-x on right
# this x can vary from 0 to n
# each of these values will result in a new combination of two sides (dp[n-x]*dp[x-1])
# Add the current dp[n] value to every combination
from math import factorial as fact
class Solution:
def numTrees(self, a):
# code for catlan number approach with O(a) time complexity
'''
count = 0
n = 2*a
count = fact(n)//(fact(a)*fact(n-a))
count = count//(a+1)
return count
'''
# code for dp approach
dp = [0 for i in range(a+1)]
dp[1]=1
dp[0]=1
for i in range(2,a+1):
for j in range(0,i+1):
dp[i] = (dp[i-j]*dp[j-1]) + dp[i]
return dp[-1]
# TC O(a^2)
# SC O(a)
|
'''
Array 3 Pointers
You are given 3 sorted arrays A, B and C.
Find i, j, k such that : max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])) is minimized.
Return the minimum max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])).
Problem Constraints
0 <= len(A), len(B), len(c) <= 106
0 <= A[i], B[i], C[i] <= 107
Example Input
Input 1:
A = [1, 4, 10]
B = [2, 15, 20]
C = [10, 12]
Input 2:
A = [3, 5, 6]
B = [2]
C = [3, 4]
Example Output
Output 1:
5
Output 2:
1
'''
class Solution:
# put a pointer on each arr
# our goal is to maximize the subtracting value or min the adding val
# since the arr is sorted we can only max the subtracting value
def minimize(self, a, b, c):
i = j = k = 0
mi = float('inf')
while i < len(a) and j < len(b) and k<len(c):
ma = max((abs(a[i]-b[j]),abs(b[j]-c[k]),abs(c[k]-a[i])))
mi = min(ma,mi)
# increment the min value since we want to maximize the subtracting value
if a[i] <= b[j] and a[i] <= c[k]:
i += 1
elif b[j] <= a[i] and b[j] <= c[k]:
j += 1
else:
k += 1
return mi
|
'''
Populate Next Right Pointers Tree
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
Example :
Given the following binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
'''
# we connect the left child of root to the right child.
# if there is no right child we move to the next horizontal node that is available and connect its first child
class Solution:
# func to return the next available node
def getNextRight(self, q):
q = q.next
while q:
if q.left:
return q.left
if q.right:
return q.right
q = q.next
return q
def connect(self, root):
p = root
while p:
q = p
while q:
if q.left:
if q.right:
q.left.next = q.right
else:
q.left.next = self.getNextRight(q)
if q.right:
q.right.next = self.getNextRight(q)
q = q.next
if p.left:
p = p.left
elif p.right:
p = p.right
else:
p = self.getNextRight(p)
return root
# TC O(n)
# SC O(1)
|
'''
Fibonacci Number
Given a positive integer N, write a program to find the Ath Fibonacci number.
In a Fibonacci series, each term is the sum of the previous two terms and the first two terms of the series are 0 and 1. i.e. f(0) = 0 and f(1) = 1. Hence, f(2) = 1, f(3) = 2, f(4) = 3 and so on.
NOTE: 0th term is 0. 1th term is 1 and so on.
Problem Constraints
0 <= N <= 44
Example Input
Input 1:
N = 4
Input 2:
N = 6
Example Output
Output 1:
3
Output 2:
8
'''
# store fib of calculated values in an array called dp
# check the arr if you already have the val you need to avoid recomputation
def fibonacci(n, dp):
if n <= 0:
return 0
if dp[n]:
return dp[n]
dp[n] = fibonacci(n-1, dp) + fibonacci(n-2, dp)
return dp[n]
def main():
n = int(input())
dp = [None]*(n+1)
dp[0] = 0
if n > 0:
dp[1] = 1
print(fibonacci(n, dp))
return
if __name__ == '__main__':
main()
# TC O(n)
# SC O(n)
|
'''
Different Bits Sum Pairwise
We define f(X, Y) as number of different corresponding bits in binary representation of X and Y.
For example, f(2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f(2, 7) = 2.
You are given an array of N positive integers, A1, A2 ,..., AN. Find sum of f(Ai, Aj) for all pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 109+7.
Problem Constraints:
1 <= N <= 105
1 <= A[i] <= 231 - 1
Input 1:
A = [1, 3, 5]
Input 2:
A = [2, 3]
Ouptut 1:
8
Output 2:
2
'''
class Solution:
def cntBits(self, a):
sum = 0
m = 10**9 + 7
# count the number of 1s in each parity of every number
for i in range(32):
count_1 = 0
for j in range(len(a)):
if a[j] & (1<<i):
count_1 += 1
# multiply number of 1s with number of 0s, this will give us number of diff bits for all pairs in that parity
# multiple by 2 because we can have f(i,i) too
sum += 2 * count_1 * (len(a)-count_1)
sum = sum % m
return sum
|
'''
Single Element in a Sorted Array
Given a sorted array of integers A where every element appears twice except for one element which appears once, find and return this single element that appears only once.
NOTE: Users are expected to solve this in O(log(N)) time.
Problem Constraints
1 <= |A| <= 100000
1 <= A[i] <= 10^9
Input 1:
A = [1, 1, 7]
Input 2:
A = [2, 3, 3]
Output 1:
7
Output 2:
2
'''
class Solution:
# the second occ of a number occurs on even pos before the req element and after it, the pos is odd
# we check if pos is even or odd and modify the search span accordingly
def binS(self,a,st,end):
if st > end:
return None
if st == end:
return a[st]
mid = (st + end)//2
if mid & 1 == 0:
if a[mid] == a[mid+1]:
return self.binS(a,mid+2, end)
else:
return self.binS(a,st,mid)
if mid & 1 == 1:
if a[mid] == a[mid-1]:
return self.binS(a,mid+1,end)
else:
return self.binS(a,st,mid-1)
def solve(self, a):
return self.binS(a,0,len(a)-1)
|
'''
Sort Array in given Order
Given two array of integers A and B, Sort A in such a way that the relative order among the elements will be the same as those are in B. For the elements not present in B, append them at last in sorted order.
Return the array A after sorting from the above method.
NOTE: Elements of B are unique.
Problem Constraints
1 <= length of the array A <= 100000
1 <= length of the array B <= 100000
-10^9 <= A[i] <= 10^9
Example Input
Input 1:
A = [1, 2, 3, 4, 5]
B = [5, 4, 2]
Input 2:
A = [5, 17, 100, 11]
B = [1, 100]
Example Output
Output 1:
[5, 4, 2, 1, 3]
Output 2:
[100, 5, 11, 17]
'''
class Solution:
# map elements of arr a with their frequency
def solve(self, a, b):
map = {}
for i in range(len(a)):
if a[i] in map:
map[a[i]] += 1
else:
map[a[i]] = 1
res = []
# for each element in b that is present in a, add the element in res
# subtract the frequency from the map
for i in range(len(b)):
if b[i] in map:
while map[b[i]] > 0:
res.append(b[i])
map[b[i]] -= 1
# for all elements in map having frequency more than 0, need to be added in a temp arr
# this will give us remaining a elements
temp = []
for i in range(len(a)):
while map[a[i]] > 0:
temp.append(a[i])
map[a[i]] -= 1
temp.sort()
for i in range(len(temp)):
res.append(temp[i])
return res
# TC O(max(len(a),len(b)))
# SC O(len(a))
|
'''
Clone Graph
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
Note: The test cases are generated in the following format (use the following format to use See Expected Output option):
First integer N is the number of nodes.
Then, N intgers follow denoting the label (or hash) of the N nodes.
Then, N2 integers following denoting the adjacency matrix of a graph, where Adj[i][j] = 1 denotes presence of an undirected edge between the ith and jth node, O otherwise.
Problem Constraints
1 <= Number of nodes <= 10^5
Example Input
Input 1:
1
/ | \
3 2 4
/ \
5 6
Input 2:
1
/ \
3 4
/ /|\
2 5 7 6
Example Output
Output 1:
Output will the same graph but with new pointers:
1
/ | \
3 2 4
/ \
5 6
Output 2:
1
/ \
3 4
/ /|\
2 5 7 6
'''
# Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
class Info:
def __init__(self):
self.vis = {}
# Create a clone node for each given node
# Run a loop through its neighbors array and recursively call clone of its neighbour and append it
# to the neighbour list of the original clone node
# In order to avoid any repeatition, we will store node->clone in a dict/hashmap
# If we have already visited a node then we will just return its clone
class Solution:
def cloneGraphUtil(self, node, info):
# If we touch a null node
if node == None:
return node
if node in info.vis:
return info.vis[node]
clone = UndirectedGraphNode(node.label)
info.vis[node] = clone
for neighbour in node.neighbors:
clone.neighbors.append(self.cloneGraphUtil(neighbour, info))
return clone
def cloneGraph(self, node):
info = Info()
return self.cloneGraphUtil(node, info)
# TC O(N), number of the nodes
# SC O(N + H), H = Height of the graph, due to the recursion stack.
|
'''
Greatest Common Divisor
Given 2 non negative integers A and B, find gcd(A, B)
GCD of 2 integers A and B is defined as the greatest integer g such that g is a divisor of both A and B.
Both A and B fit in a 32 bit signed integer.
constraints:
0 <= A, B <= 109
input:
A = 4
B = 6
output: 2
input:
A = 6
B = 7
output: 1
'''
import sys
sys.setrecursionlimit(10**6)
class Solution:
# a%g = 0 and b%g = 0
# => (a-b) % g = 0 => (a-b) % g
# % will give repeating minus => we can use a%b instead of a-b
def gcd(self, a, b):
if a == 0:
return b
return self.gcd(b%a, a)
|
'''
Kth Smallest Element In Tree
Given a binary search tree represented by root A, write a function to find the Bth smallest element in the tree.
Problem Constraints
1 <= Number of nodes in binary tree <= 100000
0 <= node values <= 10^9
Example Input
Input 1:
2
/ \
1 3
B = 2
Input 2:
3
/
2
/
1
B = 1
Example Output
Output 1:
2
Output 2:
1
'''
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# counter class to count k smallest elements
class Counter:
def __init__(self):
self.i = 0
def inc(self):
self.i += 1
def getCounter(self):
return self.i
# The inorder traversal gives us node values in a sorted order
# We make a counter class to count the number of nodes we traverse in inorder fashion
# If the left becomes null we inc the counter
# We keep inc counter for nodes in the left sub tree, until counter, i == k
class Solution:
def getKthSmallest(self, root,k,i):
if not root:
return None
left = self.getKthSmallest(root.left, k,i)
if left != None:
return left
i.inc()
if i.getCounter() == k:
return root.val
return self.getKthSmallest(root.right, k,i)
def kthsmallest(self, root, k):
i = Counter()
ans = self.getKthSmallest(root,k,i)
return ans
# TC O(n)
# SC O(h), height of the tree
|
'''
Maximum Absolute Difference
You are given an array of N integers, A1, A2, .... AN.
Return the maximum value of f(i, j) for all 1 ≤ i, j ≤ N. f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x.
Constraints:
1 <= N <= 100000
-109 <= A[i] <= 109
input: [1, 3, -1]
output: 5
input: [2]
output: 0
'''
def maxArr(a):
# absolute sol can be broken down to 2 diff equations based on its defination
# rearranging them will give a[i]+i - a[j] + j and a[i]-i - a[j]-j
# since there is no relation between and i and j we can say i == j is possible
ma1 = float('-inf')
mi1 = float('inf')
ma2 = ma1
mi2 = mi1
# we need the max of the operation that is contributing to the sum and min of the operation that is being deducted
for i in range(len(a)):
ma1 = max(ma1,a[i]+i)
mi1 = min(mi1,a[i]+i)
ma2 = max(ma2,a[i]-i)
mi2 = min(mi2,a[i]-i)
return max((ma1-mi1),(ma2-mi2))
|
'''
Passing game
There is a football event going on in your city. In this event, you are given A passes and players having ids between 1 and 106.
Initially some player with a given id had the ball in his possession. You have to make a program to display the id of the player who possessed the ball after exactly A passes.
There are two kinds of passes:
1) ID
2) 0
For the first kind of pass, the player in possession of the ball passes the ball "forward" to player with id = ID.
For the second kind of a pass, the player in possession of the ball passes the ball back to the player who had forwarded the ball to him.
In the second kind of pass "0" just means Back Pass.
Return the ID of the player who currently posseses the ball.
Problem Constraints
1 <= A <= 100000
1 <= B <= 100000
|C| = A
Example Input
Input 1:
A = 10
B = 23
C = [86, 63, 60, 0, 47, 0, 99, 9, 0, 0]
Input 2:
A = 1
B = 1
C = [2]
Example Output
Output 1:
63
Output 2:
2
'''
# push in the stack when the ball is passed to a new player
# pop when ball is passed back
from collections import deque
class Solution:
def solve(self, a, b, c):
stack = deque()
stack.append(b)
for i in range(a):
if c[i] == 0:
stack.pop()
else:
stack.append(c[i])
return stack[-1]
# TC O(n)
# SC O(n)
|
'''
Vertical Order traversal
Given a binary tree, return a 2-D array with vertical order traversal of it.
NOTE: If 2 Tree Nodes shares the same vertical level then the one with lesser depth will come first.
Problem Constraints
0 <= number of nodes <= 105
Example Input
Input 1:
6
/ \
3 7
/ \ \
2 5 9
Input 2:
1
/ \
3 7
/ \
2 9
Example Output
Output 1:
[
[2],
[3],
[6, 5],
[7],
[9]
]
Output 2:
[
[2],
[3],
[1],
[7],
[9]
]
'''
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# We need to make a map => <distance_from_center,[(depth,root.val)]>
# first we sort based on distance from center
# then within that list we sort based on depth
class Solution:
def sortDistanceWise(self,root,d,lvl,map):
if not root: return
if d not in map:
map[d] = list([tuple([lvl,root.val])])
else:
map[d].append(tuple([lvl,root.val]))
self.sortDistanceWise(root.left,d-1,lvl+1,map)
self.sortDistanceWise(root.right,d+1,lvl+1,map)
return
def verticalOrderTraversal(self, root):
map = {}
self.sortDistanceWise(root,0,0,map)
for i in map.values():
i.sort(key=lambda x:x[0])
if not map: return []
mi = min(map)
ma = max(map)
res = []
for i in range(mi,ma+1):
j = map[i]
lis = []
for x in j:
lis.append(x[1])
res.append(lis)
return res
# TC O(n)
# SC O(n)
|
'''
Maximum Sum
You are given an array A of N integers and three integers B, C, and D.
You have to find the maximum value of A[i]*B + A[j]*C + A[k]*D, where 1 <= i <= j <= k <= N.
Problem Constraints
1 <= N <= 10^5
-10000 <= A[i], B, C, D <= 10000
Example Input
Input 1:
A = [1, 5, -3, 4, -2]
B = 2
C = 1
D = -1
Input 2:
A = [3, 2, 1]
B = 1
C = -10
D = 3
Example Output
Output 1:
18
Output 2:
-4
'''
# maintain a dp arr for which we will compute max val after multiplying it by b or c or d
# initially we need to find the max value between dp[i] = max(b*a[i], dp[i-1])
# now we need to check which ind will give us max when multiplied by c
# plus dp[i], so we will store dp[i] = max(c*a[i]+dp[i], dp[i-1])
# Now we need to do the same for d
class Solution:
def solve(self, a, b, c, d):
dp = [0]*len(a)
dp[0] = b*a[0]
for i in range(1,len(a)):
dp[i] = max(b*a[i], dp[i-1])
for i in range(1,len(a)):
dp[i] = max(b*a[i], dp[i-1])
dp[0] = dp[0] + a[0]*c
for i in range(1,len(a)):
dp[i] = max(c*a[i]+dp[i], dp[i-1])
dp[0] = dp[0] + a[0]*d
for i in range(1,len(a)):
dp[i] = max(d*a[i]+dp[i], dp[i-1])
return dp[-1]
# TC O(n)
# SC O(n)
|
'''
Count Right Triangles
Given two arrays of integers A and B of size N each, where each pair (A[i], B[i]) for 0 <= i < N represents a unique point (x, y) in 2D Cartesian plane.
Find and return the number of unordered triplets (i, j, k) such that (A[i], B[i]), (A[j], B[j]) and (A[k], B[k]) form a right angled triangle with the triangle having one side parallel to the x-axis and one side parallel to the y-axis.
NOTE: The answer may be large so return the answer modulo (109 + 7).
Problem Constraints
1 <= N <= 105
0 <= A[i], B[i] <= 109
Example Input
Input 1:
A = [1, 1, 2]
B = [1, 2, 1]
Input 2:
A = [1, 1, 2, 3, 3]
B = [1, 2, 1, 2, 1]
Example Output
Output 1:
1
Output 2:
6
'''
class Solution:
# from a pivot point, same x points and y points will give us the other two points to form the triangle
# which is parallel to the axis
# all the same x points - (pivot point, 1) * all the same y points - (pivot point, 1) will give us all triangles
# for one pivot point
def solve(self, a, b):
ans = 0
mx = {}
my = {}
for i in range(len(a)):
if a[i] in mx:
mx[a[i]] += 1
else:
mx[a[i]] = 1
if b[i] in my:
my[b[i]] += 1
else:
my[b[i]] = 1
for i in range(len(a)):
ans += (((mx[a[i]]-1)*(my[b[i]]-1)) % (10**9+7))
return ans % (10**9+7)
# TC O(n)
# SC O(n+n) => O(n)
|
'''
Matrix and Absolute Difference
Given a matrix C of integers, of dimension A x B.
For any given K, you are not allowed to travel between cells that have an absolute difference greater than K.
Return the minimum value of K such that it is possible to travel between any pair of cells in the grid through a path of adjacent cells.
NOTE:
Adjacent cells are those cells that share a side with the current cell.
Problem Constraints
1 <= A, B <= 10^2
1 <= C[i][j] <= 10^9
Example Input
Input 1:
A = 3
B = 3
C = [ [1, 5, 6]
[10, 7, 2]
[3, 6, 9] ]
Example Output
Output 1:
4
'''
# let all elements of the matrix be graph points on a graph
# The weights on the edges will be the 2 nodes' absolute difference
# Then apply prim's algorithm to calculate min spanning tree of the matrix
# take the max weighted edge from this MST as the ans
from collections import defaultdict
import heapq as heap
class Graph:
def __init__(self):
self.graph = defaultdict(list)
self.vis = set()
def addEdge(self, v, u, w):
self.graph[v].append((u,w))
def calMinK(self, s):
h = []
heap.heappush(h,(0,s))
k = 0
while h:
w,v = heap.heappop(h)
if v in self.vis:
continue
k = max(w,k)
self.vis.add(v)
for nv,nw in self.graph[v]:
if nv not in self.vis:
heap.heappush(h,(nw,nv))
return k
# TC O(v + e * log e)
# SC O(v + e)
class Solution:
def solve(self, a, b, c):
gr = Graph()
for i in range(a):
for j in range(b):
if i>=1:
gr.addEdge((i-1)*b+j,(i)*b+j,abs(c[i-1][j]-c[i][j]))
if i<a-1:
gr.addEdge((i+1)*b+j,(i)*b+j,abs(c[i+1][j]-c[i][j]))
if j>=1:
gr.addEdge(i*b+(j-1),i*b+j,abs(c[i][j-1]-c[i][j]))
if j<b-1:
gr.addEdge(i*b+(j+1),i*b+j,abs(c[i][j+1]-c[i][j]))
return gr.calMinK(0)
|
'''
Trailing Zeros in Factorial
Given an integer A, return the number of trailing zeroes in A! i.e. factorial of A.
Note: Your solution should run in logarithmic time complexity.
Problem Constraints:
1 <= A <= 109
Input 1
A = 5
Input 2:
A = 6
Output 1:
1
Output 2:
1
'''
class Solution:
# we count all 5s in the factors of a!
def trailingZeroes(self, a):
count = 0
while a>=5:
a = a//5
count += a
return count
|
'''
Level Order
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
Problem Constraints
1 <= number of nodes <= 105
Example Input
Input 1:
3
/ \
9 20
/ \
15 7
Input 2:
1
/ \
6 2
/
3
Example Output
Output 1:
[
[3],
[9, 20],
[15, 7]
]
Output 2:
[
[1]
[6, 2]
[3]
]
'''
from collections import deque
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# add root in queue
# save the size of the queue, s
# when you pop an element from the queue, add its left and right children in the queue
# and push the popped element in the temp list
# once you iterate through s values append the temp list to the res list and start another temp list
# Keep repeating until q is not null
class Solution:
def levelOrder(self, root):
q = deque()
res = []
q.append(root)
while q:
s = len(q)
lvl = []
for i in range(s):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
lvl.append(node.val)
res.append(lvl)
return res
# TC O(n)
# SC O(n)
|
'''
Merge Intervals
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Constraints:
1 <= |intervals| <= 105
Input: Given intervals [1, 3], [6, 9] insert and merge [2, 5]
Output: [ [1, 5], [6, 9] ]
Input: Given intervals [1, 3], [6, 9] insert and merge [2, 6]
Output: [ [1, 9] ]
'''
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def insert(intervals, newInterval):
n = len(intervals)
# if we get an interval where start < end we will convert it to start > end
if newInterval.start > newInterval.end:
newInterval.start, newInterval.end = newInterval.end, newInterval.start
a = Interval()
res = []
# adding the incoming interval with the existing list
for i in range(n):
if intervals[i].start > newInterval.start:
intervals.insert(i,newInterval)
break
if newInterval not in intervals:
intervals.append(newInterval)
ans = Interval(float('-inf'),float('-inf'))
n = len(intervals)
# we need to find the largest (ans.start, ans.end), i.e, min(ans.start) and max(ans.end)
# that can be merged with the previous interval and append it
for i in range(n):
a = intervals[i]
if a.start > ans.end:
if i != 0:
res.append(Interval(ans.start, ans.end))
ans.end = a.end
ans.start = a.start
elif a.end >= ans.end:
ans.end = a.end
# if all the intervals can be merged
if ans.end != float('-inf') and ans not in res:
res.append(ans)
return res
|
'''
Bob and Queries
Bob has an array A of N integers. Initially, all the elements of the array are zero. Bob asks you to perform Q operations on this array.
You have to perform three types of query, in each query you are given three integers x, y and z.
if x = 1: Update the value of A[y] to 2 * A[y] + 1.
if x = 2: Update the value A[y] to ⌊A[y]/2⌋ , where ⌊⌋ is Greatest Integer Function.
if x = 3: Take all the A[i] such that y <= i <= z and convert them into their corresponding binary strings. Now concatenate all the binary strings and find the total no. of '1' in the resulting string.
Queries are denoted by a 2-D array B of size M x 3 where B[i][0] denotes x, B[i][1] denotes y, B[i][2] denotes z.
Problem Constraints
1 <= N, Q <= 100000
1 <= y, z <= N
1 <= x <= 3
Example Input
Input 1:
A = 5
B = [
[1, 1, -1]
[1, 2, -1]
[1, 3, -1]
[3, 1, 3]
[3, 2, 4]
]
Input 2:
A = 5
B = [
[1, 1, -1]
[1, 2, -1]
[3, 1, 3]
[2, 1, -1]
[3, 1, 3]
]
Example Output
Output 1:
[3, 2]
Output 2:
[2, 1]
'''
# Build a segment tree for sum of nums from start to end
# To update choose a mid of start and end and check if id<= mid: go the left sub tree, else right sub tree
# To query find the range that fits our match, if a part of it fits then search for the next part in the other sub tree
class Solution:
def buildSegmentTree(self, a, tree, ind, st, end):
if st == end:
tree[ind] = a[st]
return
mid = (st+end)//2
self.buildSegmentTree(a,tree,2*ind+1,st,mid)
self.buildSegmentTree(a,tree,2*ind+2,mid+1,end)
tree[ind] = tree[2*ind+1] + tree[2*ind+2]
def updateTree(self, a, tree, ind, st, end, id, val):
if st == end:
tree[ind] = val
return
mid = (st + end)//2
if id <= mid:
self.updateTree(a, tree, 2*ind+1, st, mid, id, val)
else:
self.updateTree(a, tree, 2*ind+2, mid+1, end, id, val)
tree[ind] = tree[2*ind+1] + tree[2*ind+2]
def queries(self, tree, ind, st, end, l, r):
if r<st or l>end:
return 0
if l<=st and r>=end:
return tree[ind]
mid = (st+end)//2
left = self.queries(tree, 2*ind+1, st, mid, l, r)
right = self.queries(tree, 2*ind+2, mid+1, end, l, r)
return (left+right)
def solve(self, a, b):
tree = [0]*(4*a)
a = list([0]*a)
self.buildSegmentTree(a,tree,0,0,len(a)-1)
res = []
for i in range(len(b)):
if b[i][0] == 1:
a[b[i][1]-1] = 2*a[b[i][1]-1]+1
val = bin(a[b[i][1]-1]).split('0b')[1]
val = val.count('1')
self.updateTree(a, tree, 0, 0, len(a)-1, b[i][1]-1, val)
if b[i][0] == 2:
a[b[i][1]-1] = a[b[i][1]-1]//2
val = bin(a[b[i][1]-1]).split('0b')[1]
val = val.count('1')
self.updateTree(a, tree, 0, 0, len(a)-1, b[i][1]-1, val)
if b[i][0] == 3:
ones = self.queries(tree, 0, 0, len(a)-1, b[i][1]-1, b[i][2]-1)
res.append(ones)
return res
# TC O(N + Q*log n), Q is the number of queries
# SC O(N)
|
import math
def root2(a,b,c):
t = b*b - 4*a*c
t2 = math.sqrt(t) if t>0 else complex(0,math.sqrt(abs(t))) ##因為複數的英文就是 complex number,所以在Python要表示複數就可以使用:complex(x, y)來表示。x代表實部的數字,y代表虛部的數字。
return [(-b+t2)/(2*a), (-b-t2)/(2*a)]
print("root of 1x^2+4x+0=", root2(1,4,0))
|
def raizQuadrada(num):
valorRaiz = 1
while((valorRaiz*valorRaiz) <= num):
if((valorRaiz*valorRaiz) == num):
return valorRaiz
elif((valorRaiz*valorRaiz) > num):
return valorRaiz-1
else:
valorRaiz+=1
print(raizQuadrada(4))
print(raizQuadrada(9))
print(raizQuadrada(16))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.