blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
d62c2e7b6fe1981f14d7b36a4404a1d58c8e2d57 | Archanasurendran12/python-myworks | /numpyar/np10_arithmatic.py | 1,515 | 3.9375 | 4 | # import numpy as np
# a = np.arange(9, dtype =float).reshape(3,3)
#
# print('first array:')
# print(a)
# print('\n')
#
# print('second array:')
# b = np.array([10,10,10])
# print(b)
# print('\n')
#
# print('add the two arrays:')
# print(np.add(a,b))
# print('\n')
#
# print('substract the two arrays:')
# print(np.subtract(a,b))
# print('\n')
#
# print('multiply the two arrays:')
# print(np.multiply(a,b))
# print('\n')
#tangent values
# import numpy as np
# a = np.array([0,30,45,60,90])
# print(a)
#
# print('sine of different angles:')
# print(np.sin(a*np.pi/180))
# print('\n')
#
# print('cosine values for angles in array:')
# print(np.cos(a*np.pi/180))
# print('\n')
#
# print('tangent values for given angles:')
# print(np.tan(a*np.pi/180))
import numpy as np
a = np.array([0,30,45,60,90])
print('array containing sine values:')
sin = np.sin(a*np.pi/180)
print(sin)
print('\n')
print('compute sine inverse of angles, return values are in radians:')
inv = np.arcsin(sin)
print(inv)
print('\n')
print('check result by converting to degrees:')
print(np.degree(inv))
print('\n')
print('across and arctan functions behave similarly:')
cos = np.cos(a*np.pi/180)
print(cos)
print('\n')
print('inverse of cos:')
inv = np.across(cos)
print(inv)
print('\n')
print('in degrees:')
print(np.degree(inv))
print('\n')
print('tan function:')
tan = np.tan(a*np.pi/180)
print(tan)
print('\n')
print('inverse of tan:')
inv = np.arctan(tan)
print(inv)
print('\n')
print('in degrees:')
print(np.degrees(inv))
|
3d9b0e99515d80dec7481fa0c3bd451b76555478 | EDalSanto/ThinkPythonExercises | /dictionaries.py | 1,301 | 3.96875 | 4 | def histogram(s):
"""
Returns histogram of string as dictionary
s: string
"""
d = {}
for c in s:
if c != " ":
d[c] = d.get(c,0) + 1
return d
print histogram('helllloo') == {'h': 1, 'e': 1, 'l': 4, 'o': 2}
h = histogram('parrot')
def print_hist(h):
"""
Returns sorted histogram keys
"""
return sorted(h.keys())
print print_hist(h) == ['a', 'o', 'p', 'r', 't']
def reverse_lookup(h,v):
"""
Performs a reverse lookup for a key with a certain value
h: dictionary
v: value
Returns a list of all keys with value, v
"""
t = [ k for k in h if h[k] == v ]
return t
print reverse_lookup(h,10) == []
def invert_dict(h):
"""
Inverts dictionary
h: a dictionary
"""
inverse = {}
for key in h:
val = h[key]
inverse.setdefault(val,[])
inverse[val].append(key)
return inverse
print invert_dict(h) == {1: ['a', 'p', 't', 'o'], 2: ['r']}
def has_duplicates(t):
d = {}
for elm in t:
if elm in d:
return True
else:
d[elm] = False
return False
def has_duplicates2(t):
"""
Utilized Set properties to check for duplicates
"""
return len(set(t)) < len(t)
print has_duplicates2([1,2,2]) == True
|
1f9c18db0857575e02e908906deacba309ddf39f | kmgowda/ds-programs-python | /src/string-permutations.py | 838 | 3.796875 | 4 |
def get_perms(lt):
perms = list()
if len(lt) == 0:
return perms
first = lt[0]
rem = lt[1:]
words = get_perms(rem)
if len(words):
for i in range(len(words)):
for j in range(len(words[i])+1):
tmp = list()
tmp.extend(words[i])
tmp.insert(j, first)
perms.append(tmp)
else:
tmp = list()
tmp.append(first)
perms.append(tmp)
return perms
if __name__=="__main__":
print("Python program to print all permutations of string")
str = input("Enter the input string")
lt = list(str)
#print (lt)
perms = get_perms(lt)
print("All permutations of string")
for i in range(len(perms)):
str = ''.join(perms[i])
print("%d : %s" %(i+1, str))
|
5929b0f423754095527085d66c722bf22f210b39 | Hardik11794/TicTacToe-Game-Python | /TicTacToe.py | 6,944 | 4.15625 | 4 |
import random
print("This is TicTacToe !!!")
print(' ')
#*********************************************************
# This function print a board
#*********************************************************
def display_board(board):
print(board[7],'|',board[8],'|',board[9])
print(board[4],'|',board[5],'|',board[6])
print(board[1],'|',board[2],'|',board[3])
#*********************************************************
# This function choose player and marker
#*********************************************************
def player_input():
marker = ' '
while marker != 'X' and marker != 'O':
marker = input("Player 1 Choose your marker 'X' or 'O' : ").upper()
player1 = marker
if player1 == 'X':
player2 = 'O'
else:
player2 = 'X'
print(" ")
print(f"Player 1 is {player1}.")
print(f"Player 2 is {player2}.")
return player1,player2
#*********************************************************
# This function place a marker on board
#*********************************************************
def place_marker(board,marker,position):
board[position] = marker
return(board)
#*********************************************************
# This function checks win
#*********************************************************
def win_check(board,marker):
if board[1]==board[5]==board[9]== marker or board[3]==board[5]==board[7]== marker or board[1]==board[2]==board[3]== marker or board[4]==board[5]==board[6]== marker or board[7]==board[8]==board[9]== marker or board[7]==board[4]==board[1]== marker or board[8]==board[5]==board[2]== marker or board[9]==board[6]==board[3]== marker:
display_board(print_board)
return True
else:
return False
#*********************************************************
# This function decides who will go first
#*********************************************************
def choose_first(player1,player2):
random_player = random.randint(0,1)
if random_player == 0:
print(f"Player 1 will go first with marker {player1}")
player1Turn = True
player2Turn = False
elif random_player == 1:
print(f"Player 2 will go first with marker {player2}")
player1Turn = False
player2Turn = True
return player1Turn,player2Turn
#*******************************************************************
# This function checks particular position is free or not
#*******************************************************************
def space_check(board,position):
if board[position] == ' ':
return True
else:
return False
#*********************************************************
# This function checks free space on the board
#*********************************************************
def full_board_check(board):
if board[1] != ' ' and board[2] != ' ' and board[3] != ' ' and board[4] != ' ' and board[5] != ' ' and board[6] != ' ' and board[7] != ' ' and board[8] != ' ' and board[9] != ' ':
return True
else:
return False
#********************************************************************************
# This function ask player for position and checks if it is available
#********************************************************************************
def player_choice(board):
while True:
position = int(input("Enter your next position(1-9) : "))
if space_check(board,position) == True:
return int(position)
break
else:
print('This position has been filled up, Choose another one.')
continue
#********************************************************************************
# This function ask player for replay
#********************************************************************************
def replay():
ask_replay = input("Do you want to play again ? ").upper()
if ask_replay == "YES":
return True
else:
return False
while True:
print_board = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player1,player2 = player_input() #This function choose player and marker.
print(" ")
player1Turn,player2Turn = choose_first(player1,player2) #This function decides who will go first.
while True:
if player1Turn == True and player2Turn == False:
display_board(print_board) #This function display the board
print(" ")
print('Player 1,Your turn !!')
print(" ")
position = player_choice(print_board) #This function ask player for position and checks if it is available
place_marker(print_board,player1,position) #This function place a marker on board
if win_check(print_board,player1) == True: #This function checks for win
print('Congtulations, Player 1 won !!')
break
if full_board_check(print_board) == False: #This function checks if board is full or not
player1Turn = False
player2Turn = True
if full_board_check(print_board) == True:
display_board(print_board)
print("Game is Draw !!")
break
else:
player1Turn == False and player2Turn == True
display_board(print_board) #This function display the board
print(" ")
print('Player 2,Your turn !!')
print(" ")
position = player_choice(print_board) #This function ask player for position and checks if it is available
place_marker(print_board,player2,position) #This function place a marker on board
if win_check(print_board,player2) == True: #This function checks for win
print('Congtulations, Player 2 won !!')
break
if full_board_check(print_board) == False: #This function checks if board is full or not
player1Turn = True
player2Turn = False
if full_board_check(print_board) == True:
display_board(print_board)
print("Game is Draw !!")
break
if replay() == False: #This function ask player for display
break
|
92cae5e83eb2b42bbfdc05da3f4e4728839448f1 | YaohuiZeng/Leetcode | /438_Find_All_Anagrams_in_a_string.py | 2,086 | 4.03125 | 4 | """
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input:
s: "abab" p: "ab"
Output:
[0, 1, 2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
"""
from collections import Counter, defaultdict
class Solution(object):
# brute-force: time: O()
def findAnagrams1(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
res, len_p = [], len(p)
if len(s) < len_p:
return []
lookup = Counter(p)
for i in xrange(len(s)):
if Counter(s[i:(i + len_p)]) == lookup:
res.append(i)
return res
# sliding window: O(n)
def findAnagrams2(self, s, p):
res = []
len_p, len_s = len(p), len(s)
if len_s < len_p: return res
lookup = defaultdict(int)
for c in p:
lookup[c] += 1
left, right, count = 0, 0, len_p
while right < len_s:
if lookup[s[right]] >= 1: count -= 1
lookup[s[right]] -= 1
right += 1
if count == 0: res.append(left)
if right - left == len_p:
if lookup[s[left]] >= 0:
count += 1
lookup[s[left]] += 1
left += 1
return res
if __name__ == "__main__":
s = "cbaebabacd"
p = "abc"
# s = "abab"
# p = "ab"
print Solution().findAnagrams1(s, p)
print Solution().findAnagrams2(s, p)
|
514f19e9f1e0faf06e6a44354ab8e519392893a7 | coldmanck/leetcode-python | /0289_Game_of_Life.py | 1,599 | 3.84375 | 4 | # Runtime: 32 ms, faster than 57.55% of Python3 online submissions for Game of Life.
# Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Game of Life.
import copy
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def get_nb_of_live_neighbor(board, i, j):
left = max(j-1, 0)
right = min(j+1, len(board[0])-1)
up = max(i-1, 0)
down = min(i+1, len(board)-1)
nb = 0
for k in range(up, down + 1):
for l in range(left, right + 1):
if k == i and l == j: continue
nb += board[k][l]
# if board[k][l] == 1 or board[k][l] == -1:
# nb += 1
return nb
board_old = copy.deepcopy(board)
for i in range(len(board)):
for j in range(len(board[0])):
nb_of_live_neighbor = get_nb_of_live_neighbor(board_old, i, j)
if board[i][j] == 0 and nb_of_live_neighbor == 3:
board[i][j] = 1 # 2 # from 0 to 1
else:
if nb_of_live_neighbor < 2 or nb_of_live_neighbor > 3:
board[i][j] = 0 # -1 # from 1 to 0
# for i in range(len(board)):
# for j in range(len(board[0])):
# if board[i][j] == 2:
# board[i][j] = 1
# elif board[i][j] == -1:
# board[i][j] = 0 |
81f084c3929007e781197fd0f7f55255da1c91fa | FranckNdame/leetcode | /problems/98. Validate Binary Search Tree/solution.py | 691 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if not root:
return True
return self.helper(root, float('-inf'), float('inf'))
def helper(self, node, minVal, maxVal):
if not node:
return True
if node.val <= minVal or node.val >= maxVal:
return False
if not self.helper(node.left, minVal, node.val):
return False
if not self.helper(node.right, node.val, maxVal):
return False
return True
|
e82fa2a4e3929ae9ec35e3cead18fef1e09e6638 | tnmcneil/Algorithms | /zerosumsort.py | 3,898 | 3.71875 | 4 | # Theresa McNeil
# U09757615
# CS 330 Assignment 1
# 4 a: zerosumsort.py in O(n^2 logn) time
#Python 3.6.4
def zerosumsort(sequence):
# make a hard copy of the sequence to refer to later to preserve the original indices
# takes O(n) time
original = list(sequence)
# sort the input sequence which takes nlog(n) time (given by Python)
sequence.sort()
# find all pairs of numbers in the sequence using a double nested for loop and compute
# their sum which takes n^2 time because it iterates through a list of n integers twice
# calculating the sum takes constant time because of instant lookup
for i in range (0, len(sequence)):
for j in range(i+1, len(sequence)):
x = 0 - (sequence[i] + sequence[j])
# now use binary search (O(logn)) to search the list to see if a value equal
# to x exists because that would imply that sequence[i] + sequence[j]
# + x = 0 and x would be our third integer
start = 0
end = len(sequence) - 1
while start <= end:
k = (start + end) // 2
if ((sequence[k] == x) and k != i and k != j):
print ("Success!")
# print ("ints are: ", sequence[i], sequence[j], sequence[k])
return original.index(sequence[i]), original.index(sequence[j]), original.index(sequence[k])
elif sequence[k] > x:
end = k - 1
elif sequence[k] < x:
start = k + 1
else:
return "No"
return "No"
# this program works by first creating a hard copy of the input sequence of integers to preserve the original indices (takes O(n) time) before sorting the
# input sequence using the built in .sort() function in python which takes O(nlog(n)) time as given by the algorithm. Next it iterates through all possible
# pairs in the a double nested for loop, with each loop running in O(n) time, and takes their sum which takes O(1) time since it uses the indexing of
# the list. Next it uses binary search on the sorted list which we know takes O(log(n)) time. The binary search is looking for the negative of the sum we
# previously calculated because this would imply the third integer which sums to 0 is in the list, but also must check to make sure its index is not equal
# to either of the other indices so as to prevent the use of duplicates. If such a match is found we have a success! We then use Python's built in .index
# on the hard copy of the original list to obtain the correct indices of the triplets. Each lookup takes O(n) times and there are three lookups so
# O(n) + O(n) + O(n) = O(3n) = O(n) however because this occurs in an if statement it is only computed once and therefore is added to the overall O(n), not
# multiplied. If no such match is found the function returns "No"
# the overall time complexity is O(n) + O(nlogn) + O(n*n*logn + n + n + n) = O(n) + O(nlogn) + O(n^2logn + 3n) = O(n^2logn) beccause this leading term grows to
# infinity much faster than the rest of them
|
bf1d62f9bde86f8350dab6b89b692a3ea8d84549 | haldokan/PythonEdge | /pythonEdge/src/org/haldokan/edge/lunchbox/pserver.py | 1,998 | 3.53125 | 4 | # server
#!C:\haldokan\3p\Python34\python.exe -u
import sys
import http.server
import urllib
from urllib import request
import cgi
import cgitb
cgitb.enable() # for troubleshooting
"""
By default this is a file server: 'http://localhost:8000' lists the files wher the server is run.
Specifying a file name in the request gets the file content: 'http://localhost:8000/experiment.py'
"""
def runserver(server_class=http.server.HTTPServer, handler_class=http.server.SimpleHTTPRequestHandler):
# host = ''
# or
host = 'localhost'
server_addr = (host, 8000)
httpd = server_class(server_addr, handler_class)
print('Runnig server on address: ' + repr(server_addr))
httpd.serve_forever()
def runcgiserver(server_class=http.server.HTTPServer, handler_class=http.server.CGIHTTPRequestHandler):
host = 'localhost'
server_addr = (host, 8000)
httpd = server_class(server_addr, handler_class)
print('Runnig cgiserver on address: ' + repr(server_addr))
httpd.serve_forever()
def runclient():
try:
with urllib.request.urlopen('http://localhost:8000/experiment.py') as f:
print(f.read().decode('utf-8'))
except urllib.error.HTTPError:
print('NOT FOUND')
def cgirequest():
greetings = b'Hello there!'
req = urllib.request.Request(url='http://localhost:8000/cgi-bin/test.cgi', data=greetings)
f = urllib.request.urlopen(req)
print(f.read().decode('utf-8S'))
def main():
args = sys.argv[1:]
if len(args) < 1:
print('Usage: pserver.py func')
sys.exit(1)
func = args[0]
if func == '--runserver':
runserver()
if func == '--runcgiserver':
runcgiserver()
elif func == '--runclient':
runclient()
elif func == '--cgirequest':
cgirequest()
else: raise RuntimeError('function %s is not defined' % func)
##
if __name__ == '__main__':
main()
|
5c549fdb6872feba3b8035cc08d44fdbcefea6a2 | adrielleAm/ListaPython | /Slide2_1.py | 753 | 4.34375 | 4 | '''
Faça um programa que:
a. Solicite ao usuário que digite o nome de um arquivo texto (caminho completo);
b. Solicite ao usuário que digite uma palavra;
c. Verifique em todo arquivo quais as linhas contêm a palavra. Todas as linhas localizadas devem ser salvas em um novo arquivo texto com o nome FIND_<nome_arquivo_original>, contendo o seguinte:
'''
def escreverArquivo(path, palavraChave):
arquivo = open(path, 'r')
newFile = open('FIND_' + path, 'w')
for l_num, line in enumerate(arquivo, 1):
if(palavraChave in line):
newFile.writelines("[" + str(l_num) + "] " + line)
newFile.close()
arquivo.close()
path = input('Digite o caminho completo do arquivo: ')
palavraChave = input('Digite uma palavra: ') |
dff685ca6bc2b1bdfbfd960da06f0f18890f1aca | invenia/mailer | /mailer/mailer.py | 5,714 | 3.5625 | 4 | """
The Mailer class provides a simple way to send emails.
"""
from __future__ import absolute_import
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
from smtplib import SMTP
import six
_ENCODING = 'utf-8'
class Mailer(object):
"""
The Mailer class provides a simple way to send emails.
"""
def __init__(self, username, password, host='smtp.gmail.com:587'):
self._username = username
self._password = password
self._host = host
self._server = None
def open(self):
"""
Open the mail server for sending messages
"""
self._server = SMTP(self._host)
self._server.starttls()
self._server.login(self._username, self._password)
def close(self):
"""
Close the mail server
"""
self._server.close()
self._server = None
def is_open(self):
"""
Checks whether the connection to the mail server is open
"""
return self._server is not None
def __enter__(self):
self.open()
return self
def __exit__(self, exc_type, exc_value, traceback):
if self.is_open():
self.close()
# I'm fine with the number of arguments
# pylint: disable-msg=R0913
def send(self, recipients, subject, body, mail_as=None, cc_recipients=None,
bcc_recipients=None, attachments=None):
"""
Send an email message.
recipients: either an email address, or a list of email
addresses of the direct recipients of the message.
subject: the header of the message
body: the message body
mail_as: an alias to use for sending the message. If None,
the username for logging into the server is used.
Default: None
cc_recipients: either an email address, or a list of email
addresses of all recipients who are to be receive
Carbon Copies of the message. Default: None
bcc_recipients: either an email address, or a list of email
addresses of all recipients who are to be receive
Blind Carbon Copies of the message. Default: None
attachments: either a filepath, or list of filepaths of all
files that should be added to the message as
attachments. Default: None
"""
if isinstance(recipients, six.string_types):
recipients = [recipients]
if mail_as is None:
mail_as = self._username
if cc_recipients is None:
cc_recipients = []
elif isinstance(cc_recipients, six.string_types):
cc_recipients = [cc_recipients]
if bcc_recipients is None:
bcc_recipients = []
elif isinstance(bcc_recipients, six.string_types):
bcc_recipients = [bcc_recipients]
if attachments is None:
attachments = []
elif isinstance(attachments, six.string_types):
attachments = [attachments]
message = build_message_string(recipients, subject, body, mail_as,
cc_recipients, bcc_recipients,
attachments)
all_recipients = recipients + cc_recipients + bcc_recipients
self._server.sendmail(mail_as, all_recipients, message)
# pylint: enable-msg=R0913
# pylint: disable-msg=R0913
def build_message_string(recipients, subject, body, sender, cc_recipients=None,
bcc_recipients=None, attachments=None):
"""
Build an email message.
NOTE: It's recommended that you use the Mailer object to accomplish
this. besides handling (interfacing) smtp, it also alllows fuller
defaults.
recipients: a list of email addresses of the direct recipients.
subject: the header of the message
body: the message body
mail_as: an alias to use for sending the message. If None,
the username for logging into the server is used.
Default: None
cc_recipients: a list of email addresses of all recipients who are
to be receive Carbon Copies of the message.
Default: None
bcc_recipients: a list of email addresses of all recipients who are
to be receive Blind Carbon Copies of the message.
Default: None
attachments: a list of filepaths of all files that should be added
to the message as attachments. Default: None
"""
subject = subject.encode(_ENCODING)
message = MIMEText(body.encode(_ENCODING), _charset=_ENCODING)
if attachments:
full_message = MIMEMultipart()
full_message.attach(message)
message = full_message
for attachment in attachments:
application = MIMEApplication(open(attachment, 'rb').read())
application.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(attachment))
message.attach(application)
message['Subject'] = subject
message['From'] = sender
message['To'] = _format_addresses(recipients)
if cc_recipients:
message['Cc'] = _format_addresses(cc_recipients)
if bcc_recipients:
message['Bcc'] = _format_addresses(bcc_recipients)
return message.as_string()
# pylint: enable-msg=R0913
def _format_addresses(addresses):
"""
build an address string from a list of addresses
"""
return ', '.join(addresses).encode(_ENCODING)
|
a1de82f0dee560ede5dd413adb937d6977de2a16 | karnsaurabhkumar/soscipy | /soscipy/utilities/progress_bar.py | 1,009 | 3.9375 | 4 | import sys
def update_progress(progress):
"""
Update_progress() : Displays or updates a console progress bar
Accepts a float between 0 and 1. Any int will be converted to a float.
A value under 0 represents a 'halt'.
A value at 1 or bigger represents 100%
:param progress: Float as input
:return: A standard output to display a progress bar
"""
barLength = 10 # Modify this to change the length of the progress bar
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "error: progress var must be float\r\n"
if progress < 0:
progress = 0
status = "Halt...\r\n"
if progress >= 1:
progress = 1
status = "Done...\r\n"
block = int(round(barLength * progress))
text = f"\rPercent Completion: [{'#' * block + '-' * (barLength - block)}] {progress * 100:.2f}% {status}"
sys.stdout.write(text)
sys.stdout.flush() |
d1f021119db123ded005b1fd6c1b7b5070ae02a6 | mfnu/Python-Assignment | /Section4-PickleUnpickleUserData.py | 1,337 | 3.890625 | 4 | ''' Author: Madhulika
Program: Section4-PicleUnpickleUserData.py
Input: Enter name, age and country.
Output: Creates a text file and stores the input information in form of list,
and then reads it back.
Date Created: 5/7/2015
Version : 1
'''
import pickle
f = open("picklesUserData.txt","bw")
name = input("Please enter your name: ")
age = input("Please enter your age: ")
country = input("Please enter your country of origin: ")
myList=[name,age,country]
pickle.dump(myList,f)
f.close()
#--------------------------Function Definition-----------------------------------
'''
Function name: unpickleAndRead
Description: This function unpickles and reads the pickled file.
Input Parameters: None.
'''
def unpickleAndRead(filename):
print("Printing the read data from picklesUserData.txt file: ")
f = open(filename,"br")
myList = pickle.load(f)
print(myList)
f.close()
#--------------------------------------------------------------------------------
#Calling unpickleAndRead function:
unpickleAndRead("picklesUserData.txt")
'''
O/P:
C:\Python34\Assignments>python Section4-PickleUnpickleUserData.py
Please enter your name: Suresh
Please enter your age: 34
Please enter your country of origin: India
Printing the read data from picklesUserData.txt file:
['Suresh', '34', 'India']
''' |
d2d64d210e36255f05881fdea149386e30776d42 | Nand4Kishore/Personal_Projects | /TIC-TAC-TOE-WithAI/TicTacToeGame.py | 7,004 | 4.03125 | 4 | import random
random.seed(1)
import math
class TicTacToeGame:
def __init__(self):
cells = "_________"
self.area = [[*cells[i:i + 3]] for i in range(0, len(cells), 3)]
self.x_turn = len([x for x in cells if x == "X"]) <= len([x for x in cells if x == "O"])
# print(self.area)
def user_turn(self):
while True:
xy = [int(x) for x in input("Enter coordinates:").split(" ") if x.isdigit()]
if len(xy) != 2:
print("You should enter numbers!")
else:
x, y = xy
if min(x, y) < 1 or max(x, y) > 3:
print("Coordinates should be from 1 to 3!")
elif self.area[-y][x - 1] != "_":
print("This cell is occupied! Choose another one!")
else:
return x, y
def start(self):
# self.print_cells()
while True:
cmd = input("Input command:")
actual = 'start easy user medium hard'.split()
com = cmd.split()
if len(com) == 3:
for word in com:
if word in actual:
pass
elif word == 'exit':
return
else:
print('Bad parameters!')
break
break
else:print('Bad parameters!')
#
# if cmd in ['start hard user','start hard hard','start user hard','start easy medium','start medium easy','start medium medium','start easy easy', 'start medium user', 'start user user', 'start user medium','start user easy','start easy user']:
# break
# elif cmd == 'exit':return
# else:
# print('Bad parameters!')
self.print_cells()
#com = cmd.split()
calls = {'easy':self.ezaimove,'hard':self.hardmove,'medium':self.ai_move_easy,'user':self.user_move}
while True:
calls[com[1]]()
self.print_cells()
if self.winwin(): break
calls[com[2]]()
self.print_cells()
if self.winwin(): break
def winwin(self):
win = self.is_game_over()
if win:
if win == 'Draw':
print('Draw')
return True
else:
print(f"{win} wins")
return True
return None
def is_game_over(self):
if "_" in [cell for row in self.area for cell in row]:
winner = self.check_winner()
if winner:
#print(f"{winner} wins")
return winner
else:
winner = self.check_winner()
if winner:
#print(f"{winner} wins")
return winner
else:
#print("Draw")
return 'Draw'
return False
def user_move(self):
x, y = self.user_turn()
self.move(-y, x - 1)
def move(self, y, x):
self.area[y][x] = "X" if self.x_turn else "O"
self.x_turn = not self.x_turn
def ai_move_easy(self):
move = list()
aival = "X" if self.x_turn else "O"
bestscore = -math.inf
cells = [cell for row in self.area for cell in row]
print('Making move level "hard"')
for i in range(3):
for j in range(3):
if self.area[i][j] == "_":
self.area[i][j] = aival
score = self.minimax(self.area,0, False,aival)
self.area[i][j] = "_"
if (score > bestscore):
bestscore = score
move = [i, j]
self.area[move[0]][move[1]] = aival
self.x_turn = not self.x_turn
def hardmove(self):
move = list()
aival = "X" if self.x_turn else "O"
bestscore = -math.inf
cells = [cell for row in self.area for cell in row]
print('Making move level "medium"')
for i in range(3):
for j in range(3):
if self.area[i][j] == "_":
self.area[i][j] = aival
score = self.minimax(self.area,0, False,aival)
self.area[i][j] = "_"
if (score > bestscore):
bestscore = score
move = [i, j]
self.area[move[0]][move[1]] = aival
self.x_turn = not self.x_turn
def ezaimove(self):
aival = "X" if self.x_turn else "O"
print('Making move level "easy"')
cells = [cell for row in self.area for cell in row]
coord = random.choice([i for i, cell in enumerate(cells) if cell == "_"])
cells[coord] = "X" if self.x_turn else "O"
self.x_turn = not self.x_turn
self.area = [[*cells[i:i + 3]] for i in range(0, len(cells), 3)]
def getscore(self,aival,uval,result):
if result == aival : return 10
elif result == uval : return -10
else : return 0
def minimax(self,area,depth,ismax,aival):
uval = 'X' if aival=='O' else "O"
result = self.is_game_over()
score = []
if result :
return self.getscore(aival,uval,result)
if ismax:
for i in range(3):
for j in range(3):
if area[i][j] == "_":
area[i][j] = aival
score .append( self.minimax(area,depth+1, False,aival))
area[i][j] = "_"
else:
for i in range(3):
for j in range(3):
if area[i][j] == "_":
area[i][j] = uval
score .append( self.minimax(area,depth+1, True,aival))
area[i][j] = "_"
return max(score) if ismax else min(score)
def check_winner(self):
row1 = "".join(self.area[0])
row2 = "".join(self.area[1])
row3 = "".join(self.area[2])
col1 = "".join([self.area[0][0], self.area[1][0], self.area[2][0]])
col2 = "".join([self.area[0][1], self.area[1][1], self.area[2][2]])
col3 = "".join([self.area[0][2], self.area[1][2], self.area[2][2]])
diagonal1 = "".join([self.area[0][0], self.area[1][1], self.area[2][2]])
diagonal2 = "".join([self.area[0][2], self.area[1][1], self.area[2][0]])
winner_positions = [row1, row2, row3, col1, col2, col3, diagonal1, diagonal2]
if "XXX" in winner_positions:
return "X"
elif "OOO" in winner_positions:
return "O"
return None
def print_cells(self):
print('---------')
print(f"| {' '.join(self.area[0]).replace('_', ' ')} |")
print(f"| {' '.join(self.area[1]).replace('_', ' ')} |")
print(f"| {' '.join(self.area[2]).replace('_', ' ')} |")
print('---------')
game = TicTacToeGame()
game.start() |
fca3a978ca9fcd17fab22cfecfd4e7e81a318edb | Linxichuan/drone | /test.py | 131 | 3.578125 | 4 | print("this is tklin for drone test")
def save(num):
if num == 2:
return
else:
print("tklin")
save(5)
|
10ed38baf9ff435dd2c0bb3ae87b671f4d3241b4 | Energy-Gauntlet/energy-gauntlet-server | /energy_gauntlet/commands/__init__.py | 783 | 3.609375 | 4 | from command import Command
def factory(cmd_type, params = {}):
"""Used to define command classes at run time."""
def __init__(self, new_params = {}):
params.update(new_params)
Command.__init__(self, cmd_type, params)
newclass = type(cmd_type, (Command,),{"__init__": __init__})
return newclass
Drive = factory('drive', { 'forwardBack': 0, 'leftRight': 0 })
VariableDrive = factory('variableDrive', { 'forwardBack': 0, 'leftRight': 0 })
TurnByDegrees = factory('turnByDegrees', { 'theDegrees': 0 })
PoleUp = factory('poleUp')
PoleDown = factory('poleDown')
PoleStop = factory('poleStop')
DeployKickstands = factory('deployKickstands')
RetractKickstands = factory('retractKickstands')
Speak = factory('speak', { 'string': '' })
|
83336bc9e82144d67fa8b7766f3365ec4c43ecfb | klaseskilson/aoc-2020 | /day03/main.py | 535 | 3.53125 | 4 | def count(trees: [str], dy: int, dx: int) -> int:
c, x, y = [0, 0, 0]
while y < len(trees):
c += trees[y][x % len(trees[0])] == "#"
x += dx
y += dy
return c
def main():
inputs = [str(s) for s in open("input.txt", "r").read().splitlines()]
print("part one:", count(inputs, 1, 3))
# part 2
moves = [[1, 1], [1, 3], [1, 5], [1, 7], [2, 1]]
a = 1
[a := a * c for c in [count(inputs, *move) for move in moves]]
print("part two:", a)
if __name__ == "__main__":
main()
|
810d269b316d05fe7fa043409267428810861665 | ggbiun/roulette | /roulette.py | 4,977 | 3.75 | 4 | from random import randint as r
from math import log2, floor
class Roulette:
""" Roulette class for representing and manipulating a roulette spin wheel. """
def __init__(self, color_streak, min_bet, max_bet, spin_time, max_dur, net_gain_stop):
self.color_streak=color_streak #Sets how many same color spins need to occur until a bet is placed on the opposite color.
self.min_bet=min_bet
self.max_bet=max_bet
self.spin_time=spin_time
self.max_dur=max_dur
self.net_gain_stop=net_gain_stop
self.game_counter=0
self.loss_streak=0
self.max_loss_streak=0
self.game_bet=min_bet
self.start_balance=min_bet*(2*(2**floor(log2(max_bet/min_bet)))-1) #calculate starting balance where n=log2(max bet/min bet))
self.game_balance=self.start_balance
self.max_game_counter=floor(60*self.max_dur/self.spin_time)
self.game_color_streak=0
self.previous_color='' #Used to determine color streak
self.wheel_color_landed='NONE'
self.bet_color='NA'
self.bet_next_spin=False
self.game_outcome='NA'
def wait_for_streak(self):
if self.wheel_color_landed != 'g':
if self.wheel_color_landed == self.previous_color:
self.game_color_streak+=1
if self.game_color_streak >= self.color_streak:
if self.wheel_color_landed == 'r':
self.bet_color='b'
self.bet_color='r'
else:
self.game_color_streak=1
if self.game_counter !=0:
self.previous_color=self.wheel_color_landed
else:
self.game_color_streak=1
def spin_wheel(self):
self.game_counter+=1
list_pos=0
available = ['-0g', '28b', '09r', '26b', '30r', '11b', '07r', '20b', '32r', '17b',
'05r', '22b', '34r', '15b', '03r', '24b', '36r', '13b', '01r', '00g',
'27r', '10b', '25r', '29b', '12r', '08b', '19r', '31b', '18r', '06b',
'21r', '33b', '16r', '04b', '23r', '35b', '14r', '02b']
list_pos=r(0,37)
self.wheel_color_landed = available[list_pos][2:] #returns (r)ed, (b)lack, (g)reen
if self.bet_color=='NA':
if self.wheel_color_landed in ('g', 'r'):
self.bet_color='b'
else:
self.bet_color='r'
def bet_or_pass(self):
#Determine if a bet should be made or wait for streak
if self.game_color_streak>=self.color_streak:
self.bet_next_spin = True
else:
self.bet_next_spin=False
return self.bet_next_spin
def process_bet(self):
if self.wheel_color_landed == self.bet_color: #Won or Lost
self.game_outcome='Won'
self.game_balance+=self.game_bet
self.game_bet=self.min_bet
self.loss_streak=0
self.game_color_streak
else:
self.game_outcome='Lost'
self.game_balance-=self.game_bet
self.game_bet*=2
self.loss_streak+=1
if self.loss_streak>self.max_loss_streak:
self.max_loss_streak=self.loss_streak
self.game_color_streak=0
return self.game_outcome
def game_over(self):
if ((self.game_counter >= self.max_game_counter and self.game_outcome == 'Won') or
self.game_bet > self.max_bet or self.game_bet > self.game_balance or
(self.game_balance-self.start_balance)>=self.net_gain_stop):
return 'Game Over'
def final_results(self):
net=(self.game_balance-self.start_balance) #/(self.game_counter*self.spin_time/60)
return (self.game_counter, self.min_bet, self.max_bet, self.start_balance,
self.game_balance, net, self.max_loss_streak)
def __repr__(self):
return 'Hello World'
def main():
day=0
net_gain=0
min_bet=int(input('Enter Min Bet: '))
color_streak=int(input("Enter Color Streak Before Bet: "))
net_gain_stop=int(input("Daily Net Gain: "))
for y in range(365):
x=''
min_bet=5 #int(input('Enter Min Bet: '))
max_bet=5000 #int(input('Enter Max Bet: '))
spin_time=1 #float(input('Enter Time Between Spins (minutes): '))
max_dur=4 #float(input('Enter Max Play time (hours): '))
gambler=Roulette(color_streak, min_bet, max_bet, spin_time, max_dur, net_gain_stop)
while x !='Game Over':
gambler.wait_for_streak()
if gambler.bet_or_pass():
gambler.spin_wheel()
gambler.process_bet()
else:
gambler.spin_wheel()
x=gambler.game_over()
net=gambler.final_results()
day+=1
net_gain+=net[5]
print('Day: ', day, gambler.final_results(), 'Net= ', net_gain)
if __name__ == "__main__":
main() |
3b37e643e793cb43bb9e48f79ba352d847cdd96c | JEH127/EXERCICES | /somme_multiple_3_5.py | 310 | 3.609375 | 4 | somme_multiple_3 = 0
for i in range(1000):
if i % 3 == 0:
somme_multiple_3 += i
print(f"somme_multiple_3 < 1000 = {somme_multiple_3}")
somme_multiple_5 = 0
for i in range(1000):
if i % 5 == 0:
somme_multiple_5 += i
print(f"somme_multiple_5 < 1000 = {somme_multiple_5}")
|
cd513bf8c89d6a9fb0a64d5ea6686d745961adcf | michaelatmywork/TopoE | /calculations/binary_decision_tree.py | 8,021 | 3.921875 | 4 | test = "trees are connected"
#######################################################################
# SCENARIO RESULTS -- tied to the leaves of the binary decision tree.
msg_condition_results = {
1: "Your customers complain about losing energy on a normal basis, and the electric grid tends to go dark during heat waves. Also, your company is being charged by the state for failing their renewables target.",
2: "Your customers lose power during normal days and heat waves, but at least you have made your renewables target to help the environment!",
3: "Your electric grid doesn't have enough energy to function on most days, but has too much energy during sunny heat waves -- causing local areas in the grid to melt down (e.g. voltage flux).",
4: "You definitely keep the lights on for your customers, during both the normal days and the hot ones. However, your environmental foresight is lacking and your grandchildren have asthma.",
5: "You have hit your environmental goals, while keeping the lights on during both normal days and heat waves. Congratulations! You should apply to be a utility CEO!",
6: "Your customers have energy most days, and your renewable targets are awesome. However, during intense heat waves the excess sunny energy may cause voltage fluctuations. (Congrats...you have melted your distribution grid.)"
}
####################################################################
# MAKE NODES for the binary decision tree.
class Node(object):
def __init__(self, left=None, right=None, threshold=None, fuel_type=None, msg=None):
assert left is None or isinstance(left, Node)
assert right is None or isinstance(right, Node)
self.fuel_type = fuel_type # what fuel type will be tested
self.threshold = threshold # what the threshold is for the test
self.left = left # this is the left child
self.right = right # this is the right child
self.msg = msg
def __repr__(self):
"""Return debugging-friendly representation of node."""
return "<BDT_Node. msg: %s >" % (self.msg)
def testing_condition(self, condition_dict):
current_node = self
if current_node.left==None and current_node.right==None: # no children
return current_node.msg
if condition_dict[current_node.fuel_type] <= current_node.threshold:
current_node = current_node.left
return current_node.testing_condition(condition_dict)
if condition_dict[current_node.fuel_type] > current_node.threshold:
current_node = current_node.right
return current_node.testing_condition(condition_dict)
## LESSON LEARNED. recursion makes another instance of this function, and pauses the original function. Will return to the original function afterwards.
## LESSON LEARNED. since recursive functions which return the result (self.msg), then return to continue the idled functions started earlier....the return result will be overwritten. therefore, need to call the recursive function be "return recursive_function(self,params)". so final return function, returns to the previos function which was paused, which returns to the previos function paused, etc up the tree.
##################################################################
# BUILD THE TREE!
# leaves are the resultant decisions. msg is pulled from dict of msg_condition_results.
bdt_leaf_1 = Node(msg=["alert alert-danger", msg_condition_results[1]])
bdt_leaf_2 = Node(msg=["alert alert-warning", msg_condition_results[2]])
bdt_leaf_3 = Node(msg=["alert alert-danger", msg_condition_results[3]])
bdt_leaf_4 = Node(msg=["alert alert-warning", msg_condition_results[4]])
bdt_leaf_5 = Node(msg=["alert alert-success", msg_condition_results[5]])
bdt_leaf_6 = Node(msg=["alert alert-danger", msg_condition_results[6]])
# leaves 1&2 and 4&5 all undergo the renewables-target-test, to see if above 30% threshold
bdt_renewables_target_test1 = Node(left=bdt_leaf_1, right=bdt_leaf_2, threshold=30, fuel_type="renewables_total", msg="renewables target test 1 (left)")
bdt_renewables_target_test2 = Node(left=bdt_leaf_4, right=bdt_leaf_5, threshold=30, fuel_type="renewables_total", msg="renewables target test 2 (right)")
# the parent of 1&2 (renewable node test1 above), and the leaf 3, undergo the solar density test if above 35% threshold.
bdt_solar_density_test1 = Node(left=bdt_renewables_target_test1, right=bdt_leaf_3, threshold=35, fuel_type="solar", msg="solar density test 1 (left)")
# the parent of 4&5 (renewable node test2 above), and the leaf 6, undergo the solar density test if above 35% threshold.
bdt_solar_density_test2 = Node(left=bdt_renewables_target_test2, right=bdt_leaf_6, threshold=35, fuel_type="solar", msg="solar density test 2 (right)")
# for both solar_density_test nodes, they are children of the root.
## root has a test if the baseload % is above 60.
# (This 70% is highly abstracted. Actual grid reliability could be maintained with a higher % renewables if we simply had a TON of total MWs. So the MWs needed for baseload would be there as a smaller % of a larger MW total.)
bdt_root_test = Node(left=bdt_solar_density_test1, right=bdt_solar_density_test2, threshold=60, fuel_type="baseload_total", msg="baseload test")
###################################################################
# when this moodule gets imported into the server.py, it auto-runs and creates the bdt, and dictionary of message results.
# then this specific function below, gets only called on the specific frontend data.
def bdt_on_user_input(user_input_dict, bdt_root_test=bdt_root_test):
results_dict = {}
for county,condition in user_input_dict.items():
# enter into condition dict, the two additional values used in the decision tree
user_input_dict[county]["renewables_total"] = int(user_input_dict[county]["solar"]) + int(user_input_dict[county]["wind"]) + int(user_input_dict[county]["hydro"])
user_input_dict[county]["baseload_total"] = int(user_input_dict[county]["gas"]) + int(user_input_dict[county]["coal"]) + int(user_input_dict[county]["nuclear"])
# run condition through the decision tree, and assign result to dict per county
results_dict[county] = bdt_root_test.testing_condition(condition)
return results_dict
# TESTING ANOTHER INTERACTIVE MAP, WITH WHOLE USA
def bdt_on_user_input_usa(user_input_dict, bdt_root_test=bdt_root_test):
results_dict = {}
for state,condition in user_input_dict.items():
# enter into condition dict, the two additional values used in the decision tree
user_input_dict[state]["renewables_total"] = int(user_input_dict[state]["solar"]) + int(user_input_dict[state]["wind"]) + int(user_input_dict[state]["hydro"])
user_input_dict[state]["baseload_total"] = int(user_input_dict[state]["gas"]) + int(user_input_dict[state]["coal"]) + int(user_input_dict[state]["nuclear"])
# run condition through the decision tree, and assign result to dict per state
results_dict[state] = bdt_root_test.testing_condition(condition)
return results_dict
###################################################################
# # TEST THE DECISION TREE!
# fuel_mix_test = {
# "Alameda": {"gas":30, "coal":20, "solar":14, "wind":20, "nuclear": 30, "hydro":30, "other":14},
# "Alpine": {"gas":16, "coal":14, "solar":40, "wind":14, "nuclear": 14, "hydro":14, "other":14},
# "Amador": {"gas":30, "coal":40, "solar":14, "wind":0, "nuclear": 14, "hydro":0, "other":14},
# "Butte": {"gas":16, "coal":14, "solar":14, "wind":14, "nuclear": 14, "hydro":14, "other":14}
# }
# # alameda should be all good.
# # alpine should have too litte norm, and too much solar
# # amador should be good on norm and heat, and missing renewables target.
# # but has too little on norm and heat waves, but at least made renewable target
# print bdt_on_user_input(fuel_mix_test)
|
4ba5396e9671bc2572d4377cf71c2b4911c4e095 | loredanasandu/algorithms-and-data-structures | /Course 1 - Algorithmic Toolbox/algorithmic-warmup/fibonacci_last_digit.py | 821 | 4.1875 | 4 | # Computes the last digit of the n-th Fibonacci number.
# Input: A non-negative integer n.
# Output: the last digit of the n-th Fibonacci number.
import sys
def get_fibonacci_last_digit_naive(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current % 10
def get_fibonacci_last_digit_with_pisano(n):
if n <= 1:
return n
pisano_period = 60 # Pisano period of 10 is 60
while n >= pisano_period:
if n % pisano_period != 0:
n = n % pisano_period
else:
break
return get_fibonacci_last_digit_naive(n)
if __name__ == '__main__':
input = sys.stdin.read()
n = int(input)
print(get_fibonacci_last_digit_with_pisano(n))
|
6cfa54df17f8cee35cc244272602c6eecddb98b2 | daniel-reich/turbo-robot | /9wfEZ4898nnpa9wL5_23.py | 466 | 3.765625 | 4 | """
Create a function that returns the ASCII value of the passed in character.
### Examples
ctoa("A") ➞ 65
ctoa("m") ➞ 109
ctoa("[") ➞ 91
ctoa("\") ➞ 92
### Notes
* Don't forget to `return` the result.
* If you get stuck on a challenge, find help in the **Resources** tab.
* If you're _really_ stuck, unlock solutions in the **Solutions** tab.
"""
def ctoa(char):
return ord(char)
print(ctoa("$"))
|
7609f87c1f60972ad820641bebafcb5256eed5ab | jerrylee17/Algorithms | /KattisPractice/Winter2020/SecureDoors.py | 430 | 3.75 | 4 | tc = int(input())
room = set()
for _ in range(tc):
action, name = input().split(' ')
if action == 'entry':
res = f'{name} entered'
if name in room:
res += ' (ANOMALY)'
else:
room.add(name)
print(res)
else:
res = f'{name} exited'
if name not in room:
res += ' (ANOMALY)'
else:
room.remove(name)
print(res)
|
5e26e7218d373be3eb84369154caeb5292c286f4 | polmonroig/bird_call | /src/utils/stats.py | 392 | 3.9375 | 4 | import numpy as np
def count_unique(data):
"""
Counts the quantity of unique values in a list
of values
"""
count = {}
for d in data:
d = d.split('-')[0]
if d in count:
count[d] += 1
else:
count[d] = 1
values = [count[k] for k in sorted(count.keys())]
total = np.arange(len(count))
return total, values
|
8471adafff728201425af98e4a609e071cf2fc86 | nikuzuki/I111_Python_samples | /1/34.py | 236 | 3.8125 | 4 | # 最大値を取得する
# 最大値を求めたいデータが入ったlistを用意
data = [3, 2, 1, 5, 7, 9, 0, 4, 6, 8]
ans_max = data[0]
for i in data:
if ans_max < i:
ans_max = i
print("最大値は"+str(ans_max))
|
74fb7adf733ca1a5474ffdfb056fb1acf54bff99 | dariadiatlova/spellchecker | /src/utils.py | 1,709 | 3.84375 | 4 | from data import DATA_ROOT_PATH
import pandas as pd
import nltk
def filter_vocabulary():
"""
Function filters vocabulary from words we consider incorrect and adds to the dictionary correct words from lowercase
and capital letter.
:return: list
"""
df = pd.read_csv(DATA_ROOT_PATH / "wordlist.txt", header=None)
wrong_words = pd.read_csv(DATA_ROOT_PATH / "test.txt", sep="\t", header=None)[0]
wrong_words = [w.lower() for w in wrong_words]
vocabulary = []
for word in df[0]:
if word not in wrong_words:
vocabulary.append(word)
vocabulary.append(word.upper())
print(f"Vocabulary size: {len(vocabulary)}")
return vocabulary
def get_unigram_frequency_dictionary(unigram_count_filepath: str = DATA_ROOT_PATH / "unigram_freq.csv") -> dict:
"""
Function takes path to csv file with columns: "word", "count". Computes the probability of each word
and returns a dictionary with words and their probabilities.
:param unigram_count_filepath: Union[Path, str] path to csv file with words and their counts
:return: dict
"""
frequency_df = pd.read_csv(unigram_count_filepath)
total_count = frequency_df.sum(axis=0)[0]
frequency_df["count"] = frequency_df["count"].div(total_count)
frequency_df = frequency_df.dropna()
frequency_dictionary = dict(zip(frequency_df["word"], frequency_df["count"]))
return frequency_dictionary
def words_preprocessing(words: pd.Series):
lematizer = nltk.stem.WordNetLemmatizer()
lemmatized_words = [lematizer.lemmatize(word.lower()) for word in words]
if len(lemmatized_words) == 1:
return lemmatized_words[0]
return lemmatized_words
|
2867127992952e9d2e2c609db7a299d3af424cd1 | seilkhanovk/Pavlo_Glovo | /user/shit.py | 81 | 3.640625 | 4 | arr = ["a", "b", "c"]
dict = {"abc": arr, "b": None}
for a in dict:
print(a)
|
62840b9dedf42071fe05e344c02cfbe9ac2ce8e4 | ncc1701k/Database | /Modeling/processor/helpers/data_objects.py | 3,545 | 4.09375 | 4 | import itertools
class ShotsData(object):
'''
ShotsData: This object holds some shots data for easier manipulation and
output.
Attributes:
oord: Whether the shots data represents offense or defense.
size: Data for player size, ie big/small/ALL
data: A dict with keys of dates, values of dicts containing data
'''
def __init__(self, oord, size, data):
self.oord = oord
self.size = size
self.data = data
def __repr__(self):
# String representation, shows up with print()
return '{' + str(self.oord) + ',' + str(self.size) + '}'
class DataVars(object):
'''
DataVars: This object holds variables and makes it easier to collect and
aggregate them. Acts like an ordereddict with extra methods to make
adding new elements easier.
Used to collect player_vars, team_vars, game_vars into a row for a single
game output.
Attributes:
- values: a list of all data values
- header: a list of all labels corresponding to the data values
- prefix: a string prefix to tack onto header items
Methods:
- add_datavars(): Combine other DataVars objects with this one
- add_lists_of_datavars(): Takes in lists of DataVars objects and
combines them into one DataVars objects.
- add_dict(): Takes in a dict of data and adds it into the
current datavar object
- add_shots_data(): Takes in a ShotData object and adds it to current object
'''
def __init__(self, prefix=''):
self.values = []
self.header = []
self.prefix = prefix
def __repr__(self): # string representation
return str(zip(self.header, self.values))
def add_datavars(self, *datavars):
# iterate through DataVars objects received in arguments
for datavar in datavars:
# add each DataVars object to the values and headers
self.values.extend(datavar.values)
self.header.extend(datavar.header)
def add_lists_of_datavars(self, *lists_datavars):
# iterate through arguments
for list_datavar in lists_datavars:
# if current arg is a list, add all list elements
if isinstance(list_datavar, list):
self.add_datavars(*list_datavar)
# otherwise if it's a singleton, add that one DataVars object
else:
self.add_datavars(list_datavar)
def add_dict(self, add_dict, data_prefix=''):
# sort the dict received into a list of sorted tuples
sorted_items = sorted(add_dict.items())
# add the values from the dict into self.values
self.values.extend([item[1] for item in sorted_items])
# mumbo jumbo to get string prefixes for the header right
full_prefix = ''
if self.prefix:
full_prefix = full_prefix + self.prefix + '_'
if data_prefix:
full_prefix = full_prefix + data_prefix + '__'
# add the keys from the dict into the header with appropriate prefixes
self.header.extend([full_prefix + str(item[0]) for item in sorted_items])
def add_shots_data(self, shots_data, date, data_prefix=''):
# grab the data dict from the ShotsData object
add_dict = shots_data.data[date]
# create a string prefix with offense/defense and player size
shots_prefix = data_prefix + '_' + str(shots_data.oord) + '_' + str(shots_data.size)
# add the data dict to the current object
self.add_dict(add_dict, shots_prefix)
|
dd6f6f85690bcdca49e0dbe46f72194ad65362c6 | milnorms/pearson_revel | /ch6/ch6p2.py | 1,335 | 4.28125 | 4 | '''
(Financial application: compute the future investment value)
Write a function that computes a future investment value at a given interest rate for a specified number of years. The future investment is determined using the formula in Programming Exercise 2.19 in Chapter 2 Programming Exercise from the Book.
Use the following function header:
def futureInvestmentValue(investmentAmount, monthlyInterestRate, years):
For example, futureInvestmentValue(10000, 0.05/12, 5) returns 12833.59.
Write a test program that prompts the user to enter the investment amount and the annual interest rate in percent and prints a table that displays the future value for the years from 1 to 30.
Sample Run
The amount invested: 1000
Annual interest rate: 9
Years Future Value
1 1093.80
2 1196.41
...
29 13467.25
30 14730.58
'''
def futureInvestmentValue(investmentAmount, monthlyInterestRate, years):
numberOfMonths = years * 12
futureInvestmentAmount = investmentAmount * ((1 + monthlyInterestRate) ** numberOfMonths)
return futureInvestmentAmount
investment = int(input("The amount invested: "))
annual_interest = float(input("Annual interest rate: "))
interest = annual_interest / 100
print("Years Future Value")
for i in range(1, 31):
print(i, format(futureInvestmentValue(investment, interest/12, i), "0.2f"))
|
b7d3fbb06a7618af9cfaf29b008ab50ad60515d7 | kumar-akshay324/projectEuler | /proj_euler_q007.py | 351 | 3.90625 | 4 | # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
n,c,n_count=1,0,0
while True:
for i in range(1,n+1):
if n%i ==0:
c = c +1
if n==2:
n_count = n_count +1
if n_count == 10001:
break
n = n + 1
print ("The 10 001st prime number is %d" %(n))
|
5cc02d81a0e8a0b7ec41999720f6ccca922ac6dc | HarperHao/python | /exercise/002.py | 442 | 3.796875 | 4 | """
请编写一个函数fun(),它的功能是:求解一个数各个数据位的平方和,
一个数各数字的平方求和最终得到1或145,返这个数。主函数已经实现结果的输出
"""
def fun(number):
sum = 0
for i in number:
sum = sum + int(i) ** 2
if sum == 1 and sum == 145:
return number
else:
return sum
number = input("请输入一个数:")
x = fun(number)
print(x)
|
245d359cf6956c709c5f9d368c612798f10adb8c | Holladaze804/Python-Problems | /Input_Number_Problem.py | 206 | 4 | 4 | a = int(input("What is the first number that you want to enter into the equation? "))
b = int(input("What is the second number that you want to enter into the equation? "))
print(a+b)
print(a-b)
print(a*b)
|
882c0480c9ae73e554bf02d77e2c641dd14dd82a | anomitra/ds-algo-python | /heaps/heap_classes.py | 3,214 | 3.78125 | 4 | class Heap(object):
def __init__(self):
self.array = [-1]
def size(self):
return len(self.array) - 1
def show(self):
print(*self.array[1:], sep=' ')
def move_up(self, index):
return NotImplementedError()
def insert(self, element):
self.array.append(element)
self.move_up(self.size())
def pop(self):
current_size = self.size()
element = self.array[1]
self.array[1] = self.array[current_size]
self.array = self.array[:-1]
self.move_down(1)
return element
def move_down(self, index):
return NotImplementedError()
def heapify(self, array):
self.array = [-1] + array[:]
mid = len(array) // 2
for i in range(mid, 0, -1):
self.move_down(i)
def peek(self):
return None if self.size() == 0 else self.array[1]
class MinHeap(Heap):
def move_up(self, index):
while index // 2 > 0:
if self.array[index] < self.array[index // 2]:
temp = self.array[index]
self.array[index] = self.array[index // 2]
self.array[index // 2] = temp
index = index // 2
def move_down(self, index):
while True:
min_below = self.min_child(index)
if min_below and self.array[min_below] < self.array[index]:
self.array[min_below], self.array[index] = self.array[index], self.array[min_below]
else:
return
index = min_below
def min_child(self, index):
if index * 2 < self.size():
left = index * 2
right = index * 2 + 1
l_val = self.array[left]
r_val = self.array[right] if self.size() > right else None
if not r_val:
return left
else:
if l_val > r_val:
return right
else:
return left
class MaxHeap(Heap):
def move_up(self, index):
while index // 2 > 0:
if self.array[index] > self.array[index // 2]:
temp = self.array[index]
self.array[index] = self.array[index // 2]
self.array[index // 2] = temp
index = index // 2
def move_down(self, index):
while True:
min_below = self.min_child(index)
if min_below and self.array[min_below] > self.array[index]:
self.array[min_below], self.array[index] = self.array[index], self.array[min_below]
else:
return
index = min_below
def min_child(self, index):
if index * 2 < self.size():
left = index * 2
right = index * 2 + 1
l_val = self.array[left]
r_val = self.array[right] if self.size() > right else None
if not r_val:
return left
else:
if l_val < r_val:
return right
else:
return left
# heap = MaxHeap()
# for i in range(1, 17):
# heap.insert(i)
# for i in range(16):
# heap.pop()
# # heap.show()
|
4663d769b1a12a981de13fe958e9f40e5ebc0f3b | yumesaka/CheckiO_jungwoo | /Scientific Expedition/10.Double Substring.py | 675 | 3.90625 | 4 | def double_substring(line):
sameword_list = []
for i in range(len(line)-1):
for j in range(i, len(line)):
if line[i:j] in line[j:]:
sameword_list.append(line[i:j])
if len(sameword_list) >0 :
print(max(sameword_list, key=len))
return len(max(sameword_list, key= len))
else:
return 0
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert double_substring('aaaa') == 2, "First"
assert double_substring('abc') == 0, "Second"
assert double_substring('aghtfghkofgh') == 3, "Third"
print('"Run" is good. How is "Check"?') |
73237a418ce6f2e1bb88317a5e37fce51b4a201f | mhoma-b/exercice-algo | /int_divisible_by_3_or_5.py | 689 | 3.59375 | 4 | #exercice 1: Calculer la somme des entiers divisible par 3 ou par 5 entre 1 et n.
class N : # Définition de notre classe
def __init__(self, nb): # Définition du constructeur
self.n = nb
def run(self): # Définition de la méthode run
i = 0 # la variable qu'on incrémentera
sum_int = 0 # la variable qui stockera la somme de tous les entiers divisibles par 3 ou 5
while(i < self.n): # tant que i < à l'entier limite
if( i%3 ==0) or (i%5 == 0): # on vérifie que i est divisible par 3 ou 5
sum_int += i
i = i + 1 # on incrémente i
return(sum_int)
#def get_classes(): #définition de get_classes()
#en cours...
myObj = N(30)
myObj.run();
|
68e1a53bbb8f5ac45559ebf23b3db6845dad4d0b | devsantoss/Modelos-II | /ejercicios de arboles binarios/arbol.py | 1,298 | 3.734375 | 4 | class Nodo:
def __init__(self, valor, izquierda = None, derecha = None):
self.valor = valor
self.izquierda = izquierda
self.derecha = derecha
def buscar(arbol, valor):
if arbol == None:
return False
elif arbol.valor == valor:
return True
elif valor > arbol.valor:
return buscar(arbol.derecha, valor)
else:
return buscar(arbol.izquierda, valor)
def aLista(arbol):
if arbol == None:
return []
return aLista(arbol.izquierda) + [arbol.valor] + aLista(arbol.derecha)
def insertarValor(arbol, valor):
if arbol == None:
return Nodo(valor)
elif valor > arbol.valor:
return Nodo(arbol.valor, arbol.izquierda, insertarValor(arbol.derecha, valor))
else:
return Nodo(arbol.valor, insertarValor(arbol.izquierda, valor), arbol.derecha)
def insertarLista(arbol, lista):
if (lista == []):
return arbol
elif (lista [1:] == []):
return insertarValor(arbol, lista[0])
else:
return insertarLista(insertarValor(arbol, lista[0]), lista[1:])
print(aLista(insertarLista(Nodo(25, Nodo(18, Nodo(10), Nodo(20))), [11, 45,49,51])))
|
f77204c6ef78db55a1496586055ed0e62322724b | AnhTuan-AiT/CBIR | /v2/FeatureDescriptor.py | 2,530 | 3.578125 | 4 | """
Step1: define feature descriptor
1. convert to HSV and initialize features to quantify and represent the image
2. split by corners and elliptical mask
3. construct feature list by looping through corners and extending with center
"""
import numpy as np
# extract 3D HSV color histogram from images
from cv2 import cv2
class FeatureDescriptor:
def __init__(self, bins):
# store # of bins for histogram
self.bins = bins
# convert RGB to HSV and
# initialize features to quantify and represent the image
def describe(self, image):
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
features = []
# grab dimensions and computer center of image
# from beginning 0 to end-1 = 1, i.e. shape[0] & shape[1]
(h, w) = image.shape[:2]
(cx, cy) = (int(w * 0.5), int(h * 0.5))
# divide image into top-left, top-right, bottom-right, bottom-left corner segments as mask
segments = [(0, cx, 0, cy), (0, cx, cy, h), (cx, w, cy, h), (cx, w, 0, cy)]
# construct an elliptical mask representing the center of the image
(axesX, axesY) = (int(w * 0.75 / 2), int(h * 0.75 / 2))
ellipse_mask = np.zeros(image.shape[:2], dtype="uint8")
cv2.ellipse(ellipse_mask, (cx, cy), (axesX, axesY), 0, 0, 360, 255, -1)
# loop over mask corners
for seg in segments:
# construct mask for each corner by np.zeros()
corner_mask = np.zeros(image.shape[:2], dtype='uint8')
# draw rectangle mask on corner_mask object
corner_mask[seg[0]:seg[1], seg[2]:seg[3]] = 255
corner_mask = cv2.subtract(corner_mask, ellipse_mask)
# extract hsv histogram from segment of image with mask
hist = self.histogram(image, corner_mask)
# update feature vector
features.extend(hist)
# extract hsv histogram from ellipse with mask
hist_ellipse = self.histogram(image, ellipse_mask)
features.extend(hist_ellipse)
return features
# Calculate the histogram of the masked region of the image
def histogram(self, image, mask):
# use number of bins per channel
# Hue is an angle, but 0-360 is mapped to 0-180 interval in order to fit in a byte of memory
hist = cv2.calcHist([image], [0, 1, 2], mask, self.bins, [0, 180, 0, 256, 0, 256])
# normalize histogram to obtain scale invariance
hist = cv2.normalize(hist, hist).flatten()
return hist
|
98c88bdf948e6fd8a64c0f1db5b5f7f1c00925fd | AV272/Python | /Tasks/bank.py | 473 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 17:14:22 2020
@author: alex
Task: function takes two arguments - amount of money and time, and returns
two values - full amount of money on account and sum of percent (10% for year).
"""
def bank(money,years):
x=0;
x = money
for i in range(years):
x = x + x*0.1
xx = x - money
print('Full amount of money = ' + str(x))
print('Percent amount = ' + str(xx))
|
f669906e38df06b99068f931cbeac8063fbf15b0 | DanielSBaumann/dias.de.vida | /maisDias.py | 2,919 | 3.8125 | 4 | from datetime import datetime
#definindo datas com int
print('Este programa calcula os dias de vida de uma pessoa')
print()
dia=input('Digite data de nascimento : \ndd/mm/aaaa : ')
vetor_dia=dia.split('/')
data_hoje=datetime.today()
#primeiro calculo qtd de dias pela diferença de anos
dias_anos=(int(data_hoje.year)-int(vetor_dia[2])-1)*365
#somando dias para anos bissextos
count=0
for i in range(int(vetor_dia[2]),int(data_hoje.year)):
if i%4==0:
#print(i)
count+=1
#print(dias_anos)
dias_anos+=count
#print(dias_anos)
count=0
#definindo qtd dias mes nasc
dias_mes_nasc=0
if int(vetor_dia[1])==1 or int(vetor_dia[1])==3 or int(vetor_dia[1])==5 or int(vetor_dia[1])==7 or int(vetor_dia[1])==8 or int(vetor_dia[1])==10 or int(vetor_dia[1])==12 :
dias_mes_nasc=31-int(vetor_dia[0])+1
elif int(vetor_dia[1])==4 or int(vetor_dia[1])==6 or int(vetor_dia[1])==9 or int(vetor_dia[1])==11 :
dias_mes_nasc=30-int(vetor_dia[0])+1
else:
if int(vetor_dia[2])%4==0:
dias_mes_nasc=29-int(vetor_dia[0])+1
else:
dias_mes_nasc=28-int(vetor_dia[0])+1
#calculando dias por meses ano nascimento
dias=0
for i in range(int(vetor_dia[1])+1,13):
if i==1 or i==3 or i==5 or i==7 or i==8 or i==10 or i==12 :
dias+=31
#print(31)
elif i==4 or i==6 or i==9 or i==11 :
dias+=30
#print(30)
else:
if int(vetor_dia[2])%4==0:
dias+=29
#print(29)
else:
dias+=28
#calculando dias corridos do ano atual
maisDias=0
for i in range(1,int(data_hoje.month)):
if i==1 or i==3 or i==5 or i==7 or i==8 or i==10 or i==12 :
maisDias+=31
#print(31)
elif i==4 or i==6 or i==9 or i==11 :
maisDias+=30
#print(30)
else:
if int(data_hoje.year)%4==0:
maisDias+=29
#print(29)
else:
maisDias+=28
#qtd de dias de vida é a soma dos resultados de :
#dias_anos - qtd de dias entre ano Nasc e ano At
#dias_mes_nasc - qtd de dias vividos no mes de nascimento
#dias - qtd de dias somando qtd de meses vividos no ano de nascimento
#maisDias - dias vividos nos meses do ano At
#diaAt - dias do mes corrente
dias_de_vida = dias_anos + dias_mes_nasc + dias + maisDias + int(data_hoje.day)
#definindo dias até o aniversario
niver=366-(maisDias+int(data_hoje.day))-(dias+dias_mes_nasc)
if int(data_hoje.month)<3 and int(data_hoje.day)<29 and int(data_hoje.year)%4==0:
niver+=1
print()
print('Vc tem '+str(dias_de_vida)+' dias de vida!!')
#deifindo e printando horas vividas
print('Vc viveu '+str(dias_de_vida*24)+' horas ')
#definindo e printando minutos vividos
print('E '+str((dias_de_vida*24)*60)+' minutos')
print('Faltam '+str(niver)+' dias para seu niver')
print('Fim do programa')
print() |
835441961131299bd6a9fc6b34175a3c2734a2d6 | Environmental-Informatics/06-graphing-data-with-python-thejibin | /program-06.py | 2,641 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on 2020-02-28
by Jibin Joseph -joseph57
Assignment 06 - Graphing Data with Python
Revision 03-2020-04-14
Modified to add comments
"""
## Import the required packages
import numpy as np
import matplotlib.pyplot as plt
import sys
## Check the command lines options before accepting
## Check for python script file name, input file and output file name
if len(sys.argv)!=3:
print("Requires the format python <py_program.py> <input_file> <output_file>")
## Read the arguments from the command line and use them as i/o filename
input_filename=sys.argv[1]
output_filename=sys.argv[2]
## Open the file (using genfromtxt()) and use header to define the array names
data_graph=np.genfromtxt(input_filename,
dtype=['int','float','float','float','float','float','float'],
names=True,delimiter='\t')
plt.figure(1,figsize=(8.27,11.69)) ## Create an empty figure numbered 1 with A4 pagesize
## Create the first subplot LINE PLOT
plt.subplot(311) #or (3,1,1)
plt.plot(data_graph['Year'],data_graph['Mean'],'k',label="Mean Streamflow")
plt.plot(data_graph['Year'],data_graph['Max'],'r',label="Max Streamflow")
plt.plot(data_graph['Year'],data_graph['Min'],'b',label="Min Streamflow")
plt.xlabel('Year',fontsize=7)
plt.ylabel("Streamflow ("+r"$ft^3/s$"+" or cfs)",fontsize=7)#my first trial to use latex expression in python
plt.title("Line Plot showing Mean, Maximum, Minimum Streamflow",fontsize=7)
plt.legend(loc='upper left',frameon=True,fontsize=5)
##As y values are high, it offsets the y label towards left, so work-around
plt.ticklabel_format(style='sci',axis='y',scilimits=(1,4))
plt.ylim(data_graph['Min'].min(),1.1*data_graph['Max'].max())
## Create the second subplot SCATTER PLOT
plt.subplot(312) #or (3,1,2)
plt.scatter(data_graph['Year'],data_graph['Tqmean']*100,color='m',marker='*',label="Tqmean")
plt.xlabel('Year',fontsize=7)
plt.ylabel("Tqmean (%)",fontsize=7)
plt.title("Scatter Plot showing Annual Values of Tqmean",fontsize=7)
plt.legend(loc='upper left',frameon=True,fontsize=5)
## Create the third subplot BAR PLOT
plt.subplot(313) #or (3,1,3)
plt.bar(data_graph['Year'],data_graph['RBindex'],facecolor='g',label="RBindex")
plt.xlabel('Year',fontsize=7)
plt.ylabel("RBindex (ratio)",fontsize=7)
plt.title("Bar Plot showing RBindex",fontsize=7)
plt.legend(loc='upper left',frameon=True,fontsize=5)
plt.suptitle("PLOTS FOR INPUT FILE: "+sys.argv[1],fontsize=10)
## Tweak the spacing between subplots to prevent labels from overlapping
plt.subplots_adjust(hspace=1)
## Save the plot as pdf
plt.savefig(output_filename+".pdf")
plt.close(1) |
d3a209eaeb1fc72004abc7feb5bad25260c802b1 | OsmanC4hit/PythonNotlarm | /23-hesapmakinesi.py | 920 | 3.875 | 4 | import math
def new_function():
key = 1
while key == 1:
soru = input("Yapmak istediğiniz işlemin numarasını girin 1 giriş (Çıkmak için q): ")
if soru == "q":
break
elif soru == "1":
sayı1 = int(input("bir sayı giriniz"))
sayı2 = int(input("ikinci sayıyı giriniz"))
secim = input("hangi işlemi yapmak istiyorsunuz + * - / % ")
if secim == "+":
toplam = sayı1 + sayı2
print(toplam)
elif secim == "-":
cıkarma = sayı1 - sayı2
print(cıkarma)
elif secim == "/":
bölmee = sayı1 / sayı2
print(bölmee)
elif secim == "*":
carpma = sayı1 * sayı2
print(carpma)
else:
print("yanlış değer girdiniz")
new_function()
|
17fb6c5a7cefc0187923a7ab341e73eaae9f801e | syurskyi/Python_Topics | /020_sequences/examples/ITVDN Python Essential 2016/15-list_shallow_copy_bug.py | 2,764 | 4.25 | 4 | # Операция умножения часто используется со списками
# для инициализации списка заданным количеством одинаковых элементов
some_list = [0] * 10
print(some_list)
print()
# Операция * конкатенирует неполные копии списков, то есть объекты
# внутри копий не копируются, а сохраняются ссылки на них.
# Об этом следует помнить, когда в списке находятся изменяемые
# объекты, например, другие списки.
# Начинающие программисты на Python часто допускают подобную
# ошибку, когда хотят инициализировать двумерную матрицу при
# помощи списков списков.
def print_matrix(matrix):
"""Функция вывода матрицы"""
for row in matrix:
print(' '.join(str(element) for element in row))
# Создание матрицы 5x5 (неправильно)
matrix_done_wrong = [[0] * 5] * 5
# Пока что выводится правильно
print_matrix(matrix_done_wrong)
print()
# Изменение одного элемента
matrix_done_wrong[1][3] = 8
# Изменились соответствующие элементы во всех строках
print_matrix(matrix_done_wrong)
print()
# Это произошло из-за того, что список хранит в себе ссылки
# на объекты. Второй оператор * создал список из ссылок на
# один и тот же список. Правильным было бы использовать
# функцию deepcopy модуля copy (что в данном случае было бы
# неудобно и породило бы много кода, но было бы удобно,
# например, для создания копии уже созданной матрицы) или,
# что является лучшим решением в данном случае, создавать
# каждую строку матрицы отдельно. Проще и лаконичнее всего
# это сделать при помощи спискового включения.
# Создание матрицы 5x5 (правильно)
matrix_done_right = [[0] * 5 for _ in range(5)]
# Вывод
print_matrix(matrix_done_right)
print()
# Изменение одного элемента
matrix_done_right[1][3] = 8
# Только один элемент и изменился
print_matrix(matrix_done_right)
|
2a2d85801b28743256fbb621c87d76cf30e179e3 | PARKGOER/Python | /200717/200717_08.py | 342 | 3.640625 | 4 | class MyError(Exception) :
def __str__(self) :
return "허용되지 않는 별명입니다"
def say_nick(nick) :
if nick == "천사" :
print(nick)
elif nick == "바보" :
raise MyError ()
else :
pass
try :
say_nick("천사")
say_nick("바보")
except MyError as e :
print(e)
|
5d37e73b9a293bf1a8d96ba745aa2a7c43189543 | santospat-ti/Python_Ex.EstruturadeRepeticao | /ex33.py | 735 | 3.890625 | 4 | """O Departamento Estadual de Meteorologia lhe contratou para desenvolver um programa que leia as um conjunto
indeterminado de temperaturas, e informe ao final a menor e a maior temperaturas informadas, bem como a média
das temperaturas."""
import time
quant_temp = int(input("Quantidade de temperaturas que irá digitar: "))
temperaturas = []
n_temperatura = 1
for t in range(quant_temp):
valor_temp = float(input('Digite os graus: '))
temperaturas.append(valor_temp)
n_temperatura += 1
m = round(sum(temperaturas) / len(temperaturas))
print(f'A menor temperatura informada é {min(temperaturas)}')
print(f'A maior temperatura informada é {max(temperaturas)}.')
print(f'A média de graus é {m}') |
13f86b9e68db90e52da2354ec91877b5330686d2 | Maxim-Kovalenko/my-lyceum-python-code | /word_counter.py | 372 | 3.984375 | 4 | string = str(input("Input sentence: "))
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
n = 0
for text in counts:
n = n + 1
return n
print("There are", (word_count(string)), "words in this string:", string)
|
a47b01e60842feb7a91432fa219eafa3e2827fee | Androspy/myfirstprogram | /licuado.py | 139 | 3.859375 | 4 |
dato = int(input("dime tu edad: "))
if dato >= 18:
print("eres mayor de edad")
else:
print("jajaja que estupidin, largo de aqui") |
f02c346ce2a3c126d68c82b716c8076327432f16 | MLoopz/CodeWars | /baker/baker.py | 687 | 3.6875 | 4 | def cakes(recipe, available):
spent = {}
for demanded in recipe:
if demanded in available:
qty = calculate_quantities(recipe[demanded], available[demanded])
if qty < 1:
return 0
else:
spent[demanded] = qty
else: return 0
return math.floor(min(spent.values()))
def calculate_quantities(demanded, current):
return current / demanded
recipe = {'flour': 41, 'cocoa': 28, 'pears': 4}
available = {'oil': 7592, 'sugar': 9631, 'pears': 2392, 'eggs': 8115, 'flour': 3222, 'cocoa': 5021, 'apples': 5995, 'cream': 8527, 'crumbles': 9983, 'chocolate': 2792}
print(cakes(recipe, available)) |
8de946ba202b59ef0592af9005e24958f48ec184 | sivanesanceg/music_recommender | /server_recom/queue_dll.py | 884 | 3.828125 | 4 | class Node():
def __init__(self, path, hp, index):
self.prev = None
self.data = [path,hp,index]
self.next = None
class Queue():
def __init__(self):
self.top = None
self.back = None
def display_top(s):
temp = s.top
a = ''
while temp != None:
print(temp.data)
temp = temp.prev
def display_back(s):
temp = s.back
a = ''
while temp != None:
print(temp.data)
temp = temp.next
def is_empty(s):
if s.top == None:
return 1
return 0
def push(s, n):
if is_empty(s):
s.top = n
s.back = n
else:
s.back.prev = n
temp = s.back
s.back = n
s.back.next = temp
def pop(s):
if is_empty(s):
return 0
else:
x = s.top.data
if s.top.prev == None:
s.top = None
s.back = None
else:
temp = s.top.prev
temp.next = None
#del s.top
s.top = temp
return x
|
1fbf9652e1838c765d12c6e490e579571e01125d | Gonzalowc/HLC_2122 | /Tema1/Ejercicio7.py | 135 | 3.953125 | 4 | nombres = input("Introduce 3 nombres: ")
nombres_separados = nombres.split(" ")
for nombre in nombres_separados:
print(nombre)
|
9e1b8c1cd8966ca6d99c6f1552242e776f25eef3 | Jiezhi/myleetcode | /src/540-SingleElementinaSortedArray.py | 1,473 | 3.65625 | 4 | #!/usr/bin/env python
"""
CREATED AT: 2021/11/20
Des:
https://leetcode.com/problems/single-element-in-a-sorted-array/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Medium
Tag: BinarySearch
See:
"""
from typing import List
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
"""
Runtime: 117 ms, faster than 10.42%
Memory Usage: 16.3 MB, less than 94.67%
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^5
:param nums:
:return:
"""
l, h = 0, len(nums) - 1
while l < h:
mid = l + (h - l) // 2
if nums[mid] != nums[mid - 1] and nums[mid] != nums[mid + 1]:
return nums[mid]
if (nums[mid] == nums[mid - 1] and mid % 2 == 1) or (nums[mid] == nums[mid + 1] and mid % 2 == 0):
l = mid + 1
else:
h = mid - 1
return nums[l]
def test():
assert Solution().singleNonDuplicate(nums=[1]) == 1
assert Solution().singleNonDuplicate(nums=[1, 1, 2, 2, 3]) == 3
assert Solution().singleNonDuplicate(nums=[1, 1, 2, 2, 4, 4, 5, 5, 9]) == 9
assert Solution().singleNonDuplicate(nums=[2, 2, 3]) == 3
assert Solution().singleNonDuplicate(nums=[1, 2, 2]) == 1
assert Solution().singleNonDuplicate(nums=[1, 1, 2, 3, 3, 4, 4, 8, 8]) == 2
assert Solution().singleNonDuplicate(nums=[3, 3, 7, 7, 10, 11, 11]) == 10
if __name__ == '__main__':
test()
|
8609c58ab9677b6af41c50f7191be745e69f7e7a | littlepriyank/guvi_rep | /bs1-3.py | 255 | 4.15625 | 4 | r = input()
if((r>='a' and r<='z')or(r>='A' and r<='Z')):
if(r=='a' or r== 'A' or r == 'e' or r == 'E' or r=='i' or r =='I' or r=='o' or r =='O' or r == 'U' or r =='u'):
print("Vowel")
else:
print("Consonant")
else:
print("Invalid Input")
|
9fcde3cb681fc2891b3257d53f07a842ebd7e071 | lightmen/leetcode | /python/tree/recover-binary-search-tree.py | 701 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inOrder(self,root):
if root is None:
return
self.inOrder(root.left)
if self.prev and self.prev.val > root.val:
self.t2 = root
if self.t1 is None:
self.t1 = self.prev
self.prev = root;
self.inOrder(root.right)
def recoverTree(self, root):
self.prev = None
self.t1 = None
self.t2 = None
self.inOrder(root)
self.t1.val, self.t2.val = self.t2.val,self.t1.val
|
86d9015447f38166960480cac9ec770098da511f | lukaskellerstein/PythonSamples | /2_OOP/1_inheritance_polymorphism.py | 1,190 | 4.3125 | 4 | class Animal(object):
def __init__(self):
print("Animal created")
def whoami():
print("I am an animal")
def eat():
print("i am eating")
# abstract method
def speak():
raise NotImplementedError("Subclass must implement this abstract method")
# Inheritance
class Dog(Animal):
def __init__(self):
# call super class
Animal.__init__(self)
print("Dog created")
# Polymorphysm - override
def whoami():
print("I am a dog")
def speak():
print("BARK BARK")
def eat():
print("dog is eating")
# Polymorphysm - overload - PYTHON DOESN'T HAVE A METHOD OVERLOADING
# def eat(text):
# print(f"dog eating {text}")
# Inheritance
class Cat(Animal):
def __init__(self):
# call super class
Animal.__init__(self)
print("Cat created")
# Polymorphysm - override
def whoami():
print("I am a cat")
def speak():
print("MEOW MEOW")
def eat():
print("cat is eating")
# Polymorphysm - overload - PYTHON DOESN'T HAVE A METHOD OVERLOADING
# def eat(text):
# print(f"dog eating {text}")
|
f4964e436eef2fae9b19f9d143ac2408048bf057 | PRAVEEN100999/praveen-code-all | /data.py | 304 | 3.9375 | 4 | def square(a):
return a**2
l = [1,2,3,4]
def my(func , p):
new= []
for item in p :
new.append(func(item))
return new
print(my(square,l))
print(my(lambda a :a**2,l))
#list comprehension
def my2(func,l):
return [func(item) for item in l]
print(my2(lambda a:a**3,l))
|
64fdcc48ea588dc972b89e4ff9b5e26d3163ecd0 | lancelote/advent_of_code | /src/year2020/day01a.py | 646 | 3.59375 | 4 | """2020 - Day 1 Part 1: Report Repair."""
def process_data(data: str) -> list[int]:
return [int(number) for number in data.strip().split("\n")]
def find_2020_summands(numbers: list[int]) -> tuple[int, int]:
for i in range(len(numbers)):
for j in range(i, len(numbers)):
if numbers[i] + numbers[j] == 2020:
return numbers[i], numbers[j]
raise ValueError("no 2020 summands were found in input")
def solve(task: str) -> int:
"""Find two number which sum is 2020 and multiply them."""
numbers = process_data(task)
first, second = find_2020_summands(numbers)
return first * second
|
c3161404357e29027220d25e97c651277a3cb630 | chenjienan/python-leetcode | /144.binary-tree-preorder-traversal.py | 1,578 | 3.859375 | 4 | #
# @lc app=leetcode id=144 lang=python3
#
# [144] Binary Tree Preorder Traversal
#
# https://leetcode.com/problems/binary-tree-preorder-traversal/description/
#
# algorithms
# Medium (50.40%)
# Total Accepted: 310.4K
# Total Submissions: 615.8K
# Testcase Example: '[1,null,2,3]'
#
# Given a binary tree, return the preorder traversal of its nodes' values.
#
# Example:
#
#
# Input: [1,null,2,3]
# 1
# \
# 2
# /
# 3
#
# Output: [1,2,3]
#
#
# Follow up: Recursive solution is trivial, could you do it iteratively?
#
#
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode):
# res = []
# self.traverse(root, res)
# return res
# TODO:Iteration
# time: O(n)
# space: O(h)
if not root: return []
s = [root] # put root to init the stack
res = []
while s:
node = s.pop()
if node:
# root -> left -> right
res.append(node.val)
s.append(node.right) # use stack, so put right node first
s.append(node.left) # then left node
return res
# TODO: recursion:
# time: O(n)
# space: O(1)
def traverse(self, node, res):
if not node: return
res.append(node.val)
self.traverse(node.left, res)
self.traverse(node.right, res)
|
5b8b4de659c0a5bec9dc7cb13ddd0a1b8a416f18 | salimuddin87/Python_Program | /algorithm/sort_quick.py | 1,411 | 4.28125 | 4 | """
Quick sort is in-place sorting and divide and conquer algorithm.
best case: O(nlogn)
worst case: O(n^2) if we pick greatest/smallest element as pivot
There are different way to pick quick sort pivot element:
1. Pick first/last element as pivot
2. Pick random element as pivot
3. Pick median as pivot
"""
import math
def partition(num_list, first, last):
pivot = math.floor((first + last) / 2)
pivot_value = num_list[pivot]
print("pivot item :", pivot_value)
i = first
j = last
while i < j:
if num_list[i] < pivot_value:
i += 1
if num_list[j] > pivot_value:
j -= 1
# swap i and j position item
if i != pivot and j != pivot:
num_list[i], num_list[j] = num_list[j], num_list[i]
i += 1
j -= 1
if i == pivot:
i += 1
if j == pivot:
j -= 1
# i == j after coming out of loop, swap with pivot value
num_list[i], num_list[pivot] = num_list[pivot], num_list[i]
print("List after partition for pivot {} is : {}".format(num_list[j], num_list))
return i
def quick_sort(num_list, first, last):
if first < last:
q = partition(num_list, first, last)
quick_sort(num_list, first, q-1)
quick_sort(num_list, q+1, last)
return num_list
if __name__ == '__main__':
print(quick_sort([4,9,2,1,6], 0, 4))
|
abe40e802054502e41f92dacf3d960eb4b9fb13e | suyundukov/LIFAP1 | /TD/TD6/Code/Python/4.py | 381 | 3.609375 | 4 | #!/usr/bin/python
# Retourner l'indice de la plus petite valeur contenue dans le tableau
def recherche_min(tab):
val_min = tab[0]
for i in range(len(tab)):
if tab[i] < val_min:
val_min = tab[i]
return tab.index(val_min)
tab = [5, 18.5, 13.2, 8.75, 2, 15, 13.5, 6, 17]
# val_min = tab.index(min(tab)) # I ❤ Python
print(recherche_min(tab))
|
8212aa73f22b787613e7620025a5ca5370a21a0b | PriyankaMali-13/Python_Learning | /courseera_1_assignment/ex2.py | 391 | 3.515625 | 4 | #try-expect
hrs = input("Enter Hours:")
rate = input("Enter rate:")
try:
h =float(hrs)
r = float(rate)
except:
print("Error, Please put valid input")
#if err do not continue and run further stmt ->
# this will nt give u traceback err, try running without quit()
quit()
if h>40:
reg = h*r
p = (h-40.0)*(r*0.5)
res = reg+p
else:
res = h*r
print(res)
|
3d006116243f289ff7dc62e8732f4375c5775b34 | Chatwaroon/Portfolio | /workshop/สร้างระบบพยากรณ์อากาศด้วย Yahoo API/WeatherForcast.py | 642 | 3.703125 | 4 | import yweather
from weather import Weather,Unit
client=yweather.Client()
name=input("Input Your City :")
dataid=client.fetch_woeid(name+",Thailand")
weather=Weather(unit=Unit.CELSIUS)
lookup=weather.lookup(dataid)
condition=lookup.condition
location=weather.lookup_by_location(name+",Thailand")
forcasts=location.forecast
for result in forcasts:
print("สภาพอากาศ : "+result.text)
print("วันที่ : "+result.date)
print("อุณหภูมิสูงสุด : "+result.high)
print("อุณหภูมิต่ำสุด : "+result.low)
print("-------------------")
|
bb037d511e22c99d7339e2eec9552c24f99774e5 | raghav1674/graph-Algos-In-Python | /Recursion/03/permutations.py | 681 | 3.671875 | 4 | # O(n*n!)
def permutation_helper(input_str, count, output, out, level):
if level == len(input_str):
output.append(out)
else:
for i in range(len(input_str)):
if count[i] == 1:
count[i] = 0
level += 1
permutation_helper(input_str, count, output,
out+input_str[i], level)
count[i] = 1
level -= 1
def permutation(string):
count = [1]*len(string)
output_arr = []
output_string = ""
level = 0
permutation_helper(string, count, output_arr, output_string, level)
return output_arr
print(permutation("ABC"))
|
008f8f90fd00a6f34be05bcf3f9b3eb5b6837358 | PatZarama/appTest7 | /conditional.py | 696 | 4 | 4 | '''
this script let you apply basic math operations as:
add, mult, divide, sustract
'''
#libraries####################################
import os
##############################################
#function#####################################
def calc(x, y, z):
if z == 1 :
Ans = x + y
elif z == 2 :
Ans = x - y
elif z == 3 :
Ans = x * y
else :
Ans = x / y
return Ans
#Main#########################################
ni = int(input("First number: "))
n2 = int(input("Second number: "))
print(":::MENU:::)
print("[1]. Add")
print("[2]. Subs")
print("[3]. Mult")
print("[4]. Div")
opt = int(input("press an option: "))
print("The answer is: ",calc(n1,n2,opt)
|
d26607468c4d818b12eddbc971f9a09624e0b45e | chibitofu/Coding-Challenges | /leap_year.py | 536 | 4.15625 | 4 | def leap_year(year):
"""Take in a year and determines if it's a leap year"""
## Is the year evenly divisible by 4
if year % 4 is 0:
## Is not evenly divisible by 100
## Unless it's also evenly divisible by 400
if year % 100 is 0 and year % 400 is 0:
return True
elif year % 100 is not 0:
return True
else:
return False
else:
return False
print(leap_year(1997))
print(leap_year(1996))
print(leap_year(1900))
print(leap_year(2000)) |
384d6b9cfd7ed5a68b86f9f9488c393eb845c385 | KingKerr/Interview-Prep | /Arrays/hasSingleCycle.py | 1,030 | 4.09375 | 4 | """
Single Cycle Check.. Given an array of integers that represents a jump of it's value in the array. If your integer is 2, then you
have to jump 2 indices forward. If the integer is -5, then you have to jump 5 indices backwards. If your jump exceeds the bounds of the array,
it wraps over.
Examples:
[2, 3, 1, -4, -4, 2] will return True
[1, -1, 1, -1] will return False.
"""
def hasSingleCycle(array):
numOfElementsVisited = 0
currentIdx = 0
while numOfElementsVisited < len(array):
if numOfElementsVisited > 0 and currentIdx == 0:
return False
numOfElementsVisited += 1
currentIdx = getNextIdx(currentIdx, array)
return currentIdx == 0
def getNextIdx(currentIdx, array):
jump = array[currentIdx]
# We're dividing by length of array to account for large integers or negative ones
nextIdx = (jump + currentIdx) % len(array)
return nextIdx if nextIdx >= 0 else nextIdx + len(array)
"""
Runtime: O(N) in which N is length of the array
Space: 0(1)
"""
|
bb4953dac42b03c09b89a0213afe212e239141ce | hebertmello/pythonWhizlabs | /estudo_for.py | 188 | 3.75 | 4 | # For
# -------------------------------------
l = [1, 2, 3, 4, 5]
sum = 0
for i in l:
sum = sum + i
print(sum)
for i in l:
print(i)
else:
print('fim do loop')
|
4827c1d8e619286abf5a85f72698785f2a0de28d | frodosamoa/cmsi386 | /homework-1/pythonwarmup.py | 1,342 | 3.796875 | 4 | import random
def change(cents):
"""Returns a tuple containing the smallest number of U.S. quarters,
dimes, nickels, and pennies that equal the passed amount of cents."""
if cents < 0:
raise ValueError('Amount of cents must be 0 or greater.')
quarters, remaining = divmod(cents, 25)
dimes, remaining = divmod(remaining, 10)
nickels, pennies = divmod(remaining, 5)
return (quarters, dimes, nickels, pennies)
def strip_vowels(string):
"""Returns the passed string with all ASCII vowels removed."""
return ''.join([char for char in string if char.lower() not in 'aeiou'])
def scramble (string):
"""Returns the passed string randomly permuted."""
return ''.join(random.sample(string, len(string)))
def powers_of_two(n):
"""Generator of powers of two up to and including the passed limit."""
num = 1
while num <= n:
yield num
num *= 2
def powers(base, n):
"Generator of powers of an arbitrary base up to and including the passed limit."
num = 1
while num <= n:
yield num
num *= base
def interleave(l1, l2):
"""Returns the two passed lists interleaved."""
l3 = [value for pair in zip(l1, l2) for value in pair]
if len(l1) != len(l2):
l3.extend(l1[len(l2):] if len(l1) > len(l2) else l2[len(l1):])
return l3
def stutter (list):
"""Returns the list with each item doubled up."""
return interleave(list, list) |
2ec83b0fdf784b2072c71b69667eda1239fc62c1 | morganmann4/cse210-tc06 | /mastermind/game/director.py | 3,503 | 3.71875 | 4 | from game.code import Code
from game.check import Check
from game.guess import Guess
from game.player import Player
from game.end_game import End_game
guess = Guess()
check = Check()
code = Code()
end_game = End_game()
class Director:
"""A code template for a person who directs the game. The responsibility of
this class of objects is to control the sequence of play.
Stereotype:
Controller
Attributes:
keep_playing (boolean): Whether or not the game can continue.
"""
def __init__(self):
"""The class constructor.
Args:
self (Director): an instance of Director.
"""
self.code = ""
self.PLayer1 = ""
self.PLayer2 = ""
self.turns = 0
def start_game(self):
"""Called from the main function to start the game. Gets the 4 digit code from Code().
Gets 2 players by calling the get player function. Gets the first guess from player 1.
Calls the function to turn the guess and the code into lists. Checks to see what numbers
if any are right.
Args:
self (Director): an instance of Director.
"""
self.code = code.get_random_num()
self.Player1 = self.get_player(1)
self.Player2 = self.get_player(2)
attempt = self.Player1.make_guess()
guess.guess_lists(attempt, self.code)
right_answer_list = guess.return_answer()
num_guessed_list = guess.return_player_guess()
check.check(num_guessed_list, right_answer_list)
attempt = self.Player2.make_guess()
guess.guess_lists(attempt, self.code)
right_answer_list = guess.return_answer()
num_guessed_list = guess.return_player_guess()
output = check.check(num_guessed_list, right_answer_list)
play = end_game.end_game(output)
if play == True:
self.keep_playing()
def get_player(self, num):
"""Gets the inputs at the beginning for each player on what the number is.
Args:
self (Director): An instance of Director.
num (Guess): An instance of Guess.
"""
name = input(f"What is the name for player number {num}? ")
player = Player(name)
return player
def keep_playing(self):
"""Outputs that 2 players make a guess for the four digit number. if the number is right, they win, but if it is
wrong they keep playing
Args:
self (Director): An instance of Director.
"""
if self.turns % 2 == 0:
attempt = self.Player1.make_guess()
guess.guess_lists(attempt, self.code)
right_answer_list = guess.return_answer()
num_guessed_list = guess.return_player_guess()
output = check.check(num_guessed_list, right_answer_list)
play = end_game.end_game(output)
self.turns += 1
if play == True:
self.keep_playing()
else:
attempt = self.Player2.make_guess()
guess.guess_lists(attempt, self.code)
right_answer_list = guess.return_answer()
num_guessed_list = guess.return_player_guess()
output = check.check(num_guessed_list, right_answer_list)
play = end_game.end_game(output)
self.turns += 1
if play == True:
self.keep_playing()
|
c8b208fc36d19970e637fd628225c8faacd49ad3 | emurph1/unit4 | /localDemo.py | 281 | 3.515625 | 4 | #Emily Murphy
#2017-10-23
#localDemo.py - learn how to us local variables
#local variables are ones that are declared in the function
def f():
x = 77 #x is a local variable
y = 10 #y is a local variable
x = 5
f() #x does not change
print(x)
print(y) #this will cause an error |
04e9218dfb3b5ae86e5808396f92cad83567f34e | vwinkler/LDE-Solver | /DiophanticSum.py | 1,466 | 3.609375 | 4 | class DiophanticSum:
def __init__(self, coefficients, constant):
assert all([type(c) is int for c in coefficients.values()])
assert type(constant) is int
self.coefficients = coefficients
self.constant = constant
def getConstant(self):
return self.constant
def getCoefficients(self):
return self.coefficients
def multiplyWith(self, value):
coefficients = {name : value*coeff for name, coeff in self.coefficients.items()}
constant = value * self.constant
return DiophanticSum(coefficients, constant)
def evaluateForVariableAssignment(self, assignment):
result = self.constant
for name in self.coefficients:
coeff = self.coefficients[name]
valueOfVariable = assignment[name]
result = result + coeff*valueOfVariable
return result
def __eq__(self, other):
if not isinstance(other, DiophanticSum):
return NotImplemented
return self.coefficients == other.coefficients and self.constant == other.constant
def __str__(self):
return self.__repr__()
def __repr__(self):
terms = []
for name in self.coefficients:
terms.append(str(self.coefficients[name]) + "*" + str(name))
result = str(self.constant)
if len(self.coefficients) > 0:
result = " + ".join(terms) + " + " + result
return result
|
bc076ad529c44038294dbc9d8e678dec929cdab7 | liuyazhou0917/hello- | /exercise04.py | 378 | 3.703125 | 4 | """
创建Python文件exercise04.py
结果:终端中显示 请输入武器名称: 用户在控制台中输入了名称
终端中显示 请输入攻击力: 用户在控制台中输入了攻击力
终端中显示 xx的攻击力是xx
"""
armament = input("请输入武器名称:")
att = input("请输入攻击力:")
print(armament + "的攻击力是" + att)
|
636ab3e3567008ed4b6840ed8c6f005f34ccd6f0 | devile-xiang/-_python_spider | /LintCode_test/dome4-统计出现次数.py | 677 | 3.515625 | 4 | #encoding:utf-8
def main(n,k):
print("N的值是%s"%n)
narray = []
for i in range(0, n+1):
narray.append(i)
print("要统计的次数是:%d"%n)
print(narray)
global a
a=0
if type(narray)==int:
print("只有一个数")
for j in str(narray):
print(j)
if j == str(k):
a = a + 1
else:
#多个数
for i in narray:
for j in str(i):
print(j)
if j==str(k):
a=a+1
if a==0:
a=a+1
print("%d总共出现了%d"%(k,a))
if __name__ == '__main__':
n=12
k=1
main(n ,k)
|
462827628f02f1f2e82f6c9899f521a6c249dda6 | serinamarie/CS-Hash-Tables-Sprint | /hashtable/hashtable.py | 9,122 | 3.9375 | 4 | class HashTableEntry:
"""
Linked List hash table key/value pair
"""
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
# Hash table can't have fewer than this many slots
MIN_CAPACITY = 8
class HashTable:
"""
A hash table that with `capacity` buckets
that accepts string keys
"""
key_value_pair_counts = 0
def __init__(self, capacity):
self.capacity = MIN_CAPACITY
self.array_buckets = [None for i in range(capacity)]
def get_num_slots(self):
"""
Return the length of the list you're using to hold the hash
table data. (Not the number of items stored in the hash table,
but the number of slots in the main list.)
One of the tests relies on this.
"""
# return the length of the array
return len(self.array_buckets)
def get_load_factor(self):
"""
Return the load factor for this hash table.
"""
# return load factor
return HashTable.key_value_pair_counts / self.get_num_slots()
def djb2(self, key):
"""
DJB2 hash, 32-bit
"""
hash = 5381
byte_array = key.encode('utf-8')
for byte in byte_array:
hash = ((hash << 5) + hash) + byte
return hash
def hash_index(self, key):
"""
Take an arbitrary key and return a valid integer index
between within the storage capacity of the hash table.
"""
return self.djb2(key) % self.capacity
def put(self, key, value):
"""
Store the value with the given key.
Hash collisions should be handled with Linked List Chaining.
"""
# check if load factor would become > 0.7 if we add a new entry
if (HashTable.key_value_pair_counts + 1) / self.get_num_slots() > 0.7:
# if it would, double size and rehash
self.resize(2*self.capacity)
# increment # of pairs in table
HashTable.key_value_pair_counts += 1
# mod hash with length of array
index = self.hash_index(key)
# locate the node index
current_node = self.array_buckets[index]
# if there is nothing at that index
if current_node is None:
# add a new entry
self.array_buckets[index] = HashTableEntry(key=key, value=value)
# if there is a key/value at that index
else:
# while there is a key/value at that index and that index doesn't contain the key
while current_node and current_node.key != key:
# set the current node to the last known node
last_node = current_node
# make the next node the current node
current_node = current_node.next
# if input key does not match an existing key
if not current_node:
# once there isn't a current node
# set a pointer from the last known node to the new one created
last_node.next = HashTableEntry(key=key, value=value)
# if input key matches an existing key
elif current_node.key == key:
# overwrite existing key value
current_node.value = value
def delete(self, key):
"""
Remove the value stored with the given key.
Print a warning if the key is not found.
Implement this.
"""
# STRETCH
# if the load factor would become < 0.2 if we delete an entry
if (HashTable.key_value_pair_counts - 1) / self.get_num_slots() < 0.2:
# if our capacity isn't already at minimum
if not self.capacity == MIN_CAPACITY:
# resize to half the capacity
self.resize(int(self.capacity/2))
# mod hash with length of array
index = self.hash_index(key)
# locate the index
current_node = self.array_buckets[index]
# if there is a node at that index
if current_node:
# set the latest node to none (will make sense later in the function)
last_node = None
# while a key/value pair exists
while current_node:
# if the node's key matches input key
if current_node.key == key:
# remove a pair from our k/v pair counter
HashTable.key_value_pair_counts -= 1
# if there is a previous node
if last_node:
# set the current node's 'next' equal to our last node's 'next'
last_node.next = current_node.next
# if this is the first key at that index
else:
# the next node is the first node
self.array_buckets[index] = current_node.next
# go to the next key
last_node = current_node
current_node = current_node.next
# if there is nothing at that index
else:
# no key found
print(f"IndexError: There are no keys at that index")
def get(self, key):
"""
Retrieve the value stored with the given key.
Returns None if the key is not found.
"""
# mod hash with length of array
index = self.hash_index(key)
# locate the index
current_node = self.array_buckets[index]
# if there is nothing at that index
if current_node is None:
# no key found
print(f"KeyError: '{key}' not found in hash table")
# if there is a node at that index
else:
# set the latest node to none (will make sense later in the function)
last_node = None
# while a key/value pair exists and that pair is not our input pair
while current_node and current_node.key != key:
# go to the next key
last_node = current_node
current_node = current_node.next
# if loop stopped because we have no more keys to search through
if not current_node:
# no key found
print(f"KeyError: '{key}' not found in hash table")
# if loop stopped because found key equal to input key!
elif current_node.key == key:
return current_node.value
def resize(self, new_capacity):
"""
Changes the capacity of the hash table and
rehashes all key/value pairs.
Implement this.
"""
# store the existing array
temp = self.array_buckets
# set new capacity
self.capacity = new_capacity
# reset array to empty
self.array_buckets = [None for i in range(self.capacity)]
# reset key value pair counts to 0
HashTable.key_value_pair_counts = 0
# for each index in our temp array
for node in temp:
# while a node exists at that index
while node:
# insert the new node
self.put(node.key, node.value)
# go to the next node
node = node.next
if __name__ == "__main__":
ht = HashTable(8)
ht.put("line_1", "'Twas brillig, and the slithy toves")
ht.put("line_2", "Did gyre and gimble in the wabe:")
ht.put("line_3", "All mimsy were the borogoves,")
ht.put("line_4", "And the mome raths outgrabe.")
ht.put("line_5", '"Beware the Jabberwock, my son!')
ht.put("line_6", "The jaws that bite, the claws that catch!")
ht.put("line_7", "Beware the Jubjub bird, and shun")
ht.put("line_8", 'The frumious Bandersnatch!"')
ht.put("line_9", "He took his vorpal sword in hand;")
ht.put("line_10", "Long time the manxome foe he sought--")
ht.put("line_11", "So rested he by the Tumtum tree")
ht.put("line_12", "And stood awhile in thought.")
print("")
# Test storing beyond capacity (only for module 1 testing)
for i in range(1, 13):
print(ht.get(f"line_{i}"))
print(ht.get(f"line_13"))
# Test resizing
old_capacity = ht.get_num_slots()
# ht.resize(ht.capacity * 2)
new_capacity = ht.get_num_slots()
print(f"\nResized from {old_capacity} to {new_capacity}.\n")
print("Load factor:", ht.get_load_factor())
# Test if data intact after resizing
for i in range(1, 13):
print(ht.get(f"line_{i}"))
# print("")
# ht.delete("line_1")
# ht.delete("line_2")
# ht.delete("line_3")
# ht.delete("line_4")
# ht.delete("line_5")
# ht.delete("line_6")
# ht.delete("line_7")
# ht.delete("line_8")
# ht.delete("line_9")
# ht.delete("line_10")
# ht.delete("line_11")
# ht.delete("line_12")
print("Load factor:", ht.get_load_factor())
print('capacity:', ht.capacity)
print('kvpc:', ht.key_value_pair_counts)
|
263e315573713d6393211784f444559fa4933bf0 | merely-useful/py-rse | /src/package-py/08/bin/check_zipf.py | 358 | 3.5625 | 4 | #!/usr/bin/env python
import sys
import zipfpy.check
USAGE = '''zipf num [num...]: are the given values Zipfy?'''
if __name__ == '__main__':
if len(sys.argv) == 1:
print(USAGE)
else:
values = [int(a) for a in sys.argv[1:]]
result = zipfpy.check.is_zipf(values)
print('{}: {}'.format(result, values))
sys.exit(0)
|
d2267342acdb1f3bae86a9b0f7cb965192c2e0c1 | iverson52000/DataStructure_Algorithm | /LeetCode/0057. Insert Interval.py | 959 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 10:02:49 2019
@author: alberthsu
"""
"""
!57. Insert Interval
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.
"""
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
for i, interval in enumerate(intervals):
if interval[1] < newInterval[0]:
res.append(interval)
elif newInterval[1] < interval[0]:
res.append(newInterval)
return res+intervals[i:] # can return earlier
else: # overlap case
newInterval[0] = min(newInterval[0], interval[0])
newInterval[1] = max(newInterval[1], interval[1])
res.append(newInterval)
return res
|
885c940986da6678fad03f3c8dbd2cb006ea8e36 | Sgggser/python_homework | /lesson_loops.py | 1,604 | 3.96875 | 4 | import random
for i in range (5):
if i % 2 == 0:
print('hello world', i)
else:
print('happy new year', i)
for i in range(20, 10, -2):
print('iteration#:', i)
for _ in range(10):
print('hello world')
print('-----------------------')
for char in "abc":
print(char)
for weekday in ('Mo', 'Tu', 'We', 'Thu', 'Fri', 'Sat', 'Sun'):
print(weekday)
for i in range(2, 101, 2):
print(i)
sum_total = 0
for i in range(1, 101):
sum_total = sum_total + i
print(sum_total)
def sum_of_n(n):
sum_total = 0
for i in range(1, n+1):
sum_total += i
return sum_total
print(sum_of_n(100))
t = 'Вы перешли в режим инкогнито.'
print(len(t.split(' '))-1)
print(t.count(' '))
def find_num_of_uppers(text):
upper_total = 0
for char in text:
if char.isupper():
upper_total += 1
return upper_total
print(find_num_of_uppers(t))
def camelize_me(var_name):
var_name_lst = var_name.split('_')
result = ''
print(var_name_lst)
for part_name in var_name_lst:
#print(part_name, part_name.capitalize())
result += part_name.capitalize()
return result
print(camelize_me('emploee_first_name'))
print(camelize_me('d_ve_venei_cwicwu_v'))
print(camelize_me('em'))
def avr_whatever_of_n(n, lower_bound, upper_bound):
rand_total = 0
for _ in range(n):
rand_num = random.randint(lower_bound, upper_bound)
print(rand_num)
rand_total += rand_num
avr_rand = rand_total / n
return avr_rand
print('%.2f' % avr_whatever_of_n(11, 100, 200)) |
ff522fc326262390ff8362b6dce985d5747b497e | sanjoy-kumar/pythontutorial | /variables.py | 3,367 | 4.625 | 5 | ## Assigning Values to Variables ##
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print(counter)
print(miles)
print(name)
## Multiple Assignment ##
a = b = c = 1 # assign a single value to several variables simultaneously
print(a)
print(b)
print(c)
x, y, z = 1, 2, "john" # assign multiple objects to multiple variables
print(x)
print(y)
print(z)
## Standard Data Types :Python has five standard data types − Numbers, String, List, Tuple, Dictionary ##
## Python Numbers ##
var1 = 1 # Number data types store numeric values.
var2 = 10
print(var1)
print(var2)
del var1, var2 # delete a single object or multiple objects by using the del statement.
## Python Strings ##
str = 'Hello World!'
print(str) # Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print((str + " ") * 3) # Prints string three times
print(str + " TEST") # Prints concatenated string
## Python Lists ##
# A list contains items separated by commas and enclosed within square brackets ([]) #
# A list can be accessed using the slice operator ([ ] and [:]) with indexes
# starting at 0 in the beginning of the list
# and working their way to end -1.
# The plus (+) sign is the list concatenation operator,
# and the asterisk (*) is the repetition operator.
list = ['abcd', 786, 2.23, 'john', 70.2]
tinylist = [123, 'john']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) # Prints concatenated lists
## Python Tuples ##
# A tuple is another sequence data type that is similar to the list.
# Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed,
# while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
# Tuples can be thought of as read-only lists.
tuple = ('abcd', 786, 2.23, 'john', 70.2)
tinytuple = (123, 'john')
print(tuple) # Prints the complete tuple
print(tuple[0]) # Prints first element of the tuple
print(tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print(tuple[2:]) # Prints elements of the tuple starting from 3rd element
print(tinytuple * 2) # Prints the contents of the tuple twice
print(tuple + tinytuple) # Prints concatenated tuples
## Python Dictionary ##
# Python's dictionaries are kind of hash table type.
# They work like associative arrays or hashes found in Perl and consist of key-value pairs.
# A dictionary key can be almost any Python type, but are usually numbers or strings.
# Values, on the other hand, can be any arbitrary Python object.
# Dictionaries are enclosed by curly braces ({ }) and
# values can be assigned and accessed using square braces ([]).
dictvar = {}
dictvar['one'] = "This is one"
dictvar[2] = "This is two"
tinydict = {'name': 'john', 'code': 6734, 'dept': 'sales'}
print(dictvar['one']) # Prints value for 'one' key
print(dictvar[2]) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values
|
3575b3f38e21ec62fa1df35cbc012adf3d047ea5 | shv07/dsa | /Arrays/MoveZeros.py | 585 | 3.734375 | 4 | def moveZeroes(nums):
"""
Move all the occurence of zeros to end of the array without changing anyone's relative order.
Do it inplace in O(n)
Ref - Question taken from LeetCode
"""
l = len(nums)
zpos = 0
nextnz = 1
while zpos<l and nextnz<l:
if nums[zpos]!=0:
zpos+=1
nextnz+=1
continue
if nums[nextnz]==0:
nextnz+=1
else:
tmp = nums[zpos]
nums[zpos] = nums[nextnz]
nums[nextnz] = tmp
zpos+=1
nextnz+=1
|
bad43afa77c8afe4bdb9404cf1180fae6cf7ca3c | zafodB/pythonAssignments | /venv/Assignments/TicTacToe/TicTacToe.py | 13,230 | 3.78125 | 4 | '''
* Created by filip on 26/02/2018
'''
import copy
def main():
board = [["." for j in range(3)] for i in range(3)]
difficulty = 3
# Prints out any board
def print_board(to_print):
print("___________")
for i in to_print:
print("|", end="")
for j in i:
print(" " + str(j) + " ", end="")
print("|")
print("¯¯¯¯¯¯¯¯¯¯¯")
# Takes user's input and calls place_tile(), if move is possible. Returns True, if it's a winning move, False otherwise.
def user_turn():
print_board(board)
while True:
user_input = input("\n Please press number 1 - 9 to place X\n")
if len(user_input) == 1:
if user_input == "1" and board[2][0] == ".":
return place_tile(0, 2, "X")
if user_input == "2" and board[2][1] == ".":
return place_tile(1, 2, "X")
if user_input == "3" and board[2][2] == ".":
return place_tile(2, 2, "X")
if user_input == "4" and board[1][0] == ".":
return place_tile(0, 1, "X")
if user_input == "5" and board[1][1] == ".":
return place_tile(1, 1, "X")
if user_input == "6" and board[1][2] == ".":
return place_tile(2, 1, "X")
if user_input == "7" and board[0][0] == ".":
return place_tile(0, 0, "X")
if user_input == "8" and board[0][1] == ".":
return place_tile(1, 0, "X")
if user_input == "9" and board[0][2] == ".":
return place_tile(2, 0, "X")
print("Try again.")
# Places tile on board and returns True, if it's a winning move.
def place_tile(x, y, char):
nonlocal board
board[y][x] = char
return is_win_move(board, x, y, char)
# Takes board, coordinates and character as arguments. Places character onto the board on specified coordinates and returns, if this is a winning move.
def is_win_move(hboard, x, y, mchar):
board_vals = [[0 for k in range(3)] for l in range(3)]
# Turn board into values
yi = 0
while yi < 3:
xi = 0
while xi < 3:
if hboard[yi][xi] == mchar:
board_vals[yi][xi] = 1
xi += 1
yi += 1
board_vals[y][x] = 1
# Check rows
yi = 0
while yi < 3:
sum_win = 0
xi = 0
while xi < 3:
sum_win += board_vals[yi][xi]
xi += 1
if sum_win == 3:
return True
yi += 1
# Check columns
yi = 0
while yi < 3:
sum_win = 0
xi = 0
while xi < 3:
sum_win += board_vals[xi][yi]
xi += 1
if sum_win == 3:
return True
yi += 1
# Check diagonals
if board_vals[0][0] == 1 and board_vals[1][1] == 1 and board_vals[2][2] == 1:
return True
# Check diagonals
if board_vals[0][2] == 1 and board_vals[1][1] == 1 and board_vals[2][0] == 1:
return True
return False
# Makes AI move, depending on the selected level of difficulty.
def ai_turn():
# Creates a copy of a board (to test out hypothetical moves).
def copy_board(in_board):
out_board = [0 for l in range(3)]
i = 0
for row in in_board:
out_board[i] = list(row)
i += 1
return out_board
# Looks at passed board and considers immediate wins or losses.
def consider_possibilities(hboard, nchar):
next_turn_map = [[0 for j in range(3)] for i in range(3)]
y = 0
while y < 3:
x = 0
while x < 3:
eval_res = evaluate_turn(hboard, x, y, nchar)
if not eval_res:
x += 1
continue
elif eval_res == 45:
next_turn_map[y][x] = 45
elif eval_res == 2:
next_turn_map[y][x] = 2
elif eval_res == 100:
next_turn_map[y][x] = 100
x += 1
y += 1
return next_turn_map
# Checks, if placing a tile on specified coordinate results in win or a lose.
def evaluate_turn(hboard, mx, my, mchar):
if not is_valid_move(hboard, mx, my):
return False
if is_win_move(hboard, mx, my, mchar):
return 100
if need_to_block(hboard, mx, my, mchar):
return 45
return 2
# Checks, if a move is possible (that there are no tiles in the way)
def is_valid_move(hboard, x, y):
return hboard[y][x] == "."
# Checks if next move can be a winning move for the opposing player.
def need_to_block(hboard, x, y, mchar):
if mchar == "X":
return is_win_move(hboard, x, y, "O")
else:
return is_win_move(hboard, x, y, "X")
# Checks, if it can immediately win or lose. If yes, returns coordinates where to place tile appropriately.
def next_turn_win_lose(hboard, mchar):
next_turn_win = consider_possibilities(hboard, mchar)
found_next_turn = False
possible_moves = 0
next_move_x = -1
next_move_y = -1
y = 0
while y < 3:
x = 0
while x < 3:
# Can it win in next turn?
if next_turn_win[y][x] == 100:
found_next_turn = True
next_move_x = x
next_move_y = y
return [found_next_turn, next_move_x, next_move_y, -1]
# Does it need to block in next turn?
elif next_turn_win[y][x] == 45:
next_move_x = x
next_move_y = y
found_next_turn = True
elif not next_turn_win[y][x] == 0:
# Is there only one available move?
possible_moves += 1
if possible_moves == 1 and not found_next_turn:
next_move_x = x
next_move_y = y
x += 1
y += 1
return [found_next_turn, next_move_x, next_move_y, possible_moves]
nonlocal board
# Difficulty level 1
# Checks if AI can win or lose immediately. If it can win, it wins. If it could lose, it blocks.
# Also checks if this is the last turn. If so, places the last tile (and no further calculations are performed).
immediate_turn = next_turn_win_lose(board, "O")
if immediate_turn[0]:
return place_tile(immediate_turn[1], immediate_turn[2], "O")
elif immediate_turn[3] == 1:
return place_tile(immediate_turn[1], immediate_turn[2], "O")
# Difficulty level 1
else:
options = [[0 for l in range(3)] for k in range(3)]
# Consider placing own tile on every available position on the board.
y = 0
while y < 3:
x = 0
while x < 3:
if is_valid_move(board, x, y):
# Copying exiting game board to a hypothetical one.
hypot_board = copy_board(board)
# Place a tile onto the hypothetical board
hypot_board[y][x] = "O"
# After own tile has been placed on the hypothetical board, consider every possible next user move.
y1 = 0
while y1 < 3:
x1 = 0
while x1 < 3:
if is_valid_move(hypot_board, x1, y1):
hypot_board2 = copy_board(hypot_board)
hypot_board2[y1][x1] = "X"
# Difficulty level 2
if not next_turn_win_lose(hypot_board2, "O")[3] == -1 and not difficulty == 1:
block_rate = 0
y2 = 0
while y2 < 3:
x2 = 0
while x2 < 3:
if is_valid_move(hypot_board2, x2, y2) and not is_win_move(hypot_board2,
x2, y2, "O"):
if need_to_block(hypot_board2, x2, y2, "O"):
block_rate += 1
hypot_board3 = copy_board(hypot_board2)
hypot_board3[y2][x2] = "O"
# Difficulty level 3
if not next_turn_win_lose(hypot_board3, "X")[
3] == -1 and difficulty == 3:
y3 = 0
while y3 < 3:
x3 = 0
while x3 < 3:
if is_valid_move(hypot_board3, x3,
y3) and not is_win_move(hypot_board3,
x3, y3, "X"):
hypot_board4 = copy_board(hypot_board3)
hypot_board4[y3][x3] = "X"
block_rate2 = 0
for row in consider_possibilities(hypot_board4,
"O"):
for item in row:
if item == 45:
block_rate2 += 1
if block_rate2 > 1:
options[y][x] -= 10
x3 += 1
y3 += 1
x2 += 1
y2 += 1
if block_rate > 1:
options[y][x] -= 20
x1 += 1
y1 += 1
else:
options[y][x] = -550
x += 1
y += 1
best_option_cost = -2000
best_option_x = 0
best_option_y = 0
# Find the best move based on calculated weight of options.
y = 0
while y < 3:
x = 0
while x < 3:
if options[y][x] > best_option_cost:
best_option_cost = options[y][x]
best_option_x = x
best_option_y = y
x += 1
y += 1
# Place the tile and return True if it is a winning move.
return place_tile(best_option_x, best_option_y, "O")
# Starts the game
def play_game():
tile = 0
nonlocal difficulty
user_input = input("Select the level of difficulty: (1 - 3)")
if user_input == "1":
difficulty = 1
elif user_input == "2":
difficulty = 2
if input("Wanna start? y/n") == "y":
user_turn()
tile += 1
game_over = False
while not game_over and not tile == 9:
tile += 1
game_over = ai_turn()
if not game_over and not tile == 9:
tile += 1
game_over = user_turn()
print_board(board)
print("Game finished.")
play_game()
main()
|
2264a5c3a7cab95d439255747ff0c6c19d836e5c | tomattman/pythonTrain | /c1/4.py | 564 | 3.5625 | 4 | import random
import sys
articles = ['the', 'a']
nouns = ['cat', 'dog', 'man', 'woman']
verbs = ['sang', 'ran', 'jumped']
adverbs = ['loudly', 'quietly', 'well', 'badly']
i = 0
try:
count = int(sys.argv[1])
if 1 > count > 10:
count = 5
except ValueError:
count = 5
except IndexError:
count = 5
while i < count:
i += 1
article = random.choice(articles)
noun = random.choice(nouns)
verb = random.choice(verbs)
adverb = random.choice(adverbs)
if random.randint(0, 1) == 0:
print(article, noun, verb)
else:
print(article, noun, verb, adverb)
|
935bf472e2b81b3fc10b91219d94adc81705c707 | mayh0x/funcional_UFC | /topic_3/Python/2-final.py | 415 | 3.609375 | 4 | # Retorne os x números finais da lista
def final(n, xs):
listafinal = []
tamlista = len(xs)
n = tamlista - n
for x in xs:
if n < tamlista:
if x == xs[n]:
listafinal.append(x)
n += 1
return listafinal
print(final (3, [2,5,4,7,9,6]) == [7,9,6]) #True
print(final (2, [2,5,4,7,9,6]) == [9,6]) #True
print(final (1, [2,5,4,7,9,6]) == [6]) #True |
7aa7a341064355b4ed0c1e431a6e0273b8f5167c | woxsao/K-Means-implementation | /KMeansImplementation.py | 7,900 | 3.796875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import distance
class KMeansImplementation:
def __init__(self, k, max_iter, tol):
"""
Constructor: k is the number of clusters
max_iter is the maximum number of iterations
tol is the tolerance margin for the SSE
"""
self.k = k
self.tol = tol
self.max_iter = max_iter
def kmean_implement(self, points, blobs = False, categories = None, clustering = 'regular'):
"""
This function uses kmeans clustering to segment the points.
Parameters:
- points is the points that we are fitting to the algorithm
- blobs is a boolean for plotting blobs
- categories is a paramter for the blobs graphing
- clustering is the intial condition centroid choosing method. This function supports random initial cluster choice, best of 10
which is just choosing the centroids that produces the lowest SSE out of 10 random centroid combinations, and also kmeans++
Returns:
- a list of indeces representing which cluster each point belongs to
- the coordinates of each of those cluster centers
- the final Sum of square errors (SSE)
"""
if(blobs == True and categories == None):
print("You must specify a category parameter if blob parameter is True. Please try again")
else:
done = False
iteration = 0
previous_sse = 0
lowest_sse = None
lowest_centroid_list = None
centroid_list = None
current_sse = None
#this for loop will generate the best of 10 initial clusters:
if(clustering == 'random10'):
for i in range(0,10):
random_centroids = initialize_centroids(points, self.k)
current_sse, new_centroids = kmeans_skeleton(points, random_centroids)[0:2]
if(lowest_sse == None or current_sse < lowest_sse):
lowest_sse = current_sse
lowest_centroid_list = new_centroids
centroid_list = lowest_centroid_list
#This is the implementation for kmeans++
elif clustering == 'plus':
centroid_list = initialize_centroids(points, 1)
for i in range(0, self.k-1):
#np.seterr(divide='ignore', invalid='ignore')
distances = distance.cdist(points, centroid_list, 'minkowski', p = 1.5)
minDistances = np.min(distances, axis = 1)
probs = minDistances / sum(minDistances)
numPoints = points.shape[0]
index = np.random.choice(a = numPoints, p = probs)
point = points[index].reshape(1, len(points[index]))
centroid_list = np.append(centroid_list, point, axis = 0)
#This is random centroid initialization, no bells or whistles
else:
centroid_list = initialize_centroids(points, self.k)
#code for blob graphing
if blobs == True:
graph_blobs(points, categories, centroid_list, 'initial condition')
while done == False:
current_sse, new_centroids, new_assigned = kmeans_skeleton(points, centroid_list)
#code for blob graphing
if blobs == True:
graph_blobs(points, categories,new_centroids,iteration)
#this section is to check whether we need to keep iterating. If the SSE hasn't changed less than the tol, then we're done
if (iteration == self.max_iter) or (abs(previous_sse-current_sse) <= self.tol and iteration != 0):
done = True
print(iteration)
return new_assigned, new_centroids, current_sse
else:
previous_sse = current_sse
centroid_list = new_centroids
iteration += 1
done = False
def kmeans_skeleton(points, centroid_list):
"""
This function runs the kmeans algorithm for one iteration, just helps shorten my code a little
Parameters:
- points: the data
- centroid_list: the list of centroid coordinates
Returns:
- The sum of square errors
- The centroid list
- the list of indices indicating which centroid each point is clustered to
"""
assigned_centroids = find_closest_centroid(points, centroid_list)
#this section determines the new centroids through averages
new_centroids = find_new_centroids(points, centroid_list, assigned_centroids)
#this section reassigns the points to the new centroids
new_assigned = find_closest_centroid(points, new_centroids)
#this section is for algorithm verification
current_sse = get_errors(points, new_assigned, new_centroids)
return current_sse, new_centroids, new_assigned
def initialize_centroids(points, k):
"""
This function generates k random centroid points from the points
Parameters:
- points is the points
- k is the number of centroids
Returns:
- an array of k centroids
"""
shuffled_points = points.copy()
np.random.shuffle(shuffled_points)
return shuffled_points[:k, :]
def find_closest_centroid(points, centroids):
"""
returns an array containing the index to the nearest centroid for each point
Parameters:
- points: the points
- centroids: the coordinates of the centroids
Returns:
- an array of which indices representing which centroid each point is closest to.
"""
distances = distance.cdist(points, centroids, metric = 'minkowski')
return_value = np.argmin(distances, axis = 1)
return return_value
def find_new_centroids(points, centroids, assigned_centroids):
"""
returns a list of new centroid coordinates based on the averages across each cluster
Parameters:
- points: the data
- centroids: the coordinates of the centroids
Returns:
- an array of new averaged centroid coordinates
"""
return_array = []
for i in range(centroids.shape[0]):
return_array.append(points[assigned_centroids==i].mean(axis = 0))
return np.array(return_array)
def get_errors(points, assigned_centroids, centroid_coordinates):
"""
returns the sum of squared errors between centroids and the data.
Parameters:
- points: data
- assigned_centroids: list of indices representing which centroid each data point is assigned to
- centroid_coordinates: list of each centroid's coordinates
Returns:
- a float representing the sum of squared errors
"""
centroids = assigned_centroids.astype(int)
errors = np.sum((points - centroid_coordinates[centroids])**2)
return errors
def graph_blobs(points, categories, centroid_coordinates, iteration):
"""
Graphs the blob and iteration, only relevant for the blobs from sklearn
Parameters:
- poitns: data
- categories: the original categories from the sklearn blob function
- centroid_coordinates: the coordinates for the centroids
- iteration: which iteration number the algorithm is on
"""
x,y = zip(*centroid_coordinates)
title = "Iteration #" + str(iteration)
plt.figure()
plt.scatter(points[:, 0], points[:, 1], marker = 'o', c = categories)
plt.scatter(x,y, marker = 'h', c = 'red')
plt.title(title)
plt.show()
|
76e163673c7ebbb1fca33852fc4a9c8e19ad5b37 | CescWang1991/LeetCode-Python | /python_solution/051_060/SpiralMatrix.py | 2,232 | 3.734375 | 4 | # 054. Spiral Matrix
# 059. Spiral Matrix II
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
spiral = []
if len(matrix) == 0:
return []
if len(matrix) == 1:
spiral += matrix[0]
elif len(matrix[0]) == 1:
for row in range(len(matrix)):
spiral.append(matrix[row][0])
else:
# first row
spiral += matrix[0]
matrix.remove(matrix[0])
# last column
col = len(matrix[0]) - 1
for row in range(0, len(matrix)):
spiral.append(matrix[row][col])
matrix[row].remove(matrix[row][col])
# last row
spiral += reversed(matrix[len(matrix) - 1])
matrix.remove(matrix[len(matrix) - 1])
# first column
if len(matrix) != 0:
if matrix[0]:
for row in reversed(range(0, len(matrix))):
spiral.append(matrix[row][0])
matrix[row].remove(matrix[row][0])
if len(matrix) != 0:
if matrix[0]:
spiral += self.spiralOrder(matrix)
return spiral
class Solution2:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
return self.generateWithStart(1, n)
# 递归调用,s表示在当前层左上角开始的值
def generateWithStart(self, s, n):
if n == 0:
return []
if n == 1:
return [[s]]
ans = []
# 第一行
ans.append(list(range(s, s+n)))
s = s + n
# 最右列
for i in range(s, s+n-2):
ans.append([i])
s = s+n-2
# 最后一行
ans.append(list(reversed(range(s, s+n))))
s = s + n -1 + n - 1 # 直接将s指向内圈矩阵最开始的s
mid = self.generateWithStart(s, n-2) # 递归给出内圈的矩阵
# 左列以及中圈
if mid:
for i in range(len(mid)):
ans[i+1] = [s-i-1] + mid[i] + ans[i+1]
return ans |
8040fa64d67ebf11ad647c21aab6fc18b17db528 | yhbyhb/data_analyst_nanodegree_p2 | /P2_codes/data.py | 7,567 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.cElementTree as ET
import pprint
import re
import codecs
from bson import json_util
import json
import dateutil.parser
import audit
"""
data.py wrangles the data(.osm) and transform the shape of the data into the model that
is similar with used in Lesson 6 - 12 Preparing for Database.
function 'process_map' and 'insert_map_data' are executed sequentially.
the function 'process_map' iteratively parses map data(map.osm) and writes to JSON file.
It returns a list of dictionaries for inserting DB.
It iteratively parses xml element by calling the function 'shape_element'
the function 'shape_element' returns a dictionay, containing the shaped data for given element.
It audits and shaped a given element as follows.
- It shapes three basic data structures (top level tags), 'node', 'way' and 'relation'.
- It classified three top level tags with key 'type', for instance
{...
"type": "node",
...
}
- all attributes of "node", "way" and "relation" turned into regular key/value pairs, except:
- attributes in the CREATED array are added in dictionary under a key "created"
- attributes for latitude and longitude are added to a "pos" array with floats values (converted from strings).
- attributes for timestamp is parsed with datetime object using date aggregation operators.
- if second level tag "k" value contains problematic characters, ignored.
- if second level tag "k" value contains upper case characters, ignored.
- if second level tag "k" value starts with "addr:", it is added to a dictionary "address"
- if second level tag "k" value does not start with "addr:", but contains ":", the function process it
same as any other tag.
- if there is a second ":" that separates the type/direction of a street,
the tag is ignored, for example:
<tag k="addr:housenumber" v="5158"/>
<tag k="addr:street" v="North Lincoln Avenue"/>
<tag k="addr:street:name" v="Lincoln"/>
<tag k="addr:street:prefix" v="North"/>
<tag k="addr:street:type" v="Avenue"/>
<tag k="amenity" v="pharmacy"/>
are turned into:
{...
"address": {
"housenumber": 5158,
"street": "North Lincoln Avenue"
}
"amenity": "pharmacy",
...
}
- The top level tag "way" has child elements named 'nd'. For instence,
<nd ref="305896090"/>
<nd ref="1719825889"/>
are turned into
"node_refs": ["305896090", "1719825889"]
- The top level tag 'relation' has child elemnts named 'member'. Attributes of 'member' are added in dictionary.
'member' dictionaies are added a list named 'members'. For instance,
<member ref="333202546" role="from" type="way" />
<member ref="65449648" role="via" type="node" />
<member ref="61237966" role="to" type="way" />
are turned into:
"members": [
{
"role": "from",
"ref": "333202546",
"type": "way"
},
{
"role": "via",
"ref": "65449648",
"type": "node"
},
{
"role": "to",
"ref": "61237966",
"type": "way"
}
]
- Also, 'relation' has a second level tag 'type'. It confilcts with key 'type' as mentioned above.
So type of relation is converted as follow,
<tag k="type" v="route" />
are turned into:
"relation_type": "route"
the function 'insert_map_data' insert a list of dictionaries from function 'process_map' to mongoDB.
"""
lower = re.compile(r'^([a-z]|_)*$')
lower_colon = re.compile(r'^([a-z]|_)*:([a-z]|_)*$')
problemchars = re.compile(r'[=\+/&<>;\'"\?%#$@\,\. \t\r\n]')
CREATED = [ "version", "changeset", "user", "uid"]
def shape_element(element):
node = {}
# Allows only three basic top level elements
if element.tag in ('node', 'way', 'relation'):
# Adding type
node["type"] = element.tag
# Adding attribues - generals
node["id"] = element.attrib["id"]
if "visible" in element.attrib:
node["visible"] = element.attrib["visible"]
# Adding attribues - exceptions #1 'created'
created = {}
for key in CREATED:
created[key] = element.attrib[key]
# convert from date string to datetime object
created['timestamp'] = dateutil.parser.parse(element.attrib['timestamp'])
node["created"] = created
# Adding attribues - exceptions #2 shaping position
if "lat" in element.attrib and "lon" in element.attrib:
node["pos"] = [float(element.attrib["lat"]), float(element.attrib["lon"])]
# Adding child elements
node_refs = []
address = {}
members = []
for child in element:
# Auditing and shaping "tag" elements
if child.tag == "tag":
k = child.attrib['k']
# Ignoring key including problematic characters
if re.search(problemchars, k) != None:
continue
# Ignoring key including upper case characters
if re.search(lower, k) != None:
# Handling confilcts when second level tag "k" value is 'type'
if k == 'type':
node[element.tag + '_type'] = child.attrib['v']
else:
node[k] = child.attrib['v']
# Ignoring key including problematic characters
if re.search(lower_colon, k) != None:
if k.startswith("addr:"):
if len(k.split(":")) == 2 :
v = child.attrib['v']
# cleaning street
if k == "addr:street":
v = audit.update_name(v, audit.mapping)
address[k.split(":")[1]] = v
else:
node[k] = child.attrib['v']
# for 'way'
elif child.tag == "nd":
node_refs.append(child.attrib["ref"])
# for 'relation'
elif child.tag == 'member':
member = {}
member['ref'] = child.attrib['ref']
member['role'] = child.attrib['role']
member['type'] = child.attrib['type']
members.append(member)
if len(node_refs) > 0:
node["node_refs"] = node_refs
if len(address) > 0:
node["address"] = address
if len(members) > 0:
node["members"] = members
return node
else:
return None
def process_map(file_in, pretty = False):
file_out = "{0}.json".format(file_in)
data = []
# iterative parsing and writing JSON file
with codecs.open(file_out, "w") as fo:
for _, element in ET.iterparse(file_in):
el = shape_element(element)
if el:
data.append(el)
# Using json_util.default parser for datetime object
if pretty:
fo.write(json.dumps(el, indent=2, default=json_util.default )+"\n")
else:
fo.write(json.dumps(el, default=json_util.default) + "\n")
return data
def insert_map_data(data):
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client.p2
db.osm.insert(data)
def test():
# wrangling osm file and save to JSON file
map_file_name = 'map.osm'
data = process_map(map_file_name, False)
# inserting to mongoDB
insert_map_data(data)
if __name__ == "__main__":
test()
|
4b98ef5632276a5ffa5f5da33b400dc8f1c986ba | Victody/Pygame | /MovNave.py | 3,000 | 3.5625 | 4 | import pygame
import random
def main():
#Definições dos objetos
screen_width = 600
screen_height = 600
#variáveis para tamanho de tela
pygame.init()
#Iniciando a biblioteca
tela = pygame.display.set_mode([screen_width, screen_height])
#Defini o tamanho de Tela
pygame.display.set_caption("Movimentação e Colisão de imagem")
#Defini Texto da janela
relogio = pygame.time.Clock()
#Clock captura o tempo de atualização da tela
onGame = True
#variável para controlar a execução do jogo
cor_branca = (255,255,255)
cor_azul = (108,194,236)
cor_verde = (54,182,112)
cor_vermelha = (227,57,9)
# variável com código RGB
imagem = pygame.image.load('assets\imagem\F117Space.png')
(x,y) = (150,100)
obj_velocidade = 5
vX = 0
vY= 0
ret = pygame.Rect(250,300,20,500)
sprite = pygame.sprite.Sprite()
sprite.image = imagem
sprite.rect = imagem.get_rect()
sprite.rect.top = 50
sprite.rect.left = 50
#pygame.font.init()
#Enquanto o jogo estiver executando
while onGame:
for event in pygame.event.get():
#Capturo um evento e aplico na variável event
if event.type == pygame.QUIT:
#Sse o evento for do tipo 'quit', ou seja, o usuário clicar no botão fechar
onGame = False
#'Desliga' o jogo
# Movimento pelo teclado
if event.type == pygame.KEYDOWN:
# O primeiro passo é verificar se qualquer tecla foi pressionada
if event.key == pygame.K_LEFT:
vX -= obj_velocidade
if event.key == pygame.K_RIGHT:
vX +=obj_velocidade
if event.key == pygame.K_UP:
vY -=obj_velocidade
if event.key == pygame.K_DOWN:
vY += obj_velocidade
if event.type == pygame.KEYUP:
# O primeiro passo é verificar se qualquer tecla foi pressionada
if event.key == pygame.K_LEFT:
vX = 0
if event.key == pygame.K_RIGHT:
vX =0
if event.key == pygame.K_UP:
vY = 0
if event.key == pygame.K_DOWN:
vY = 0
# if event.type == pygame.MOUSEBUTTONDOWN:
if sprite.rect.colliderect(ret):
sprite.rect.left = oldX
sprite.rect.top = oldY
x += vX
y += vY
relogio.tick(120)
# tick atualiza a tela a 60 frames por segundo
tela.fill(cor_branca)
#tela.blit(imagem,(x-25,y-25))
#(x,y) = pygame.mouse.get_pos()
pygame.draw.rect(tela, cor_vermelha, ret)
oldX = sprite.rect.left
oldY = sprite.rect.top
tela.blit(sprite.image, sprite.rect)
sprite.rect.move_ip(vX, vY)
pygame.display.update()
pygame.quit()#Fecha a janela
main()
|
3cf3377fccbf1b3d3bbe091ab10ec927d53fb9f6 | green-fox-academy/TemExile | /week-03/day-1/bank_account.py | 1,532 | 3.8125 | 4 | class currency(object):
def __init__(self, code, centralBank, value):
self.code = code
self.centralBank = centralBank
self.value = value
class USADollar(currency):
def __init__(self, value):
self.code = 'USA'
self.centralBank = 'Federal Reserve System'
super().__init__()
class HungarianForint(currency):
def __init__(self, value):
self.code = 'HUF'
self.centralBank = 'Hungarian National Bank'
super().__init__()
class bankAccount(object):
def __init__(self, pin, curr):
self.pin = pin
self.curr = curr
def deposit(self, amount):
if amount > 0:
self.curr.value += amount
else:
print('Please deposit the right amount')
def withdraw(self, pin, amount):
if self.pin == pin and self.curr.value >= amount:
self.curr.value -= amount
return amount
elif self.pin != pin:
print('Please enter the right pin')
return 0
elif self.curr.value < amount:
print('You do not have enough balance in you account.')
return 0
class bank(object):
def __init__(self, accountlist = []):
self.accountlist = accountlist
def createAccount(self, newaccount):
self.accountlist.append(newaccount)
def getAllMoney(self):
totalamount = 0
for account in self.accountlist:
value = account.curr.value
totalamount += value
return totalamount |
7e5d65a3ea3a0f341e2c94c441bb76e94c9177d9 | uohzxela/fundamentals | /data_structures/hashset.py | 1,050 | 3.578125 | 4 | class HashSet(object):
def __init__(self, capacity=1000):
self.capacity = capacity
self.buckets = [[] for i in xrange(self.capacity)]
def hash(self, key):
return sum([ord(c) for c in key]) % self.capacity
def add(self, key):
bucket = self.buckets[self.hash(key)]
for i in xrange(len(bucket)):
if bucket[i] == key:
return
bucket.append(key)
def remove(self, key):
bucket = self.buckets[self.hash(key)]
for i in xrange(len(bucket)):
if bucket[i] == key:
bucket.remove(bucket[i])
return
raise KeyError(key)
def contains(self, key):
bucket = self.buckets[self.hash(key)]
for i in xrange(len(bucket)):
if bucket[i] == key:
return True
return False
def __contains__(self, key):
return self.contains(key)
def __repr__(self):
string = []
for bucket in self.buckets:
if not bucket: continue
string.append(bucket[0])
return '\n'.join(string)
h = HashSet()
h.add("alex")
assert "alex" in h
h.add("xela")
assert "xela" in h
h.remove("alex")
assert "alex" not in h
h.add("vera")
print h |
b22adfbd6f0b2f667669cfb62953eb98642f0ed9 | finddeniseonline/sea-c34-python.old | /students/MeganSlater/session06/special.py | 713 | 4.3125 | 4 | """Question 1:
If my class inherits from object, do I have to define every special
method I want to be able to use or are special methods set to
some kind of default?
"""
class Rectangle(object):
"""define rectangle class with attributes of height
and width as well as a special method of add"""
def __init__(self, height, width):
self.height = height
self.width = width
def __add__(self, other):
return Rectangle(self.height + other.height, self.width + other.width)
r1 = Rectangle(20, 30)
r2 = Rectangle(40, 50)
r3 = r1 + r2
# r3 = r1 * r2
# r3 = r1 + r2
# r3 = r1 / r2
# r3 = r1 // r2
# r3 = r1 ** r2
# all of these get errors. Special methods are not defined.
|
65aadd74e28373d7d4258082dcf251fbcec83004 | GMwang550146647/network | /0.leetcode/0.基本数据结构/6.其他/1.LinkHashMap(LFU&LRU)/base.py | 1,238 | 3.765625 | 4 | class Node():
def __init__(self, key=None, val=None):
self.key = key
self.val = val
self.next = None
self.pre = None
class DoubleList():
def __init__(self):
self.head = Node('HEAD', 'HEAD')
self.tail = Node('TAIL', 'TAIL')
self.head.next = self.tail
self.tail.pre = self.head
self.size = 0
def add_last(self, node):
node.next = self.tail
node.pre = self.tail.pre
self.tail.pre.next = node
self.tail.pre = node
self.size += 1
def remove(self, node):
node.pre.next = node.next
node.next.pre = node.pre
self.size -= 1
def remove_first(self):
if self.head.next == self.tail:
return None
else:
tempt = self.head.next
self.remove(tempt)
return tempt
def show(self, reverse=True):
tempt = []
if reverse:
pt = self.tail
while (pt):
tempt.append(pt.val)
pt = pt.pre
else:
pt = self.head
while (pt):
tempt.append(pt.val)
pt = pt.next
print(tempt)
return tempt[1:-1]
|
fad7b1730d73619f9a4a66d2f1658f06f4f64531 | maiali13/cs-module-project-hash-tables | /applications/word_count/word_count.py | 1,185 | 4.09375 | 4 | def word_count(s):
"""
Input: This function takes a single string as an argument.
Output: It returns a dictionary of words and their counts.
Case should be ignored. Output keys must be lowercase.
Key order in the dictionary doesn't matter.
Split the strings into words on any whitespace.
Ignore each of the following characters:
" : ; , . - + = / \\ | [ ] { } ( ) * ^ &
"""
# could use defaultdict from NLP lesson ?
# have stop characters instead of stop words
cache = {}
stop_chars = [':', ';', ',', '.', '"', '-', '+', '=', '/',
'\\', '|', '[', ']', '{', '}', '(', ')', '*', '^', '&']
# replace stop characters
for i in stop_chars:
s = s.replace(i, '')
words = s.lower().split()
for word in words:
if word in cache:
cache[word] += 1
else:
cache[word] = 1
return cache
if __name__ == "__main__":
print(word_count(""))
print(word_count("Hello"))
print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.'))
print(word_count('This is a test of the emergency broadcast network. This is only a test.')) |
4c486d41f9fdcb05b418b616d656077cbc2ae1ff | Audarya07/Core2Web | /Python/31August/prog1.py | 442 | 3.671875 | 4 | num=0
num1=num;
for outer in range(1,6):
cnt=1
for inner in range(1,10):
if((inner+outer)>=6 and (inner-outer)<=4):
if(inner<=5):
num1=num1+1
print(num1,end=" ")
flag=1;
else:
print(num1-cnt,end=" ")
cnt=cnt+1
else:
print(" ",end=" ")
print()
if(flag==1):
num1=num+1
num=num+1
|
ccb1fac21d3fe5d40bf58c33810c41c23ec6e761 | simonfqy/SimonfqyGitHub | /lintcode/easy/1283_reverse_string.py | 556 | 3.953125 | 4 | '''
Link: https://www.lintcode.com/problem/1283/
'''
# My own solution. Using two pointers.
class Solution:
"""
@param s: a string
@return: return a string
"""
def reverse_string(self, s: str) -> str:
# write your code here
left, right = 0, len(s) - 1
# Using * is called unpacking.
char_list = [*s]
while left < right:
char_list[left], char_list[right] = char_list[right], char_list[left]
left += 1
right -= 1
return ''.join(char_list)
|
c6e233b891e9fc8f30c8a01b63f5beb2b7ef7acc | Ivan270991/homework2 | /map_filter.py | 159 | 3.515625 | 4 | a=[1,2,3,4,5]
def dubble(i):
return i*2
a=list(map(dubble,a))
print(a)
b=[1,2,3,4,5]
def chek(x):
return x<3
b=list(filter(chek,b))
print(b) |
26c4c9a4e9c221459b025e98ecbf34f1d0a8c26f | shubhamkumar1739/Coding-Practice | /Perfectice/LinkedList(Easy 5).py | 802 | 3.75 | 4 | class Node :
def __init__(self,data):
self.next=None
self.data=data
def insert(root,data):
global tail
node=Node(data)
if root==None:
root=node
tail=node
else :
tail.next=node
tail=node
return root
def traverse(root,position) :
position-=1
if position==0 :
print (root.data)
else :
count=0
temp=root
while temp.next!=None and count<=position-1 :
temp=temp.next
count+=1
print(temp.data)
if __name__=="__main__" :
global root
global tail
root=None
tail=None
inpStr=[]
inp=input().split(" ")
while True :
inpStr.append(inp[0])
try :
inp=input().split(" ")
except EOFError :
break
count=0
n=int(inpStr[count])
count+=1
key=int(inpStr[count])
count+=1
for i in range(0,n) :
root=insert(root,int(inpStr[count]))
count+=1
traverse(root,key) |
88540351581e03485b274259863ea5be05e8019b | EduardoAlbert/python-exercises | /Mundo 1 - Fundamentos/028-035 Condições/ex029.py | 443 | 3.875 | 4 | speed = float(input('Qual é a velocidade atual do carro? '))
if speed > 80:
multa = speed - 80
print('\033[32mVocê foi multado em \033[31mR${:.2f} \033[32mpor execeder \033[31m{}Km \033[32mda velocidade limite de 80Km/h!\033[m'.format(multa*7, multa))
else:
kms = 80 - speed
print('\033[34mA velocidade limite é \033[31m80Km/h\033[34m, você está a {:.1f}Km/h abaixo do limite.\033[32m Dirija com segurança!'.format(kms))
|
e36bd108d7e79882a4979fff4d271af38c90a00f | Vihan226/project-104 | /median.py | 862 | 3.921875 | 4 | # list of elements to calculate mean
import csv;
from collections import Counter;
with open('data.csv', newline="") as f:
reader=csv.reader(f)
file_data=list(reader)
file_data.pop(0)
#print(file_data)
#sorting data to get the height of people
new_data= []
for i in range(len(file_data)):
n_number=file_data[i][1]
new_data.append(float(n_number))
#getting the mean
n=len(new_data)
new_data.sort()
#using floor division to get the nearest number whole number floor division is shown by //
if n % 2 ==0:
#getting the first number
median1=float(new_data[n//2])
#getting the second number
median2=float(new_data[n//2-1])
#getting median of these numbers
median=(median1+median2)/2
else:
median=new_data[n//2]
print (n)
print("Median is :- "+str(median)) |
7b5d263364fd35fe6b9cb94e13ff9800c1ab8ce1 | Constellation-Labs/economic-model | /reference-impl/plots.py | 517 | 3.5625 | 4 | import math
import numpy as np
import matplotlib.pyplot as plt
import sys
def graph(func, x_range):
# x = np.arange(*x_range)
# y = func(x)
x = np.linspace(sys.float_info.min, 1.0, 100)
y = np.exp(-1/x)
plt.figure()
plt.plot(x, y)
plt.title('address stake vs bandwidth')
plt.xlabel('DAG in address / of total DAG in circulation')
plt.ylabel('% stake of total bandwidth (transactions/sec)')
if __name__ == '__main__':
graph(lambda x: np.power(-1.0, x), (0.0, 100.0, 0.01))
t = ""
|
923e79928c6dec05c55620e709fc656bb98f54f6 | Fihra/Python-for-linear-algebra | /matrix-hw.py | 1,159 | 4 | 4 | import numpy as np
#create 3 matrices: 2 x 2, 2x2, 3x2
# compute scalar-matrix multiplication
# add all pairs of matrices
m1 = np.array([[4, 5],
[7, 3]])
m2 = np.array([[2, 8],
[9, 12]])
m3 = np.array([[7, 14],
[3, 5],
[11, 10]])
output = np.zeros((2,2))
output2 = np.zeros((2,2))
output3 = np.zeros((3,2))
print("Create 3 Matrices")
print("Matrice 1")
print(m1)
print("Matrice 2")
print(m2)
print("Matrice 3")
print(m3)
for i in range(len(m1)):
for j in range(len(m1[i])):
output[i][j] = m1[i][j] * m2[i][j]
print("Compute scalar-matrix multiplication")
print(output)
print("Add all pairs of matrices")
print("m1 + m2")
for i in range(len(m1)):
for j in range(len(m1[i])):
output2[i][j] = m1[i][j] + m2[i][j]
print(output2)
print("m1 + m3")
# for i in range(len(m3)):
# print(m3[i])
# for j in range(len(m3[i] - 1)):
# if(j >= len(m3)):
# output3[i][j] = m3[i][j]
# else:
# output3[i][j] = m1[i][j] + m3[i][j]
for i,j in enumerate(m3):
print(m1[i])
print(m3[i])
# print("j: " + str(j))
# print(output3) |
80567bd42c68d03007ef024f5c0a3d0204053837 | paulamachadomt/estudos-python-Guanabara | /Python_Guanabara_mundo123/ex017.py | 663 | 3.828125 | 4 | #cálculo do comprimento da hipotenusa com a fórmula
cat_oposto = float(input('qual o comprimento do cateto oposto? '))
cat_adj = float(input('qual o comprimento do cateto adjacente? '))
hipotenusa = (cat_oposto ** 2 + cat_adj ** 2) ** (1/2)
print('A hipotenusa vai medir {:.2f}'.format(hipotenusa))
print ('=' * 100)
print ('=' * 100)
#cálculo do comprimento da hipotenusa com a importação da biblioteca math
import math
cat_oposto = float(input('qual o comprimento do cateto oposto? '))
cat_adj = float(input('qual o comprimento do cateto adjacente? '))
hipotenusa = math.hypot(cat_oposto, cat_adj)
print('A hipotenusa vai medir {:.2f}'.format(hipotenusa)) |
fe8841204098f2fddd2019899d277dd29601da55 | marcepan/algorithms | /sort/RecursiveBubbleSort.py | 308 | 3.921875 | 4 | def Sort(unsorted_list):
sorted_list = unsorted_list
for i in range(len(sorted_list)):
if i < len(sorted_list)-1 and sorted_list[i] > sorted_list[i+1]:
sorted_list[i], sorted_list[i+1] = sorted_list[i+1], sorted_list[i]
Sort(sorted_list)
return sorted_list |
c4ed1bbea88bf6402633040301772d7390e759ef | Felienne/PythonKoans | /koans/week_3_lesson_1_about_file_IO.py | 1,725 | 3.578125 | 4 |
from runner.koan import *
class AboutFileIO(Koan):
#1
def test_reading_full_file(self):
the_file = open("one_line.txt")
contents = the_file.read()
self.assertEqual(__, contents)
#2
def test_reading_file_with_multiple_lines(self):
the_file = open("short_lines.txt")
print(the_file)
contents = the_file.read()
self.assertEqual(__, contents)
#3
def test_reading_lines_directly(self):
the_file = open("short_lines.txt")
lines = the_file.readlines()
self.assertEqual(__, lines)
#4
def test_reading_file_line_by_line(self):
the_file = open("short_lines.txt")
a_line = the_file.readline()
self.assertEqual(__, a_line)
another_line = the_file.readline()
self.assertEqual(__, another_line)
one_more = the_file.readline()
self.assertEqual(__, one_more)
#5
def test_reading_file_with_for(self):
the_file = open("short_lines.txt")
lines = list()
for line in the_file:
lines.append(line)
self.assertEqual(__, lines)
#6
def test_reading_file_with_for_strip(self):
the_file = open("short_lines.txt")
lines = list()
for line in the_file:
line = line.strip()
lines.append(line)
self.assertEqual(__, lines)
#7
def test_reading_file_with_with(self):
# there are a number of reasons for it,
# but using with is the prefered way of opening a file
# feel free to read up on that if you are interested!
with open("short_lines.txt") as file:
self.assertEqual(__, len(file.readlines()))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.