blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
3e4315c5dcba28bc2ec8d49c18ecf10283800177
|
Henhenz1/mahjong-calculator-python
|
/main.py
| 53,996 | 3.515625 | 4 |
from math import ceil
#TODO TEST EVERYTHING
class Meld:
def __init__(self):
# a meld is a grouping of 3 or 4 tiles of the same suit, or 3 or 4 identical
# honor tiles, which we designate as their own suit
# 4 melds and a pair make up most valid hands, with two exceptions which
# are handled in different methods:
# - chiitoitsu, or seven pairs
# - kokushi musou, or thirteen orphans (one of each honor tile plus one duplicate)
# there are 3 different types of melds:
# - chi: 3 tiles of consecutive increasing value (e.g. P345)
# - pon: 3 identical tiles (e.g. S444)
# - kan: 4 identical tiles (e.g. M5555)
# a meld is CLOSED if no tile was taken from an opponent's discard to complete
# the meld; closed melds are worth more fu
# a meld is SIMPLE if it is comprised only of tiles of value 2-8
# a meld is a WIND if it is a pon or kan of E, S, W, or N
# a meld is a DRAGON if it is a pon or kan of R, H, or G
# a meld is GREEN if it is comprised only of tiles S23468 and G
self.tiles = ''
self.suit = ''
self.meld_type = ''
self.closed = True
self.simple = True
self.wind = False
self.dragon = False
self.green = False
def valid_meld(self):
# standard error checking for meld inputs, given a non-chiitoitsu hand
# function is applied to all inputted melds
# a False result causes the program to pause until the user inputs a valid meld
if len(self.tiles) not in range(3,6):
return False
# range(3,6) encompasses 3, 4, and 5
# string length 3 denotes honors pon
# string length 4 denotes chi, non-honors pon, or honors kan
# string length 5 denots non-honors kan
# any other string length is an invalid meld
self.tiles = self.tiles.upper()
# check the first character of the meld string to determine how to check for errors
if self.tiles[0] in "ESWNRHG": # first char is an honor tile
if len(self.tiles) > 4:
return False
for j in range(len(self.tiles)):
if self.tiles[j] != self.tiles[0]:
return False
# if the string begins with an honor tile, then string length must not exceed 4
# honor melds must be pons or kans, so the meld is only valid if all tiles are the same
elif self.tiles[0] in "MPB": # first char is a suit indicator
if len(self.tiles) < 4:
return False
# a non-honors meld is denoted using 1 char for suit and at least 3 for tiles
# if string length is less than 4, the meld is invalid
for k in range(len(self.tiles)-1):
if self.tiles[k+1] not in "123456789":
return False
# chars after the suit indicator must be valid numbers
if len(self.tiles) == 5:
for m in range(2,5):
if self.tiles[m] != self.tiles[1]:
return False
# length 5 indicates a kan, so all numbers following the tile indicator must be the same
elif len(self.tiles) == 4:
# length 4 is ambiguous, so we check the tile numbers
if self.tiles[1] == self.tiles[2]:
if self.tiles[3] != self.tiles[2]:
return False
# if the first two numbers are the same, meld should be a pon
# meld is valid only if the third number matches the first two
elif self.tiles[1] != self.tiles[2]:
if int(self.tiles[2]) != (int(self.tiles[1]) + 1) or int(self.tiles[3]) != (int(self.tiles[2]) + 1):
return False
# if the first two numbers are not the same, meld should be a chi
# meld is valid only if the numbers form an ascending sequence with d = 1
else:
return False
# a meld starting with anything other than a suit indicator or an honor tile is invalid
return True
# if the program gets through all checks without returning False, the meld must be valid
def suit_meld(self):
# this function is called only if a meld is valid as defined by valid_meld()
# we can assume that the meld begins with any of 'MPBESWNRHG'
# we use the first char in the tile string to set the meld suit and other variables
if self.tiles[0] == 'M':
self.suit = 'manzu'
elif self.tiles[0] == 'P':
self.suit = 'pinzu'
elif self.tiles[0] == 'B':
self.suit = 'souzu'
elif self.tiles[0] in 'ESWNRHG':
self.suit = 'honor'
if self.tiles[0] in 'ESWN':
self.wind = True
else:
self.dragon = True
return self.suit
def type_meld(self):
# this function is called only if a meld is valid as defined by valid_meld()
# we can assume that the meld is of length 3, 4, or 5
# we use the first two chars in the tile string as well as the string length
# to set the meld type
if len(self.tiles) == 5:
self.meld_type = 'kan'
hand_has_kan = True
# if hand_has_kan is True, the program later asks if the conditions
# for rinshan kaihou were met
elif len(self.tiles) == 4 and self.tiles[0] in 'ESWNRHG':
self.meld_type = 'kan'
hand_has_kan = True
elif len(self.tiles) == 4 and self.tiles[0] in 'MPB':
if self.tiles[1] == self.tiles[2]:
self.meld_type = 'pon'
else:
self.meld_type = 'chi'
elif len(self.tiles) == 3:
self.meld_type = 'pon'
return self.meld_type
def is_chi(self):
return self.meld_type == 'chi'
def is_pon(self):
return self.meld_type == 'pon'
def is_kan(self):
return self.meld_type == 'kan'
# preceding three functions for future cleanup and optimization work: delete if unneeded
def closed_meld(self):
# closed melds are formed entirely by tiles the player drew themselves
# this cannot be determined by the tiles alone, so the program asks the user if the meld was closed
# a chiitoitsu hand is necessarily closed, so this function is not called in that case
self.closed = evaluate_yn('closed_meld')
return self.closed
def green_meld(self):
# green tiles are so called because their tiles use only green ink
# a hand composed of all green melds and a green pair fulfills a special scoring condition
if self.suit == 'manzu' or self.suit == 'pinzu':
self.green = False
if self.suit == 'souzu':
for i in range(len(self.tiles)-1):
if self.tiles[i+1] not in '23468':
self.green = False
if self.suit == 'honor':
if self.tiles[0] != 'G':
self.green = False
def simple_meld(self):
# a simple meld is comprised of only number tiles with value 2-8
# important for scoring
if self.suit == 'honor':
self.simple = False
else:
for i in range(3):
if self.tiles[i+1] in '19':
self.simple = False
class Pair:
def __init__(self):
self.tiles = ''
self.suit = ''
self.simple = True
self.wind = False
self.dragon = False
self.green = True
self.significant = False
def valid_pair(self):
if len(self.tiles) not in range(2,4):
return False
# a pair string can be 2 or 3 chars long
# length 2 denotes an honors pair
# length 3 denotes a non-honors pair
# tiles in a pair are necessarily the same
self.tiles = self.tiles.upper()
if self.tiles[0] in "ESWNRHG":
if len(self.tiles) != 2:
return False
if self.tiles[0] != self.tiles[1]:
return False
elif self.tiles[0] in "MPB":
if len(self.tiles) != 3:
return False
for num in range(2):
if self.tiles[num+1] not in "123456789":
return False
if self.tiles[1] != self.tiles[2]:
return False
else:
return False
return True
def suit_pair(self):
# performs the same function as suit_meld(), but for pairs
if self.tiles[0] == 'M':
self.suit = 'manzu'
elif self.tiles[0] == 'P':
self.suit = 'pinzu'
elif self.tiles[0] == 'B':
self.suit = 'souzu'
elif self.tiles[0] in 'ESWNRHG':
self.suit = 'honor'
if self.tiles[0] in 'ESWN':
self.wind = True
else:
self.dragon = True
def significant_pair(self):
# used for determining pinfu and fu calculation
if self.tiles[0] in "RHG" or self.tiles[0] == round_wind or self.tiles[0] == personal_wind:
self.significant = True
def green_pair(self):
# performs the same function as green_meld(), but for pairs
if self.suit == 'manzu' or self.suit == 'pinzu':
self.green = False
if self.suit == 'souzu':
for i in range(len(self.tiles)-1):
if self.tiles[i+1] not in '23468':
self.green = False
if self.suit == 'honor':
if self.tiles[0] != 'G':
self.green = False
def simple_pair(self):
# performs the same function as simple_meld(), but for pairs
if self.suit == 'honor':
self.simple = False
for i in range(2):
if self.tiles[i+1] in '19':
self.simple = False
# user input functions
def yes_or_no_valid(yn):
# for use in evaluate_yn()
# returns True if input string is an acceptable yes/no answer and False otherwise
yn = yn.upper()
return yn in ['Y','N','YES','NO']
def return_yn(yn):
# for use in evaluate_yn()
# returns True if input string indicates 'yes' and False otherwise
yn = yn.upper()
return (yn == 'Y' or yn == 'YES')
def evaluate_yn(ask):
# evaluates yes/no user input for a given prompt and returns True/False
# if the input is invalid, the program pauses until a valid input is given
prompts = {
'hand_closed':'Was the hand fully closed?',
'closed_meld':'Was it fully closed?',
'tsumo':'Did the player tsumo?',
'chiitoitsu':'Was the winning hand chiitoitsu/seven pairs?',
'kokushi':'Was the winning hand Kokushi Musou/Thirteen Orphans?',
'riichi':'Did the winner declare riichi?',
'double_riichi':'Was it declared on the first turn without interruption?',
'ippatsu':'Did the winner win in one turn of riichi without interruption?',
'rinshan':'Did the winner declare kan, then win on the extra draw?',
'chankan':'Did the winner ron off of a late kan?',
'haitei':'Did the winner tsumo on the last tile?',
'houtei':'Did the winner ron on the last discard?',
'paarenchan':'Is this the eighth consecutive victory for the winner?',
'chiihou':'Did the winner tsumo on the first draw?',
'renhou':'Did the winner ron off the first discard without interruption?',
'tenhou':'Did the winner tsumo on the first draw as dealer?'
}
string_input = str(input(prompts[str(ask)] + ' (y/n) '))
while not yes_or_no_valid(string_input):
invalid()
string_input = str(input(prompts[str(ask)] + ' (y/n) '))
return return_yn(string_input)
def valid_wind(wind):
# for use in evaluate_wind
# performs same function as yes_or_no_valid() but for winds
wind = wind.upper()
return wind in ['E','S','W','N','EAST','SOUTH','WEST','NORTH']
def evaluate_wind(ask):
# evaluates wind input for scoring purposes
# if the input is invalid, the program pauses until a valid input is given
prompts = {
'round_wind':'Round wind (E/S/W/N): ',
'personal_wind':'Personal wind (E/S/W/N): '
}
string_input = str(input(prompts[str(ask)]))
while not valid_wind(string_input):
invalid()
string_input = str(input(prompts[str(ask)]))
return string_input.upper()
def valid_number(num):
# for use in evaluate_number
# prevents program from crashing by attempting to convert non-numerical string to int
for i in num:
if i not in "1234567890":
return False
return True
def evaluate_number(ask):
# evaluates various numerical questions for scoring purposes
# if the input is invalid, the program pauses until a valid input is given
prompts = {
'bonus_round':'Number of bonus sticks on table: ',
'riichibon':'Number of riichi sticks on table, including any placed by the winner: ',
'dora':'Total dora value of hand: '
}
string_input = str(input(prompts[str(ask)]))
while not valid_number(string_input):
invalid()
string_input = str(input(prompts[str(ask)]))
return int(string_input)
def invalid():
# prints an error message that asks the user to try again
print(invalid_input)
# yaku checking functions
# yakuman functions
def chuuren_check():
# chuuren is a hand comprised of 1112345678999 in one suit, plus an extra tile in the same suit
# this configuration always forms a valid hand and is worth yakuman
# if the player has a 9-sided wait, the hand is optionally worth double yakuman
if melds[0].suit == melds[1].suit == melds[2].suit == melds[3].suit == std_pair.suit and hand_closed:
if melds[0].suit != 'honor':
numbers = [hand[i][1:len(hand[i])] for i in range(len(hand))]
numbers = ''.join(sorted(numbers))
return numbers in chuuren_strings
else:
return False
else:
return False
# functions called only if chuuren is False
def shousuushi_check():
# shousuushi ("small four winds") is a hand containing pons/kans of three winds and a pair of the fourth
# the hand may be open, and requires at least one non-wind meld
# would it be easier to use sets here...?
if std_pair.wind != True:
return False
winds = [melds[i].tiles for i in range(4) if melds[i].wind == True]
if len(winds) != 3:
return False
for i in range(len(winds)):
winds[i] = winds[i][:3]
# truncates any kans for ease of checking
winds.append(std_pair.tiles)
winds = ''.join(sorted(winds))
return winds in shousuushi_strings # can probably be reduced to first if statement once duplicate tile checking is integrated
def daisuushi_check():
# daisuushi ("big four winds") is a hand containing pons/kans of all four winds
# therefore, the pair cannot be a wind
if std_pair.wind != False:
return False
for i in range(4):
if melds[i].wind != True:
return False
winds = [melds[i].tiles for i in range(4)]
for i in range(len(winds)):
winds[i] = winds[i][:3]
# truncates any kans for ease of checking
winds = ''.join(sorted(winds))
return winds == daisuushi_string
def daisangen_check():
# daisangen ("big three dragons") is a hand containing pons/kans of all three dragons
# therefore, the pair cannot be a dragon, or the hand can only be shousangen at best
if std_pair.dragon == True:
return False
dragons = [melds[i].tiles for i in range(4) if melds[i].dragon == True]
if len(dragons) != 3:
return False
for i in range(len(dragons)):
dragons[i] = dragons[i][:3]
# truncates any kans for ease of checking
dragons = ''.join(sorted(dragons))
return dragons == daisangen_string
def daichisei_check():
# daichisei ("big seven stars") is chiitoitsu combined with tsuuiisou
# there are seven different honor tiles and chiitoitsu requires seven distinct pairs
# therefore, there is only one acceptable combination of tiles for daichisei
for i in range(7):
if ct_pairs[i].suit != 'honor':
return False
pairs = [ct_pairs[i].tiles for i in range(7)]
pairs = ''.join(sorted(pairs))
return pairs == daichisei_string
def tsuuiisou_check():
# tsuuiisou is a hand composed of only honors
# all four melds and the pair must be made of honors
if std_pair.suit != 'honor':
return False
for i in range(4):
if melds[i].suit != 'honor':
return False
return True
def chinroutou_check():
# chinroutou is a hand composed of only terminals
# thus, no honor melds or chi melds are allowed
for i in range(4):
if melds[i].suit == 'honor' or melds[i].meld_type == 'chi':
return False
for j in range(len(melds[i].tiles)-1):
if melds[i].tiles[j+1] not in '19':
return False
return True
def ryuuiisou_check():
# ryuuiisou is a hand composed of only "green" tiles as defined by green_meld() and green_pair()
for i in range(4):
if not melds[i].green_meld():
return False
if not std_pair.green_pair():
return False
return True
def daisharin_check():
# daisharin is an optional yakuman for a closed hand containing 22334455667788 in one suit
# with other yaku only, a daisharin hand is worth pinfu + tanyao + ryanpeikou + chinitsu
# without this yakuman condition, the hand is still worth at least 11 han for sanbaiman
# an additional 2 han from riichi/ippatsu/dora easily bring the hand to a kazoe-yakuman
# there are three different names, one for each suit
if melds[0].suit == melds[1].suit == melds[2].suit == melds[3].suit == std_pair.suit != 'honor':
numbers = [melds[i].tiles[1:] for i in range(4)]
numbers.append(std_pair.tiles[1:])
numbers = ''.join(sorted(''.join(numbers)))
return numbers == daisharin_string
def iipeikou_ryanpeikou_check():
# called only if hand is closed
# iipeikou is true if a hand contains a pair of identical sequences in the same suit
# e.g. M112233
# ryanpeikou is true if a hand contains 2 pairs of identical sequences
# e.g. S223344 P445566
# ryanpeikou resembles chiitoitsu but is composed of melds and is therefore
# not scored as chiitoitsu
# ryanpeikou is worth 3 han, iipeikou is worth 1 han
# returns the number of pairs of identical sequences
sets = [melds[i].tiles for i in range(4) if melds[i].meld_type == 'chi']
if melds[0].tiles == melds[1].tiles == melds[2].tiles == melds[3].tiles:
return 2
# if all melds are identical then 2 pairs exist
duplicate_sets = set([meld for meld in sets if sets.count(meld) > 1])
return len(duplicate_sets)
def itsuu_check():
# itsuu is true if a hand contains the three sequences 123, 456, and 789 in
# the same suit forming a straight from 1-9
# it is worth 2 han if closed and 1 if open
sets = sorted([melds[i].tiles for i in range(4) if melds[i].meld_type == 'chi'])
if len(sets) < 3:
return False
# an itsuu hand must have at least three chi melds
if len(sets) == 3:
# if there are exactly three chi melds, then their numbers must form 123456789
# and their suits must be the same
if not (sets[0][0] == sets[1][0] == sets[2][0]):
return False
itsuu_tiles = ''.join(sorted(([sets[i][1:] for i in range(3)])))
return itsuu_tiles == itsuu_string
if len(sets) == 4:
itsuu_suits = sorted([melds[i].tiles[0] for i in range(4)])
for suit in ['B','M','P']:
if itsuu_suits.count(suit) == 3:
# if there are three chi melds of the same suit, their numbers
# must form 123456789
itsuu_tiles = ''.join(sorted(([sets[i][1:] for i in range(4) if sets[i][0] == suit])))
return itsuu_tiles == itsuu_string
elif itsuu_suits.count(suit) == 4:
# if there are four chi melds, there is at least one meld that
# does not contribute to itsuu
# if all four chi melds are of the same suit, then the set of their
# numbers must contain '123', '456', and '789'
itsuu_tiles = set()
for i in range(4):
itsuu_tiles.add(sets[i][1:])
return '123' in itsuu_tiles and '456' in itsuu_tiles and '789' in itsuu_tiles
return False
def sanshoku_doujun_check():
# sanshoku doujun is true if a hand contains the same chi meld in all three non-honor suits
# e.g. M234 P234 S234
# it is worth 2 han if closed and 1 if open
sets = sorted([melds[i].tiles for i in range(4) if melds[i].meld_type == 'chi'])
if len(sets) < 3:
return False
# by definition sanshoku doujun requires at least three chi melds
if len(sets) == 3:
if sets[0][1:] == sets[1][1:] == sets[2][1:] and sets[0][0] != sets[1][0] != sets[2][0] != sets[0][0]:
return True
# if there exactly three chi melds, then all must have different suits
# and their numbers must be identical
if len(sets) == 4:
suit_check = ''.join(sorted([sets[i][0] for i in range(4)]))
if suit_check not in sanshoku_four_suits:
# if this doesn't trigger when it's supposed to, it might be a problem with not putting upper()
return False
for i in range(3):
for j in range(3-i):
sanshoku_four_compare_tiles[i][j] = sets[i][1:] == sets[j+i+1][1:]
if suit_check == 'BBMP':
return sanshoku_four_compare_tiles == sanshoku_four_compare_same or sanshoku_four_compare_tiles in sanshoku_four_compare_bbmp
elif suit_check == 'BMMP':
return sanshoku_four_compare_tiles == sanshoku_four_compare_same or sanshoku_four_compare_tiles in sanshoku_four_compare_bmmp
elif suit_check == 'BMPP':
return sanshoku_four_compare_tiles == sanshoku_four_compare_same or sanshoku_four_compare_tiles in sanshoku_four_compare_bmpp
# this honestly seems like such a horrifyingly bad way to do it but it's the best I got for now
# TODO explain how this works in comments
def sanshoku_doukou_check():
# sanshoku doukou is true if a hand contains a given pon/kan meld in all three non-honor suits
# it is incompatible with any yaku requiring two or more chi melds
# it is worth 2 han if closed and 1 if open
sets = sorted([melds[i].tiles[0:4] for i in range(4) if melds[i].meld_type == 'pon' or melds[i].meld_type == 'kan'])
if len(sets) < 3:
return False
if len(sets) == 3:
if sets[0][1:4] == sets[1][1:4] == sets[2][1:4] and sets[0][0] != sets[1][0] != sets[2][0] != sets[0][0]:
return True
if len(sets) == 4:
suit_check = ''.join(sorted([sets[i][0] for i in range(4)]))
if suit_check not in sanshoku_four_suits: # if this doesn't trigger when it's supposed to, it might be a problem with not putting upper()
return False
for i in range(3):
for j in range(3-i):
sanshoku_four_compare_tiles[i][j] = sets[i][1:4] == sets[j+i+1][1:4]
if suit_check == 'BBMP':
return sanshoku_four_compare_tiles == sanshoku_four_compare_same or sanshoku_four_compare_tiles in sanshoku_four_compare_bbmp
elif suit_check == 'BMMP':
return sanshoku_four_compare_tiles == sanshoku_four_compare_same or sanshoku_four_compare_tiles in sanshoku_four_compare_bmmp
elif suit_check == 'BMPP':
return sanshoku_four_compare_tiles == sanshoku_four_compare_same or sanshoku_four_compare_tiles in sanshoku_four_compare_bmpp
# this is literally just sanshoku_doujun but slightly modified...maybe find a way to merge? not high on priorities list as long as it works
def honroutou_check():
# true if a hand contains only terminals and honor tiles
# this function is only called if the yakuman counter is 0
# therefore, we can assume the hand is neither chinroutou nor tsuuiisou
# if this check finds honroutou is true, then junchanta must be false, as it
# requires at least one non-terminal tile, so its corresponding check is skipped
# honroutou is worth 2 han
if chiitoitsu:
return all([not ct_pairs[i].simple_pair() for i in range(7)])
else:
return all([(not melds[i].is_chi() and not melds[i].simple_meld()) for i in range(4)]) and not std_pair.simple_pair()
def junchanta_check():
# true if all four melds and the pair contain at least one terminal
# this function is only called if the yakuman counter is 0 and chiitoitsu is false
# therefore, we can assume the hand is not chinroutou and we need only check for a terminal in each set and no honors
# this check is skipped if honroutou_check returns True
# junchanta is incompatible with chiitoitsu because there are only six distinct terminals
# junchanta is worth 3 han when closed and 2 han if open
return all([not melds[i].simple_meld() and not melds[i].suit == 'honor' for i in range(4), not std_pair.simple_pair() and not std_pair.suit == 'honor'])
def shousangen_check():
# shousangen requires pons of two dragons and a pair of the third
# this function is only called if the yakuman counter is 0 and chiitoitsu is false
# we can assume the user doesn't input an impossible hand (e.g. two pons of the same dragon)
# therefore, dragon melds and the dragon pair (if they exist) are necessarily all of different dragons
# shousangen is worth 2 han
dragon_melds = [melds[i].tiles for i in range(4) if melds[i].dragon]
return all([std_pair.dragon, len(dragon_melds) == 2])
def flush_check():
# a hand satisfies chinitsu when all tiles belong to a single suit
# a hand satisfies honitsu when all tiles belong to a single suit or are honor tiles
# this function is called only if the yakuman counter is zero, so we can assume the hand is not tsuuiisou
# because sets have no duplicate elements, they can be used to test the presence of suits in the hand
# if there is only one element in the suit set, chinitsu is true
# if there are two elements and one is 'honor', then honitsu is true
# if there are three or four, neither is true
# this function does not return anything, and instead modifies global variables
# which are later used in score determination
# this kinda breaks the conventions we've had so far but it shouldn't be too big a deal
# chinitsu is worth 6 han when closed and 5 when open
# honitsu is worth 3 han when closed and 2 when open
global honitsu_pinzu
global honitsu_souzu
global honitsu_manzu
global chinitsu_pinzu
global chinitsu_souzu
global chinitsu_manzu
global yaku_han
flush_suits = set()
if chiitoitsu:
for i in range(7):
flush_suits.add(ct_pairs[i].suit)
else:
for i in range(4):
flush_suits.add(melds[i].suit)
flush_suits.add(std_pair.suit)
if len(flush_suits) == 1:
if 'pinzu' in flush_suits:
chinitsu_pinzu = True
elif 'souzu' in flush_suits:
chinitsu_souzu = True
elif 'manzu' in flush_suits:
chinitsu_manzu = True
yaku_han += 5
if hand_closed:
yaku_han += 1
elif len(flush_suits) == 2 and 'honor' in flush_suits:
if 'pinzu' in flush_suits:
honitsu_pinzu = True
elif 'souzu' in flush_suits:
honitsu_souzu = True
elif 'manzu' in flush_suits:
honitsu_manzu = True
yaku_han += 2
if hand_closed:
yaku_han += 1
def tanyao_check():
# tanyao is true when all tiles are number tiles 2-8
# it is worth 1 han
if chiitoitsu:
return all([ct_pairs[i].simple for i in range(7)])
if not chiitoitsu:
return all([all([melds[i].simple for i in range(4)]), std_pair.simple])
# suit = [] # come back to this after the rest of the calculator is done
# for i in range(1,10): # creates list of numbers for checking if user has specified more tiles than exist
# for j in range (4): # e.g. tries to specify two melds reading 'P333' when there are only 4 P3 in a set
# suit.append(i)
# j+=1
# print(suit)
# winning hand variables
tiles = ''
wait = ''
hand = []
hand_closed = True
valid_closed = False # to stop user from inputting invalid hand_closed/open information combinations
hand_has_kan = False
tsumo = True
dealer = False
# 1 han yaku
menzen_tsumo = False
pinfu = False
riichi = False
ippatsu = False
iipeikou = False
rinshan = False
chankan = False
haitei = False
houtei = False
tanyao = False
yakuhai_east = False
yakuhai_south = False
yakuhai_west = False
yakuhai_north = False
yakuhai_red = False
yakuhai_white = False
yakuhai_green = False
# 2/1 han yaku
chanta = False
itsuu = False
sanshoku_doujun = False
sanshoku_doukou = False
# 2 han yaku
double_riichi = False
toitoi = False
sanankou = False
sankantsu = False
honroutou = False
shousangen = False
chiitoitsu = False
# 3/2 han yaku
honitsu_pinzu = False
honitsu_souzu = False
honitsu_manzu = False
junchanta = False
# 3 han yaku
ryanpeikou = False
# 6/5 han yaku
chinitsu_pinzu = False
chinitsu_souzu = False
chinitsu_manzu = False
# yakuman
kokushi = False
paarenchan = False
renhou = False
chiihou = False
tenhou = False
chuuren = False
suuankou = False
shousuushi = False
daisangen = False
suukantsu = False
daichisei = False
tsuuiisou = False
chinroutou = False
ryuuiisou = False
daisharin = False
daichikurin = False
daisuurin = False
# double yakuman
kokushi_thirteen = False
chuuren_nine = False
suuankou_tanki = False
daisuushi = False
# scoring variables
yakuman_counter = 0
yaku_han = 0
total_han = 0
fu = 20
meld_fu = [0,0,0,0]
basic_points = 0
tsumo_nondealer_points = 0
tsumo_dealer_points = 0
ron_points = 0
total_points = 0
chombo = False
# board variables
round_wind = ''
personal_wind = ''
invalid_input = "Invalid input. Please re-enter."
chuuren_strings = ['11112345678999','11122345678999','11123345678999','11123445678999','11123455678999','11123456678999','11123456778999','11123456788999','11123456789999']
shousuushi_strings = ['EEENNNSSSWW','EEENNNSSWWW','EEENNSSSWWW','EENNNSSSWWW']
daisuushi_string = 'EEENNNSSSWWW'
daisangen_string = 'GGGHHHRRR'
daichisei_string = 'EEGGHHNNRRSSWW'
daisharin_string = '22334455667788'
itsuu_string = '123456789'
sanshoku_four_suits = ['BBMP','BMMP','BMPP']
sanshoku_four_compare_tiles = [[False,False,False],[False,False],[False]]
sanshoku_four_compare_same = [[True,True,True],[True,True],[True]]
sanshoku_four_compare_bbmp = [[[False,True,True],[False,False],[True]],[[False,False,False],[True,True],[True]]]
sanshoku_four_compare_bmmp = [[[True,False,True],[False,True],[False]],[[False,True,True],[False,False],[True]]]
sanshoku_four_compare_bmpp = [[[True,True,False],[True,False],[False]],[[True,False,True],[False,True],[False]]]
# there HAS to be a better way to do this
print('Japanese Mahjong Point Calculator\nPython Edition\n')
print('1. Ryanmen/Open (two consecutive non-terminal number tiles waiting for a tile on either side)')
print('2. Penchan/Edge (1-2 or 8-9 of a suit waiting for 3 or 7)')
print('3. Shanpon/Double Pair (two pairs waiting for a third tile of either)')
print('4. Kanchan/Closed (two non-consecutive number tiles waiting for the middle number)')
print('5. Tanki/Pair (one tile waiting for pair)')
print('6. 9+ Sided (nine or more possible winning tiles)\n')
wait = str(input('What was the winning wait? '))
while wait not in "123456" or len(wait) != 1:
invalid()
wait = str(input('What was the winning wait? '))
hand_closed = evaluate_yn('hand_closed')
tsumo = evaluate_yn('tsumo')
if tsumo and hand_closed:
menzen_tsumo = True
if wait == '5' and hand_closed:
chiitoitsu = evaluate_yn('chiitoitsu')
print(chiitoitsu)
else:
chiitoitsu = False
if chiitoitsu:
ct_pairs = [Pair() for i in range(7)]
print('Input pairs:')
for i in range(7):
ct_pairs[i].tiles = str(input('Pair ' + str(i+1) + ': '))
while not ct_pairs[i].valid_pair():
invalid()
ct_pairs[i].tiles = str(input('Pair ' + str(i+1) + ': '))
ct_pairs[i].suit = ct_pairs[i].suit_pair()
hand = [ct_pairs[i].tiles for i in range(7)]
print(hand) # merge with previous conditional?
elif not chiitoitsu:
if wait in "56" and hand_closed:
kokushi = evaluate_yn('kokushi')
if kokushi:
yakuman_counter += 1
if wait == "6":
kokushi_thirteen = True
yakuman_counter += 1
if not kokushi:
melds = [Meld() for i in range(4)]
std_pair = Pair()
print('Enter melds. For non-honor melds, use a suit indicator followed by 3 or 4 numbers.')
print('Suits are (P)inzu/coins, souzu/(B)amboo, and (M)anzu/characters.')
print('Honors are (E)ast, (S)outh, (W)est, (N)orth, (R)ed/Chun, White/(H)aku, and (G)reen/Hatsu.')
print('Examples: P123, M555, B9999, HHH, EEEE')
while valid_closed == False:
for i in range(len(melds)):
melds[i].tiles = str(input('Meld ' + str(i+1) + ': '))
while not melds[i].valid_meld():
invalid()
melds[i].tiles = str(input('Meld ' + str(i+1) + ': '))
melds_set = set(melds[i].tiles for i in range(4))
melds[i].suit_meld()
melds[i].type_meld()
melds_types = [melds[i].meld_type for i in range(4)]
melds[i].green_meld()
melds[i].simple_meld()
if not hand_closed:
melds[i].closed_meld()
print(melds[i].tiles, melds[i].suit, melds[i].meld_type, melds[i].closed, melds[i].simple, melds[i].wind, melds[i].dragon, melds[i].green)
if not hand_closed and melds[0].closed == melds[1].closed == melds[2].closed == melds[3].closed == True and tsumo:
print('Invalid input. You cannot win an open hand with four closed melds with tsumo. Please re-input melds.')
continue
valid_closed = True
std_pair.tiles = str(input("Enter pair: "))
while not std_pair.valid_pair():
invalid()
std_pair.tiles = str(input("Enter pair: "))
std_pair.suit_pair()
std_pair.simple_pair()
std_pair.significant_pair()
std_pair.green_pair()
print(std_pair.tiles, std_pair.suit, std_pair.simple, std_pair.wind, std_pair.dragon, std_pair.green, std_pair.significant)
hand = [melds[i].tiles for i in range(4)]
hand.append(std_pair.tiles)
print(hand)
round_wind = evaluate_wind('round_wind')
personal_wind = evaluate_wind('personal_wind')
if personal_wind == 'E' or personal_wind == 'EAST':
dealer = True
bonus_round = evaluate_number('bonus_round')
print(bonus_round)
riichibon = evaluate_number('riichibon')
print(riichibon)
dora = evaluate_number('dora')
print(dora)
if riichibon != 0:
riichi = evaluate_yn('riichi')
if riichi:
double_riichi = evaluate_yn('double_riichi')
ippatsu = evaluate_yn('ippatsu')
if not chiitoitsu and not kokushi and tsumo and hand_has_kan:
rinshan = evaluate_yn('rinshan')
if not rinshan and not tsumo:
chankan = evaluate_yn('chankan')
if not rinshan and not chankan and tsumo and (not ippatsu and not double_riichi):
haitei = evaluate_yn('haitei')
# if haitei:
# yakuman_counter += 1
# TODO this is clearly wrong. I'm not sure why this is a thing, but I'll look into it later.
if not rinshan and not chankan and not haitei and not tsumo and (not ippatsu and not double_riichi):
houtei = evaluate_yn('houtei')
if not dealer and not riichi and not rinshan and not chankan and not haitei and not houtei and hand_closed and not hand_has_kan:
if tsumo:
chiihou = evaluate_yn('chiihou')
if chiihou:
yakuman_counter += 1
if not tsumo:
renhou = evaluate_yn('renhou')
if renhou:
yakuman_counter += 1
if dealer and not riichi and not rinshan and not chankan and not haitei and not houtei and tsumo and hand_closed and not hand_has_kan:
tenhou = evaluate_yn('tenhou')
if tenhou:
yakuman_counter += 1
paarenchan = evaluate_yn('paarenchan')
if paarenchan:
yakuman_counter += 1
# check for yakuman
if not kokushi:
if chiitoitsu:
if daichisei_check():
tsuuiisou = True
daichisei = True
yakuman_counter += 2
elif not chiitoitsu:
if tsuuiisou_check():
tsuuiisou = True
yakuman_counter += 1
if chuuren_check():
chuuren = True
yakuman_counter += 1
if wait == '6':
chuuren_nine = True
yakuman_counter += 1
if not chuuren:
if hand_closed and melds[0].closed == melds[1].closed == melds[2].closed == melds[3].closed == True:
if melds_types.count('chi') == 0:
suuankou = True
yakuman_counter += 1
if wait == '5':
suuankou_tanki = True
yakuman_counter += 1
if shousuushi_check():
shousuushi = True
yakuman_counter += 1
elif daisuushi_check():
daisuushi = True
yakuman_counter += 2
if daisangen_check():
daisangen = True
yakuman_counter += 1
if melds_types.count('kan') == 4:
suukantsu = True
yakuman_counter += 1
if not tsuuiisou and not shousuushi and not daisuushi and not daisangen:
if chinroutou_check():
chinroutou = True
yakuman_counter += 1
if ryuuiisou_check():
ryuuiisou = True
yakuman_counter += 1
if daisharin_check():
if melds[0].suit == 'pinzu':
daisharin = True
elif melds[0].suit == 'souzu':
daichikurin = True
elif melds[0].suit == 'manzu':
daisuurin = True
yakuman_counter += 1
# check non-yakuman yaku if no yakuman
if yakuman_counter == 0:
if riichi:
yaku_han += 1
if double_riichi:
yaku_han += 1
if ippatsu:
yaku_han += 1
if chiitoitsu:
yaku_han += 2
if menzen_tsumo:
yaku_han += 1
if haitei:
yaku_han += 1
if houtei:
yaku_han += 1
if rinshan:
yaku_han += 1
if chankan:
yaku_han += 1
flush_check()
if tanyao_check():
tanyao = True
yaku_han += 1
if chiitoitsu:
if honroutou_check():
yaku_han += 2
elif not chiitoitsu:
if wait == '1' and hand_closed and melds_types.count('chi') == 4 and not std_pair.significant_pair():
pinfu = True # should i write a function for pinfu_check()?
yaku_han += 1
if itsuu_check():
itsuu = True
yaku_han += 1
if hand_closed:
yaku_han += 1
if hand_closed:
if iipeikou_ryanpeikou_check() == 2:
ryanpeikou = True
yaku_han += 3
elif iipeikou_ryanpeikou_check() == 1:
iipeikou = True
yaku_han += 1
if sanshoku_doujun_check():
sanshoku_doujun = True
yaku_han += 1
if hand_closed:
yaku_han += 1
if melds_types.count('chi') == 0:
toitoi = True
yaku_han += 2
if sum(1 for meld in melds if meld.meld_type == 'pon' and meld.closed) == 3:
sanankou = True
yaku_han += 2
if sanshoku_doukou_check():
sanshoku_doukou = True
yaku_han += 2
if melds_types.count('kan') == 3:
sankantsu = True
yaku_han += 2
if 'EEE' in melds_set or 'EEEE' in melds_set:
if round_wind == 'E' or personal_wind == 'E':
yakuhai_east = True
if round_wind == 'E':
yaku_han += 1
if personal_wind == 'E':
yaku_han += 1
if 'SSS' in melds_set or 'SSSS' in melds_set:
if round_wind == 'S' or personal_wind == 'S':
yakuhai_south = True
if round_wind == 'S':
yaku_han += 1
if personal_wind == 'S':
yaku_han += 1
if 'WWW' in melds_set or 'WWWW' in melds_set:
if round_wind == 'W' or personal_wind == 'W':
yakuhai_west = True
if round_wind == 'W':
yaku_han += 1
if personal_wind == 'W':
yaku_han += 1
if 'NNN' in melds_set or 'NNNN' in melds_set:
if round_wind == 'N' or personal_wind == 'N':
yakuhai_north = True
if round_wind == 'N':
yaku_han += 1
if personal_wind == 'N':
yaku_han += 1
if 'RRR' in melds_set or 'RRRR' in melds_set:
yakuhai_red = True
yaku_han += 1
if 'HHH' in melds_set or 'HHHH' in melds_set:
yakuhai_white = True
yaku_han += 1
if 'GGG' in melds_set or 'GGGG' in melds_set:
yakuhai_green = True
yaku_han += 1
if sum(1 for meld in melds if meld.simple_meld()) == 0 and not std_pair.simple_pair() and melds_types.count('chi') >= 1:
chanta = True # chanta_check()?
yaku_han += 1 # careful, chanta can be overwritten by junchanta or honroutou
if hand_closed:
yaku_han += 1
if chanta:
if honroutou_check(): # TODO include another chanta check for chiitoitsu since chanta and chiitoi are incompatible
honroutou = True
chanta = False
if not hand_closed:
yaku_han += 1
elif junchanta_check(): # if program reaches this point, hand is definitely not chinroutou
junchanta = True
chanta = False
yaku_han += 1
if shousangen_check():
shousangen = True
yaku_han += 2
if yakuman_counter == 0:
total_han = yaku_han + dora
if total_han < 5:
if chiitoitsu:
fu += 5
else:
if pinfu:
if not tsumo:
fu += 10
else:
if wait == 2 or wait == 4 or wait == 5:
fu += 2
if hand_closed and not tsumo:
fu += 10
if tsumo:
fu += 2
if not hand_closed and not tsumo:
fu += 0
if std_pair.significant_pair():
fu += 2
if std_pair.tiles[0] == round_wind == personal_wind:
fu += 2
for i in range(4):
if melds[i].meld_type != 'chi':
meld_fu[i] = 2
if not melds[i].simple_meld():
meld_fu[i] *= 2
if melds[i].closed:
meld_fu[i] *= 2
if melds[i].meld_type == 'kan':
meld_fu[i] *= 4
fu += sum(meld_fu)
fu = 10 * ceil(fu/10)
basic_points = fu * pow(2, (2 + han))
if basic_points > 2000:
basic_points = 2000
elif total_han == 5:
basic_points = 2000
elif total_han in range(6,8):
basic_points = 3000
elif total_han in range(8,11):
basic_points = 4000;
elif total_han in range(11,13):
basic_points = 6000
elif total_han >= 13:
basic_points = 8000
if yakuman_counter > 0:
if dealer:
total_points = yakuman_counter * 4 * 8000 * 1.5
if tsumo:
tsumo_nondealer_points = total_points / 3
else:
ron_points = total_points
else:
total_points = yakuman_counter * 4 * 8000
if tsumo:
tsumo_nondealer_points = total_points / 4
tsumo_dealer_points = total_points / 2
else:
ron_points = total_points
else:
if dealer:
if tsumo:
tsumo_nondealer_points = 100 * ceil((basic_points * 2) / 100)
total_points = 3 * tsumo_nondealer_points
else:
ron_points = 100 * ceil((basic_points * 6) / 100)
total_points = ron_points
else:
if tsumo:
tsumo_nondealer_points = 100 * ceil(basic_points / 100)
tsumo_dealer_points = 100 * ceil((basic_points * 2) / 100)
total_points = tsumo_dealer_points + (2 * tsumo_nondealer_points)
else:
ron_points = 100 * ceil((basicPointsFloat * 4) / 100)
total_points = ron_points
print('\n')
if yakuman_counter > 0:
if suuankou:
if suuankou_tanki:
print('Suuankou Tanki Machi: Double Yakuman')
else:
print('Suuankou: Yakuman')
if kokushi:
if kokushi_thirteen:
print('Kokushi Musou Juusanmen Machi: Double Yakuman')
else:
print('Kokushi Musou: Yakuman')
if daisangen:
print('Daisangen: Yakuman')
if shousuushi:
print('Shousuushi: Yakuman')
if daisuushi:
print('Daisuushi: Double Yakuman')
if tsuuiisou and not daichisei:
print('Tsuuiisou: Yakuman')
if daichisei:
print('Daichisei: Double Yakuman')
if chinroutou:
print('Chinroutou: Yakuman')
if ryuuiisou:
print('Ryuuiisou: Yakuman')
if daisharin:
print('Daisharin: Yakuman')
if daichikurin:
print('Daichikurin: Yakuman')
if daisuurin:
print('Daisuurin: Yakuman')
if chuuren:
if chuuren_nine:
print('Junsei Chuuren Poutou: Double Yakuman')
else:
print('Chuuren Poutou: Yakuman')
if suukantsu:
print('Suukantsu: Yakuman')
if paarenchan:
print('Paarenchan: Yakuman')
if renhou:
print('Renhou: Yakuman')
if chiihou:
print('Chiihou: Yakuman')
if tenhou:
print('Tenhou: Yakuman')
print('\n')
if yakuman_counter == 1:
print('Yakuman')
elif yakuman_counter == 2:
print('Double Yakuman')
elif yakuman_counter == 3:
print('Triple Yakuman')
elif yakuman_counter >= 4:
print('%dx Yakuman' %yakuman_counter)
if yakuman_counter == 0:
if riichi:
if double_riichi:
print('Double Riichi: 2 Han')
if not double_riichi:
print('Riichi: 1 Han')
if ippatsu:
print('Ippatsu: 1 Han')
if chiitoitsu:
print('Chiitoitsu: 2 Han')
if menzen_tsumo:
print('Menzen Tsumo: 1 Han')
if haitei:
print('Haitei Raoyue: 1 Han')
if houtei:
print('Houtei Raoyui: 1 Han')
if rinshan:
print('Rinshan Kaihou: 1 Han')
if chankan:
print('Chankan: 1 Han')
if pinfu:
print('Pinfu: 1 Han')
if itsuu:
if hand_closed:
print('Itsuu (Closed): 2 Han')
else:
print('Itsuu (Open): 1 Han')
if iipeikou:
if ryanpeikou:
print('Ryanpeikou: 3 Han')
else:
print('Iipeikou: 1 Han')
if sanshoku_doujun:
if hand_closed:
print('Sanshoku Doujun (Closed): 2 Han')
else:
print('Sanshoku Doujun (Open) 1 Han')
if toitoi:
print('Toitoi: 2 Han')
if sanankou:
print('Sanankou: 2 Han')
if sanshoku_doukou:
print('Sanshoku Doukou: 2 Han')
if sankantsu:
print('Sankantsu: 2 Han')
if tanyao:
print('Tanyao: 1 Han')
if yakuhai_east:
if round_wind == personal_wind:
print('Double Ton: 2 Han')
else:
print('Ton: 1 Han')
if yakuhai_south:
if round_wind == personal_wind:
print('Double Nan: 2 Han')
else:
print('Nan: 1 Han')
if yakuhai_west:
if round_wind == personal_wind:
print('Double Sha: 2 Han')
else:
print('Sha: 1 Han')
if yakuhai_north:
if round_wind == personal_wind:
print('Double Pei: 2 Han')
else:
print('Pei: 1 Han')
if yakuhai_green:
print('Hatsu: 1 Han')
if yakuhai_red:
print('Chun: 1 Han')
if yakuhai_white:
print('Haku: 1 Han')
if chanta:
if hand_closed:
print('Chanta (Closed): 2 Han')
else:
print('Chanta (Open): 1 Han')
if junchanta:
if hand_closed:
print('Junchan (Closed): 3 Han')
else:
print('Junchan (Open): 2 Han')
if honroutou:
print('Honroutou: 2 Han')
if shousangen:
print('Shousangen: 2 Han')
if honitsu_pinzu:
if hand_closed:
print('Pinzu Honitsu (Closed): 3 Han')
else:
print('Pinzu Honitsu (Open): 2 Han')
if honitsu_souzu:
if hand_closed:
print('Souzu Honitsu (Closed): 3 Han')
else:
print('Souzu Honitsu (Open): 2 Han')
if honitsu_manzu:
if hand_closed:
print('Manzu Honitsu (Closed): 3 Han')
else:
print('Manzu Honitsu (Open): 2 Han')
if chinitsu_pinzu:
if hand_closed:
print('Pinzu Chinitsu (Closed): 6 Han')
else:
print('Pinzu Chinitsu (Open): 5 Han')
if chinitsu_souzu:
if hand_closed:
print('Souzu Chinitsu (Closed): 6 Han')
else:
print('Souzu Chinitsu (Open): 5 Han')
if chinitsu_manzu:
if hand_closed:
print('Manzu Chinitsu (Closed): 6 Han')
else:
print('Manzu Chinitsu (Open): 5 Han')
if dora > 0:
if dora < 10:
print('%d Dora: %d Han' %(dora, dora))
else:
print('%d Dora: %d Han' %(dora, dora))
print('\n')
if yakuman_counter == 0 and yaku_han == 0:
chombo = True
print('Invalid hand: no yaku!')
if dealer:
print('Chombo Penalty: -4000 All')
else:
print('Chombo Penalty: -2000/-4000')
if not chombo and yakuman_counter == 0:
if total_han < 5:
print('%d Han %d Fu' %(total_han, fu))
elif total_han>= 5:
print('%d Han' %total_han)
if basic_points == 2000:
print('Mangan')
elif basic_points == 3000:
print('Haneman')
elif basic_points == 4000:
print('Baiman')
elif basic_points == 6000:
print('Sanbaiman')
elif basic_points == 8000:
print('Yakuman')
if not chombo:
if bonus_round > 0:
print('Bonus %d +%d' %(bonus_round, (300 * bonus_round)))
if riichibon > 0:
print('Riichi Bet(s) +%d' %(riichibon*1000))
if dealer:
if tsumo:
print('%d All\n' %(tsumo_nondealer_points + (100 * bonus_round)))
else:
print('%d\n' %(ron_points + (300 * bonus_round)))
else:
if tsumo:
print('%d/%d\n' %((tsumo_nondealer_points + (100 * bonus_round)),(tsumo_dealer_points + (100 * bonus_round))))
else:
print('%d\n' %(ron_points + (300 * bonus_round)))
if not chombo:
print('Total Points Earned: %d\n' %(total_points + (300 * bonus_round) + (1000 * riichibon)))
else:
print('No Points Earned \n')
|
f6ab7a2275114e99e412b22cd94231f0380b5131
|
csrajath/random_programming_problems
|
/median.py
| 580 | 4.34375 | 4 |
# Find the median of two sorted arrays
"""
1. combine the lists
2. find the length
3. if length is odd, the element at (len/2)+1 position is the median
4. if length is even, the average of the element at (len/2) and (len/2)+1 will be the median
"""
def median_find(arr1, arr2):
arr3 = arr1 + arr2
if len(arr3) % 2 == 1:
median = arr3[(int(len(arr3)/2))]
else:
m1 = arr3[int(len(arr3)/2)-1]
m2 = arr3[(int(len(arr3)/2))]
median = (m1+m2)/2
return median
print(median_find([1,2,3,4,5],[6,7,8,9]))
print(median_find([10,20],[30,40]))
|
46546e4f7768b59a42139ec47d5db2a6534f9260
|
asherthechamp/Coding-Problems
|
/Problem Set Two/maximum_stack.py
| 567 | 3.921875 | 4 |
# Returns The Maximum value in a stack
class MaxStack:
def __init__(self):
self.Stack = []
# Fill this in.
def push(self, val):
self.Stack.append(val)
def pop(self):
if (len(self.Stack) != 0):
self.Stack.pop(-1)
def max(self):
maximum = self.Stack[0]
for i in range(1, len(self.Stack)):
if (self.Stack[i] > maximum):
maximum = self.Stack[i]
return maximum
# Fill this in.
s = MaxStack()
s.push(1)
s.push(2)
s.push(3)
s.push(2)
print (str(s.max()))
# 3
s.pop()
s.pop()
print (str(s.max()))
# 2
|
365149f11e1a8162b4232d13d8f15761d36893a7
|
oversj96/NumericalMethodsHW
|
/Homework 2/FixedPointTest3.py
| 513 | 3.609375 | 4 |
# Author: Justin Overstreet
# Date: August 31, 2019
# Program: Fixed-point iteration test method
# Purpose: Numerical Methods Homework 2, Problem 3a, solution finding.
import math
# Math expression to evaluate.
f = lambda x: math.pi + math.sin(x)/2
# Initial variables.
p0 = 0
n = 30
tol = 10e-2
itr = 1
# Iterative loop.
while(itr <= n):
p = f(p0)
if (abs(p-p0) < tol):
print(p)
break
else:
itr = itr + 1
p0 = p
# Resulting solution after 3 iterations: P = 3.141592653589793
|
6213c5b1a746429a66fa3193b3dc4adb37dd61e4
|
standrewscollege2018/2021-year-11-python-classwork-JustineLeeNZ
|
/lists-inside-lists.py
| 2,796 | 4.59375 | 5 |
# examples of lists inside lists
# *** create a master list that contains other sub-lists ***
# the master list starts and ends with [] brackets which all the sublists sit inside
# each sub-list must be enclosed in [] brackets with commas between the [] brackets
# items inside each sub-list are separated by commas
# list of client details
client_list = [["John Smith",16],["Bob O'Roberts",18]]
# *** print an entire sublist ***
# print first client
# note the [] and commas - UGLY - only use this for debugging
print(client_list[0])
# *** print an individual sub-list item ***
# print the name of the first client
print(client_list[0][0])
# print the age of the first client
print(client_list[0][1])
# print the name of the second client
print(client_list[1][0])
# print the age of the second client
print(client_list[1][1])
# *** ask user for an index and print client details for that sub-list ***
# ask user for input
index = int(input("Enter a number: "))
# print client name
print(client_list[index][0])
# print client age
print(client_list[index][1])
# print name and age with nice formatting
print("Name: {} Age: {}".format(client_list[index][0], client_list[index][1]))
# *** print each name and age from the list ***
# range starts at zero and uses length of list for stop value
# use index variable to select next sub-list each time for loop runs
# use actual numbers to specify item inside sub-list e.g. name has index 0
for index in range(0, len(client_list)):
print(client_list[index][0], client_list[index][1])
# *** print a numbered list ***
# use index+1 to print numbered list
# use .format() to combine variable values and unchanging text
for index in range(0, len(client_list)):
print("{}. Name: {} Age: {}".format(index+1, client_list[index][0], client_list[index][1]))
# *** add new client ***
# ask user for client details
name = input("Enter client name: ")
age = int(input("Enter client age: "))
# use append() to add new client details as sub-list
# variables with new info need to be enclosed in [] brackets
client_list.append([name,age])
# print entire list to check new client added
print(client_list)
# *** delete an entire client sub-list ***
# ask user for index of sub-list to delete
index = int(input("Enter index of client to delete: "))
# delete sub-list that matches specified index
# note that del comes before the listname and there is a space between them
del client_list[index]
# print entire list to check client deleted
print(client_list)
# *** update existing client details ***
# update name for first client
client_list[0][0] = "Jenny Smith"
# print entire list to check client name updated
print(client_list)
# update age for first client
client_list[0][1] = 100
# print entire list to check client age updated
print(client_list)
|
d90b437f89b79865f69a7d9cbb9cfc569128796c
|
alidashtii/python-assignments
|
/ex3.py
| 103 | 3.609375 | 4 |
a = [ 1 , 1, 2, 3, 5 , 8 , 13 , 21, 34, 55 , 89]
b = []
for i in a:
if i < 5:
b.append(i)
print b
|
eaa5932b2380b7f348a3a029ffedde356006e58d
|
peraktong/LEETCODE_Jason
|
/709. To Lower Case.py
| 412 | 3.5 | 4 |
class Solution:
def toLowerCase(self, str: 'str') -> 'str':
return str.lower()
"""
class Solution:
def toLowerCase(self, str):
#type str: str
#rtype: str
res = ""
for s in str:
if ord('A') <= ord(s) <= ord('A')+25:
res += chr(ord(s)-ord('A')+ord('a'))
else:
res += s
return res
"""
|
c29b902312b959b231e8e5c27055549f268fea91
|
chin8628/Pre-Pro-IT-Lardkrabang-2558
|
/Prepro-Onsite/W4_D2_UltimaEazy06-MamaAddDict.py
| 305 | 3.5625 | 4 |
""" W4_D2_UltimaEazy06-MamaAddDict """
def main():
""" Giv me kongo I will giv u Mango """
inputn = int(input())
data = {}
for _ in range(inputn):
inputkey = input().split(" ")
data[inputkey[0]] = inputkey[1]
print(sorted(data))
print(sorted(data.values()))
main()
|
eb523bde2cec5c42e24afb5e9100e4a6d4894eb9
|
OnewayYoun/studygroup-for-codingTest
|
/06주차/1번(박유나).py
| 2,130 | 3.5625 | 4 |
def Exit(): # 종료 함수
print(0)
exit()
def check1(arr): # 사다리 확인
count=0
for n in range(1, N+1):
newN=n
for h in range(1, H+1):
if arr[h][newN]==0 or arr[h][newN]==-1: continue
newN=arr[h][newN] # 새로운 값 넣기
if n!= newN: #끝과 끝이 다르다면,
count+=1 #카운팅
if count==0:
return True
return False
def wall(cnt):
global ans
if cnt!=0 and check1(arr): # 가로선 개수가 0이 아니고, 사다리 확인 시 true인 경우,
ans=min(cnt, ans) # 최소값 찾기
if cnt==3: #가로선 개수가 3개라면, 종료
return
for n in range(1, N): # 1 ~ (N-1)
for h in range(1, H+1): # 1 ~ H
if (arr[h][n]!=0 or arr[h][n+1]!=0):continue # 0이 아니라면, 돌아감
arr[h][n]=n+1 # 가로선 설정
arr[h][n+1]=n # 가로선 설정
wall(cnt+1) # 가로선 개수 증가
arr[h][n]=0 # 가로선 해제
arr[h][n+1]=0 # 가로선 해제
""" 0. 입력받기 """
N, M, H=map(int, input().split()) # 세로선 개수, 가로선 개수, 높이 개수
if M==0: Exit() # 가로선 개수가 0이라면, 종료
arr = [[0]*(N+1) for _ in range(H+1)] # 사다리 표기(0인덱스 사용하지 않음)
""" 1. 기존 사다리 저장 """
for _ in range(M):
i, j = map(int, input().split())
arr[i][j]=j+1 # j+1 행값 넣음
arr[i][j+1]=j # j 행값 넣음
if 1<=(j-1) and arr[i][j-1]==0: arr[i][j-1]=-1 # 가로선이 연장하지 않기 위해 금지 표기
if (j+2)<=N and arr[i][j+2]==0: arr[i][j+2]=-1 # 가로선이 연장하지 않기 위해 금지 표기
if check1(arr): Exit() # 사다리 확인 후, true라면 종료
""" 2. 사다리 확인 """
ans=4 # 정답이 4이상으로 나올 수 없기 때문에
wall(0) # 가로선 설정 및 해제
if ans==4: # 최소값이 4라면,
print(-1) # 가로선을 놓아도 답이 될 수 없다고 판단하여 -1 출력
else:
print(ans) # 가로선을 놓아서 답이 된다면, 놓은 가로선 개수 출력
|
0f11a64d5bb5a8191a8f233bb15bf591cddff5f3
|
xjchen2008/leakage_cancellation_python
|
/gradient_descent_v3.py
| 1,847 | 4.125 | 4 |
# https://towardsdatascience.com/gradient-descent-in-python-a0d07285742f
import numpy as np
import matplotlib.pyplot as plt
def cal_cost(theta, X, y):
m = len(y)
predictions = X.dot(theta)
A = predictions - y
cost = 1.0 / (2 * m) * np.dot(np.conj(A).T, A)[0][0]
return cost
def gradient_descent(X, y, theta, learning_rate=0.01, iterations=100):
m = len(y)
cost_history = np.zeros(iterations)
theta_history = np.zeros((iterations, len(theta)))
for it in range(iterations):
prediction = np.dot((X), theta)
error = prediction - y
theta = theta - (2.0 / m) * learning_rate * np.dot(np.conj(X.T),error ) # change to CPP
#theta = theta - (1.0 / m) * learning_rate * np.dot(np.conj(X.T), error ) # change to CPP
theta_history[it, :] = theta.T
cost_history[it] = cal_cost(theta, X, y)
return theta, cost_history, theta_history
def stocashtic_gradient_descent(X, y, theta, learning_rate=0.01, iterations=10):
'''
X = Matrix of X with added bias units
y = Vector of Y
theta=Vector of thetas np.random.randn(j,1)
learning_rate
iterations = no of iterations
Returns the final theta vector and array of cost history over no of iterations
'''
m = len(y)
cost_history = np.zeros(iterations)
for it in range(iterations):
cost = 0.0
for i in range(m):
rand_ind = np.random.randint(0, m)
X_i = X#[rand_ind, :].reshape(1, X.shape[1])
y_i = y[rand_ind].reshape(1, 1)
prediction = np.dot(X_i, theta)
theta = theta - (1 / m) * learning_rate * np.dot(np.conj(X_i.T), prediction - y_i )
#(X_i.T.dot((prediction - y_i)))
cost += cal_cost(theta, X_i, y_i)
cost_history[it] = cost
return theta, cost_history
|
5f26b14eeaa4c344d684a92fd5ec86471bfdb0ec
|
EugeneStill/PythonCodeChallenges
|
/ll_is_palindrome.py
| 1,420 | 3.828125 | 4 |
import unittest
import helpers.node as nd
import helpers.linked_list as linked_list
class LLPalindrome(unittest.TestCase):
def is_ll_palindrome(self, head):
# are values of linked list a palindrome
fast = slow = head
# find the mid node
while fast and fast.next:
fast = fast.next.next
slow = slow.next
# reverse the second half
back_node = None
# consider renaming the while loop variables for clarity
while slow:
nxt = slow.next
slow.next = back_node
back_node = slow
slow = nxt
# compare the first and second half nodes
while back_node: # while node and head:
if back_node.value != head.value:
return False
back_node = back_node.next
head = head.next
return True
def test_is_ll_palindrome(self):
pal_list = linked_list.LinkedList()
one_val_list = linked_list.LinkedList()
not_pal_list = linked_list.LinkedList()
pal_list.create_linked_list([1, 2, 3, 2, 1])
one_val_list.create_linked_list([1])
not_pal_list.create_linked_list([1, 2, 3, 2, 4])
self.assertTrue(self.is_ll_palindrome(pal_list.head))
self.assertTrue(self.is_ll_palindrome(one_val_list.head))
self.assertFalse(self.is_ll_palindrome(not_pal_list.head))
|
f04ad5404cf5e0699b8e2c3484c3bb3b4e77f66c
|
joegalaxian/gameoflife
|
/gameoflife.py
| 3,649 | 3.546875 | 4 |
#!/usr/bin/env python
import random
import time
import os
import sys
DEAD = '.'
LIVING = '@'
class Game(object):
def __init__(self, x=30, y=30, population_percentage=30, fps=2):
self.generation = 0
self.population = 0
self.x = x # board's x axis
self.y = y # board's y axis
self.fps = fps # frames per second
# create board
self.board = self.empty_board(self.x, self.y)
# populate board
for i in range(int(self.x*self.y*population_percentage/100)):
while True:
rx = random.randint(0, self.x -1)
ry = random.randint(0, self.y -1)
if self.board[ry][rx] == DEAD:
self.board[ry][rx] = LIVING
break
# refresh population
self.refresh_population()
def run(self):
while self.population:
self.render()
self.tick()
time.sleep(1.0/self.fps)
def empty_board(self, x, y):
return [ [DEAD for ix in range(x)] for iy in range(y) ]
def render(self):
# Clear screen
if sys.platform in ('linux2', 'linux', 'unix', 'posix', 'darwin'):
os.system('clear')
elif sys.platform in ('win32', 'win64', 'cywin'):
os.system('cls')
# Print title and stats
print("Conway's Game Of Life - @joegalaxian")
print("Board size: %dx%d - Generation: %d - Population: %d" % (self.x, self.y, self.generation, self.population))
# Print board
result = ''
for line in self.board:
for cell in line:
result += str(cell) + ' '
result += '\n'
result = result[:-1]
print(result)
def tick(self):
"""
Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent.
At each step in time, the following transitions occur:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with two or three live neighbours lives on to the next generation.
3. Any live cell with more than three live neighbours dies, as if by overpopulation.
4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
"""
# calculate next generation
next_generation_board = self.empty_board(self.x, self.y)
for iy in range(self.y):
for ix in range(self.x):
cell = self.board[iy][ix]
neig = self.living_neighbours(ix, iy)
new_cell = DEAD
if cell == LIVING and neig < 2: new_cell = DEAD
elif cell == LIVING and neig in(2, 3): new_cell = LIVING
elif cell == LIVING and neig > 3: new_cell = DEAD
elif cell == DEAD and neig == 3: new_cell = LIVING
next_generation_board[iy][ix] = new_cell
# transit to next generation
self.board = next_generation_board[:] # flip board
self.generation += 1 # increase generation
self.refresh_population() # refresh population
def refresh_population(self):
self.population = 0
for line in self.board:
self.population += line.count(LIVING)
def living_neighbours(self, x, y):
r = 0
# count living neighbours from previous line
try:
if (self.board[y-1][x-1] == LIVING): r +=1
except:
pass
try:
if (self.board[y-1][x] == LIVING): r +=1
except:
pass
try:
if (self.board[y-1][x+1] == LIVING): r +=1
except: pass
# count living neighbours from same line
try:
if (self.board[y][x-1] == LIVING): r +=1
except: pass
try:
if (self.board[y][x+1] == LIVING): r +=1
except: pass
# count living neighbours from next line
try:
if (self.board[y+1][x-1] == LIVING): r +=1
except: pass
try:
if (self.board[y+1][x] == LIVING): r +=1
except: pass
try:
if (self.board[y+1][x+1] == LIVING): r +=1
except: pass
return r
if __name__ == "__main__":
game = Game()
game.run()
|
3dffe9f32182da692894c7a0328f1a36fde4eef3
|
xuyichen2010/Leetcode_in_Python
|
/211_add_and_search_word.py
| 1,498 | 3.953125 | 4 |
# https://leetcode.com/problems/add-and-search-word-data-structure-design/discuss/59725/Python-easy-to-follow-solution-using-Trie.
# O(N*M) N = num of words M = length of longest string
# O(N*K) N = num of nodes and K = size of the alphabet
# When encounter a "." search through all .values of children
class TrieNode:
def __init__(self):
self.children = {}
self.isEndOfWord = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.isEndOfWord = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure.
A word could contain the dot character '.' to represent any one letter.
"""
node = self.root
self.res = False
self.dfs(node, word)
return self.res
def dfs(self, node, word):
if not word:
if node.isEndOfWord:
self.res = True
return
if word[0] == ".":
for n in node.children.values():
self.dfs(n, word[1:])
else:
node = node.children.get(word[0])
if node is None:
return
self.dfs(node, word[1:])
|
b1bd0f33481d71a5dfe18716dd94d76bd3d04c24
|
AdamOtto/cmput291mp2
|
/conditions.py
| 6,963 | 3.84375 | 4 |
from data_retrieval import *
'''
A set of queries produces a conditions list, with the following spec for each condition:
[qtype, info...]
where each condition by qtype looks like:
[TEXT, prefix?, term]
[NAME, prefix?, term]
[LOCATION, prefix?, term]
[GENERAL, term]
[DATEEXACT, year, month, day]
[DATELESS, year, month, day]
[DATEGREATER, year, month, day]
prefix? is True if a prefix term, False if not
term is a string
year, month and day are integers
and the qtypes are enumerated as:
'''
INVALID = -1
TEXT = 1
NAME = 2
LOCATION = 3
GENERAL = 4
DATEEXACT = 5
DATELESS = 6
DATEGREATER = 7
def cleanConditions(conditions):
'''
Takes a list of conditions and removes redundant conditions
1. if multiple DATEEXACT conditions are present and the dates are not equal make the conditions list = None
2. removes redundant greater or less than conditions
THIS RELIES ON THE FACT THAT THE CONSTANTS FOR QTYPE ARE ENUMERATED AS LISTED IN THE ABOVE SPEC
Return the cleaned conditions list
If the conditions are found to be condtradictory the result is None
'''
conditions.sort()
#due to GREATER conditions, this is the minimum date of a query
minYear = None
minMonth = None
minDay = None
#due to LESS conditions, this is the maximum date of a query
maxYear = None
maxMonth = None
maxDay = None
for con in conditions:
if con[0] == DATEGREATER:
#invalidate Date> if its date is less than the current highest Date> date, the min date.
if minYear == minMonth == minDay == None:
minYear = con[1]
minMonth = con[2]
minDay = con[3]
elif (con[1] < minYear or
(con[1] == minYear and con[2] < minMonth) or
(con[1] == minYear and con[2] == minMonth and con[3] <= minDay)):
print("Redundant DATEGREATER")
con[0] = INVALID
else:
minYear = con[1]
minMonth = con[2]
minDay = con[3]
elif con[0] == DATELESS:
#invalid Date< if its date is greater than the current lowest Date< date, the max date.
if maxYear == maxMonth == maxDay == None:
maxYear = con[1]
maxMonth = con[2]
maxDay = con[3]
elif (con[1] > maxYear or
(con[1] == maxYear and con[2] > maxMonth) or
(con[1] == maxYear and con[2] == maxMonth and con[3] >= maxDay)):
print("Redundant DATELESS")
con[0] = INVALID
else:
maxYear = con[1]
maxMonth = con[2]
maxDay = con[3]
#The whole query is invalid if the min date is greater than the max date
if (minYear is not None and maxYear is not None and
minYear >= maxYear and minMonth>= maxMonth and minDay >= maxDay):
print("You appear to have entered a DATELESS that is less than a DATEGREATER, query invalidated")
return None
#At this point in the cleaning, we can be certain
#that there is a max of 1 dateless and 1 dategreater condition each, whose dates are stored already.
#remove redundant exact dates
exactYear = None
exactMonth = None
exactDay = None
for con in conditions:
if con[0] == DATEEXACT:
if exactYear == exactMonth == exactDay == None:
#first exactdate condition, set the exact date
exactYear = con[1]
exactMonth = con[2]
exactDay = con[3]
elif exactYear == con[1] and exactMonth == con[2] and exactDay == con[3]:
#redundant exactdate condition, invalidate condition
con[0] = INVALID
else:
#contradictory exactdates, all conditions invalid
print("You have entered two contradicting DATEEXACT dates, query invalidated")
return None
#We now have a maximum of 1 of each date type query, the Date> and Date< have
#been bounds checked, all that remains is a bounds check on the exact vs < and >
if exactYear is not None:
if minYear is not None:
if (exactYear < minYear or
(exactYear == minYear and exactMonth < minMonth) or
(exactYear == minYear and exactMonth == minMonth and exactDay < minDay)):
print("You have entered an DATEEXACT less than a DATEGREATER, query invalidated")
return None
if maxYear is not None:
if (exactYear > maxYear or
(exactYear == maxYear and exactMonth > maxMonth) or
(exactYear == maxYear and exactMonth == maxMonth and exactDay > maxDay)):
print("You have entered an DATEEXACT more than a DATELESS, query invalidated")
return None
# If we made it this far, there is a single valid dateexact, all other date conditions are invalid
for con in conditions:
if con[0] == DATELESS or con[0] == DATEGREATER:
con[0] = INVALID
#Invalid dates parsed out, we now sort the list from least likely to have large outputs, to most
def sortKey(condition):
'''
Given a condition, returns a tuple of values that when sorted will make the least likely
to have large outputs condition come before those that are more likely.
The key is a list of 5 values, if a key value doesn't apply, it's value is 0
[is not an exact query, -(term length), year, month, day]
'''
if condition[0] in [TEXT, NAME, LOCATION]:
if condition[1] == True:
return [1, -len(condition[2]), 0, 0, 0]
return [0, -len(condition[2]), 0, 0, 0]
if condition[0] == DATEEXACT:
return [0, 0, condition[1], condition[2], condition[3]]
if condition in [DATELESS, DATEGREATER]:
return [1, 0, condition[1], condition[2], condition[3]]
return [2, 0, 0, 0, 0] #For INVALID queries
#create a new list of conditions, sorted by the above criteria
output = sorted(conditions, key = sortKey)
return output
def parseConditions(conditions, te_db, te_cur, da_db, da_cur):
'''
Given a list of conditions, parses each one using Dyllan's query searching functions.
To avoid too much memory usage, will get a query's list, then if there is another query
it will AND it with that queries list before continuing.
'''
if conditions == []:
#empty conditions, no need to do anything
return []
first_time = True
# For every condition, get the list of matching tweet ids and then itersect it with the all found tweet ids thusfar
for con in conditions:
current_results = []
if con[0] == TEXT:
current_results = full_text(con[2], con[1], te_db, te_cur)
elif con[0] == NAME:
current_results = full_name(con[2], con[1], te_db, te_cur)
elif con[0] == LOCATION:
current_results = full_location(con[2], con[1], te_db, te_cur)
elif con[0] == GENERAL:
current_results = simple_term(con[1], te_db, te_cur)
elif con[0] == DATEEXACT:
current_results = date_exact(con[1], con[2], con[3], da_db, da_cur)
elif con[0] == DATELESS:
current_results = date_less(con[1], con[2], con[3], da_db, da_cur)
elif con[0] == DATEGREATER:
current_results = date_greater(con[1], con[2], con[3], da_db, da_cur)
elif con[0] == INVALID:
continue
else:
print("ERROR IN CONDITION PARSING")
if first_time:
#if this is the first time, we have nothing to itersect with, so we just store the set
total_results = set(current_results)
first_time = False
else:
#sets ensure no duplicates
total_results = total_results & set(current_results)
return total_results
|
603b54bc44519f544d6f6502dbcfd6cbfb712a24
|
paulgrote/cs-study
|
/MIT-60001/psets/ps1/ps1a.py
| 881 | 3.96875 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 11:13:53 2020
@author: paulgrote
"""
# salary variables
annual_salary = float(input("Enter your annual salary: "))
monthly_salary = annual_salary/12
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
# house variables
total_cost = float(input("Enter the cost of your dream home: "))
portion_down_payment = 0.25
down_payment = portion_down_payment * total_cost
# savings variables
current_savings = 0
annual_return = 0.04
month = 0
print("Down payment is: ", down_payment)
while current_savings < down_payment:
month += 1
monthly_return = current_savings*(annual_return/12)
current_savings = current_savings + (monthly_salary * portion_saved) + monthly_return
print("Month", month, ":", current_savings)
print("Number of months: ", month)
|
425f602f2e904ad649c8c43d4da0c03c94ef7cfb
|
davicosta12/python_work
|
/Part_01/Cap_03/Lista_3.3.py
| 588 | 3.8125 | 4 |
# printando cada nome da lista junto com uma frase diferente e especial
games = ['Call of duty', 'League of Legends', 'Counter-Strike', 'Bully', 'Doom', 'Quake']
a = games[0]
b = games[1]
c = games[2]
d = games[3]
e = games[4]
f = games[5]
print("\n\tUma das franquia mais bem elaborada é " + a)
print("\tO jogo mais acessado no mundo se chama " + b)
print("\tAs lan-houses era um meio incrivel de jogar " + c)
print("\t" + d + " é um jogo muito interessante e ao mesmo tempo polêmico")
print("\tGostaria de jogar o novo " + e)
print("\tEu sou um bom jogador de " + f)
|
0a2a2abd3b7217178881180c0fbfda78fae9511a
|
soblin/algorithm_list
|
/sort/merge_sort/main.py
| 1,250 | 3.515625 | 4 |
# -*- coding: utf-8 -*-
import sys
sentinel = 1000000
def merge(array, left_buf, right_buf, frm, mid, to):
# 1 1 2
# 3 6 9
for i in range(0, (mid-frm)+1):
left_buf[i] = array[frm+i]
left_buf[(mid-frm)+1] = sentinel
for j in range(0, (to-mid)):
right_buf[j] = array[mid+1+j]
right_buf[(to-mid)] = sentinel
i = 0
j = 0
for k in range(frm, to+1):
if left_buf[i] < right_buf[j]:
array[k] = left_buf[i]
i += 1
else:
array[k] = right_buf[j]
j += 1
return
def merge_sort(array, left_buf, right_buf, frm, to):
if frm == to:
return
mid = int((frm + to) / 2)
# [frm, mid], [mid+1, to]
merge_sort(array, left_buf, right_buf, frm, mid)
merge_sort(array, left_buf, right_buf, mid+1, to)
merge(array, left_buf, right_buf, frm, mid, to)
return
if __name__ == '__main__':
argc = len(sys.argv)
size = argc - 1
array = [int(sys.argv[i+1]) for i in range(size)]
left_buf = [0 for _ in range(size)]
right_buf = [0 for _ in range(size)]
merge_sort(array, left_buf, right_buf, 0, size-1)
ret = ""
for elem in array:
ret += str(elem) + ' '
print(ret)
|
2743f84c6e2164874a8dfc242fb6b3179e35b222
|
ryanarbow/thinkful_lesson_problems
|
/text1.py
| 1,482 | 3.859375 | 4 |
class Musician(object):
def __init__(self, sounds):
self.sounds = sounds
#self.name = name
#print(sounds)
#print(name)
def solo(self, length):
for i in range(length):
print(self.sounds[i % len(self.sounds)] + " ")
print()
class Bassist(Musician): # The Musician class is the parent of the Bassist class
def __init__(self):
# Call the __init__ method of the parent class
super(Bassist, self).__init__(["Twang", "Thrumb", "Bling"])
class Guitarist(Musician):
def __init__(self):
# Call the __init__ method of the parent class
super(Guitarist, self).__init__(["Boink", "Bow", "Boom"])
def tune(self):
print("Be with you in a moment")
print("Twoning, sproing, splang")
class Drummer(Musician):
def __init__(self):
super(Drummer, self).__init__(["Bong", "Tink", "Tik", "Tak", "Hugga Digga Burr"])
def keep_time(self):
print("one two three four")
def ignite(self):
print("PFCHHHHHKKKKOOOOOOHH i.e. big fire boom sound")
class Band(Drummer):
def __init__(self):
print("Band created")
def hire(self):
print( "you're hired!")
def fire(self):
print("you're FIRED!")
def main():
bonzo = Drummer()
bonzo.keep_time()
bonzo.solo(8)
slash = Guitarist()
slash.solo(8)
bonzo.ignite()
RHCP = Band()
RHCP.hire()
if __name__ == "__main__":
main()
|
f77776f132b1a24494cf189ed0886f2b20da6e8b
|
sreejithr/BFS
|
/bfs.py
| 1,027 | 3.625 | 4 |
EDGE_DIST = 6
def shortest_dist(next_node, start, end):
if len(next_node[start]) == 0:
return -1
came_from = {}
to_visit = [start]
dist_so_far = {start: 0}
while len(to_visit) != 0:
current = to_visit.pop(0)
if current == end:
break
for next in next_node[current]:
new_dist = dist_so_far.get(current, 0) + EDGE_DIST
if next not in dist_so_far or new_dist < dist_so_far[next]:
dist_so_far[next] = new_dist
came_from[next] = current
to_visit.append(next)
return dist_so_far.get(end, None) or -1
def solution(next_node, start):
return [
shortest_dist(next_node, start, node) for node in next_node.keys()
if node != start
]
if __name__ == "__main__":
next_node = {
1: [2, 4, 5],
2: [3],
3: [4],
4: [5, 6],
5: [],
6: []
}
start = 1
print ' '.join([str(e) for e in solution(next_node, start)])
|
427527cdde7d4708cb5dec99f6d3434ff737bebd
|
PeterUIXIV/DPG
|
/Node.py
| 6,678 | 3.609375 | 4 |
import random
import math
class Node:
def __init__(self, lower, higher, h, i, b, u=None, mean=None, count=0, active=False):
self.left = None
self.right = None
self.h, self.i = h, i
self.lower, self.higher = lower, higher
self.b = b
self.u = u
self.mean = mean
self.count = count
self.active = active
# Print the tree
def print_tree(self):
if self.left and self.left.active:
self.left.print_tree()
print(f"({self.lower}, {self.higher}), b: {self.b}, u: {self.u}, mean: {self.mean}, times: {self.count}"),
if self.right and self.right.active:
self.right.print_tree()
def print_tree_depth(self, depth):
root = self
if root and 0 < depth:
print(f"({self.lower}, {self.higher}), b: {self.b}, u: {self.u}, mean: {self.mean}, times: {self.count}")
if root.left:
root.left.print_tree_depth(depth - 1)
if root.right:
root.right.print_tree_depth(depth - 1)
def in_order_traversal(self, root):
res = []
if root:
res = self.in_order_traversal(root.left)
res.append(root)
res = res + self.in_order_traversal(root.right)
return res
def path(self, target):
current = self
path = [current]
while current != target:
try:
if target.i <= current.left.i * 2 ** (target.h - current.left.h):
current = current.left
path.append(current)
elif target.i >= current.right.i * 2 ** (target.h - current.right.h) - (2 ** (target.h - current.right.h) - 1):
current = current.right
path.append(current)
else:
raise Exception("Target not found")
except AttributeError as e:
print(f"current ({current.lower}, {current.higher}) h: {current.h}, i: {current.i}")
print(f"target ({target.lower}, {target.higher}) h: {target.h}, i: {target.i}")
print(e)
return path
def duplicate_tree(self):
old_root = self
new_root = Node(old_root.lower, old_root.higher, old_root.h, old_root.i, old_root.b, old_root.u,
old_root.mean, old_root.count, old_root.active)
if old_root.left:
new_root.left = old_root.left.duplicate_tree()
if old_root.right:
new_root.right = old_root.right.duplicate_tree()
return new_root
# for node in self.in_order_traversal(root):
def first_leaf(self):
node = self
if node.left and node.active:
node = node.first_leaf()
elif node.right and node.active:
node = node.first_leaf()
return node
def first_leaf_and_parent(self):
parent = self
leaf = self
if parent.left and parent.left.active:
leaf = parent.left
elif parent.right and parent.right.active:
leaf = parent.right
if (leaf.left and leaf.left.active) or (leaf.right and leaf.right.active):
parent, leaf = leaf.first_leaf_and_parent()
return parent, leaf
def remove(self, node):
if self.left == node:
self.left = None
elif self.right == node:
self.right = None
else:
raise Exception('Node not found')
def pre_order_trav(self):
res = []
node = self
st = []
while node or st:
while node.active:
res.append(node)
st.append(node)
node = node.left
temp = st[-1]
st.pop()
if temp.right:
node = temp.right
return res
def pre_order_traversal(self):
res = []
st = []
node = self
while node or st:
while node:
if node.active:
res.append(node)
st.append(node)
node = node.left
temp = st[-1]
st.pop()
if temp.right:
node = temp.right
return res
def find(self, target):
current = self
while current.h != target.h or current.i != target.i:
if current.left and target.i <= current.left.i * 2 ** (target.h - current.left.h):
current = current.left
elif current.right and target.i >= (current.right.i - 1) * 2 ** (target.h - current.right.h) + 1:
current = current.right
else:
print(f"current h:{current.h}, i:{current.i}")
if current.left:
print(f"current.left h: {current.left.h}, i: {current.left.i} {current.left.active}")
if current.right:
print(f"current.right h: {current.right.h}, i: {current.right.i} {current.right.active}")
print(f"target h:{target.h}, i:{target.i}")
raise Exception("Target not found")
return current
def find_and_remove(self, target):
current = self
while current.h != target.h or current.i != target.i:
if current.left and target.i <= current.left.i * 2 ** (target.h - current.left.h):
current = current.left
elif current.right and target.i >= (current.right.i - 1) * 2 ** (target.h - current.right.h) + 1:
current = current.right
else:
print(f"current h:{current.h}, i:{current.i}")
if current.left:
print(f"current.left h: {current.left.h}, i: {current.left.i} {current.left.active}")
if current.right:
print(f"current.right h: {current.right.h}, i: {current.right.i} {current.right.active}")
print(f"target h:{target.h}, i:{target.i}")
raise Exception("Target not found")
if current.left == target:
current.left.left = None
current.left.right = None
current.left.active = False
current.left.b = float("inf")
return
if current.right == target:
current.right.left = None
current.right.right = None
current.right.active = False
current.right.b = float("inf")
return
def subtree_height(node):
if node is None:
return 0
else:
return max(subtree_height(node.left), subtree_height(node.right)) + 1
|
6c4be8ce843e4335cf74e3014a1f1b4e7351e87e
|
utkarshsaini19/Utkarsh-Saini
|
/simple_l_r.py
| 926 | 3.90625 | 4 |
import numpy as nm
import matplotlib.pyplot as plt
def getregre(x,y):
#no. of observations
n=nm.size(x)
#mean of x and y vector
m_x,m_y=nm.mean(x),nm.mean(y)
#calculating cross deviation and deviation about x
sxy=nm.sum(x*y)-n*m_x*m_y
sxx=nm.sum(x*x)-n*m_x*m_x
#definig theta1 and theta0
theta1=sxy/sxx
theta0=m_y-theta1*m_x
return theta0,theta1
"""now defininf function to plot regression line"""
def plot_line(x,y,b):
#plotting the actual point as scatter plot
plt.scatter(x,y,color='m',marker=",",s=20)
#response hypothesis
y1=b[0]+b[1]*x
#plotting the regression line
plt.plot(x,y1,color="g")
#now naming x and y axis
plt.xlabel('x')
plt.ylabel('y')
def main():
x=nm.array([1,2,3,4,5,6])
y=nm.array([14,6,1,2,8,9])
#estimating parameters
b=getregre(x,y)
print("estimating value of theta0={} and theta1={}".format(b[0],b[1]))
plot_line(x, y, b)
if __name__=="__main__":
main()
|
e864cb838e8b79262bb60b89478888c5c67b13c8
|
BFavetto/InfoBCPST2
|
/TP1/exercice7.py
| 198 | 3.78125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 8 00:20:42 2014
@author: Benjamin
"""
eps=float(input("entrer epsilon:"))
S=1.
n=0
while abs(3./2. -S)>eps:
S=S+1/3**(n+1)
n=n+1
print(n)
|
040dbfc85a1599814df7440b49ce9b70c280583f
|
rwlarsen/test-doubles-python
|
/Service.py
| 497 | 3.5 | 4 |
import abc
from typing import List
class Validator(abc.ABC):
@abc.abstractmethod
def validate(self,values: List[str]) -> bool:
pass
class Service:
validator: Validator
work_count: int = 0
def __init__(self, validator: Validator) -> None:
assert isinstance(validator, Validator)
self.validator = validator
def dowork(self):
args: List[str] = ["foo", "bar"]
if self.validator.validate(args):
self.work_count += 1
|
c6b86223eb847d2dd55ae97fded74cc516216b5d
|
jmaamtehsi/machine-learning
|
/Week2/machine-learning-ex1/ex1/Python/computeCost.py
| 386 | 3.953125 | 4 |
import numpy as np
def compute_cost(x, y, theta):
"""Compute cost for linear regression. Computes the cost of using theta as the
parameter for linear regression to fit the data points in X and y.
X, y, and theta are np arrays."""
m = len(y) # Number of training examples
h_minus_y = np.dot(x, theta) - y
return (1/(2 * m)) * np.dot(h_minus_y.T, h_minus_y)
|
69aa068c3342c475b544cce23c9489d662a1ed0b
|
yo09975/Clue-less
|
/src/player.py
| 4,356 | 3.625 | 4 |
"""player.py."""
from src.hand import Hand
from src.card import Card
from src.location import Location
from src.playerstatus import PlayerStatus
from src.cardtype import CardType
class Player(object):
"""Represents a player in the game.
Player class in the Game Management Subsystem. The object that represents
each Player that is stored in teh active game's PlayerList.
Attributes:
_player_hand - Hand object that contains teh initial Cards dealt to the
Player
_character - A Card object representing the Player's character
_status - A flag representing the status of the Player
_card_id - String representing the Player's suspect card
_uuid - Player's unique ID for messaging
_current_location - Player's current location on the gameboard
_previous_location - Player's previous location on the gameboard
_was_transferred - Boolean representing if the Player was moved to current
Location via a suggestion
"""
def __init__(self, card: Card):
"""Constructor"""
# print('Constructor in Player class')
if not card.get_type() == CardType.SUSPECT:
raise ValueError('Player constructor requires a Suspect Card')
else:
self._player_hand = Hand([])
self._character = card
self._status = PlayerStatus.COMP
self._card_id = self.get_character().get_id()
self._uuid = None
self._current_location = None
self._previous_location = None
self._was_transferred = False
def __str__(self) -> str:
player_str = 'Player is playing as: '
return player_str + self.get_character().get_id()
def __eq__(self, other):
""" Overridden equality check """
if isinstance(self, other.__class__):
return self.__dict__ == other.__dict__
return False
def set_hand(self, hand: Hand):
"""Creates the Player's initial Hand of Cards"""
self._player_hand = hand
def get_hand(self) -> Hand:
"""Return's the Player's Hand of Cards"""
return self._player_hand
def set_character(self, character: Card):
"""Accepts a Card to set a Player's character"""
self._character = character
def get_character(self) -> Card:
"""Returns a Card representing a Player's character"""
return self._character
def set_status(self, status: PlayerStatus):
"""Changes the status of the Player"""
# print('set_status method in Player class')
self._status = status
def get_status(self) -> PlayerStatus:
"""Returns an Enum representing the Player's current status"""
# print('get_status method in Player class')
return self._status
def set_location(self, location: str):
if type(location) is not str:
raise TypeError('set_location expects a string index of a location')
"""Sets the Location to where the Player is on the gameboard"""
# print('set_location method in Player class')
if self._previous_location is None:
self._previous_location = location
else:
self._previous_location = self._current_location
self._current_location = location
def get_current_location(self) -> str:
"""Return the Player's current Location"""
return self._current_location
def get_previous_location(self) -> str:
"""Return the Player's previous Location"""
return self._previous_location
def set_card_id(self, card_id: str):
"""Accepts a String to set the Player's unique token"""
self._card_id = card_id
def get_card_id(self) -> str:
"""Returns a String representing the Player's unique token"""
return self._card_id
def set_uuid(self, uuid: str):
self._uuid = uuid
def get_uuid(self) -> str:
return self._uuid
def set_was_transferred(self, transferred: bool):
"""Accepts a Boolean and sets if the Player was transferred via
suggestion"""
self._was_transferred = transferred
def get_was_transferred(self) -> bool:
"""Returns a Boolean on whether the Player was moved to the current
Location via a Suggestion"""
return self._was_transferred
|
8ce4f9eaac4aad118d76081bbb9b621a6d5b5f19
|
qianlongzju/project_euler
|
/python/PE031.py
| 757 | 3.796875 | 4 |
#!/usr/bin/env python
def dynamic():
"""
Dynamic Programming
"""
coins = [1, 2, 5, 10, 20, 50, 100, 200]
ways = [0] * (200 + 1)
ways[0] = 1
for coin in coins:
for i in range(coin, 200 + 1):
ways[i] += ways[i-coin]
print ways[200]
def recursive():
"""
Recursive
"""
L = [200, 100, 50, 20, 10, 5, 2, 1]
def f(money, maxcoin):
if maxcoin == 7:
return 1
s = 0
for i in range(maxcoin, len(L)):
if money - L[i] == 0:
s += 1
elif money - L[i] > 0:
s += f(money - L[i], i)
return s
print f(200, 0)
def main():
dynamic()
# recursive()
if __name__ == '__main__':
main()
|
d5f7bfed772488b611e066d31ea1653af631d450
|
alipay/ant-xgboost
|
/demo/guide-python/custom_objective.py
| 1,913 | 3.515625 | 4 |
#!/usr/bin/python
import numpy as np
import xgboost as xgb
###
# advanced: customized loss function
#
print('start running example to used customized objective function')
dtrain = xgb.DMatrix('../data/agaricus.txt.train')
dtest = xgb.DMatrix('../data/agaricus.txt.test')
# note: for customized objective function, we leave objective as default
# note: what we are getting is margin value in prediction
# you must know what you are doing
param = {'max_depth': 2, 'eta': 1, 'silent': 1}
watchlist = [(dtest, 'eval'), (dtrain, 'train')]
num_round = 2
# user define objective function, given prediction, return gradient and second
# order gradient this is log likelihood loss
def logregobj(preds, dtrain):
labels = dtrain.get_label()
preds = 1.0 / (1.0 + np.exp(-preds))
grad = preds - labels
hess = preds * (1.0 - preds)
return grad, hess
# user defined evaluation function, return a pair metric_name, result
# NOTE: when you do customized loss function, the default prediction value is
# margin. this may make builtin evaluation metric not function properly for
# example, we are doing logistic loss, the prediction is score before logistic
# transformation the builtin evaluation error assumes input is after logistic
# transformation Take this in mind when you use the customization, and maybe
# you need write customized evaluation function
def evalerror(preds, dtrain):
labels = dtrain.get_label()
# return a pair metric_name, result. The metric name must not contain a
# colon (:) or a space since preds are margin(before logistic
# transformation, cutoff at 0)
return 'my-error', float(sum(labels != (preds > 0.0))) / len(labels)
# training with customized objective, we can also do step by step training
# simply look at xgboost.py's implementation of train
bst = xgb.train(param, dtrain, num_round, watchlist, obj=logregobj,
feval=evalerror)
|
fa4ff6b25a3d6a154527e39c56305926bbc14be5
|
mateuszkochanek/carcassone-game
|
/backend/game/Board.py
| 3,836 | 3.53125 | 4 |
from backend.tile.Tile25Start import Tile25
class Board:
"""Main class which is responsible for board and tiles in game"""
def __init__(self):
"""Initialize attributes"""
self.tile_matrix = [[None for i in range(150)] for i in range(150)]
self.tile_matrix[75][75] = Tile25()
def getTiles(self):
"""Return board in as array of tuples
board = [(x1, y1, id1, rotate1, pawn1), (x2, y2, id2, rotate2, pawn2), ...]
pawn = (id, x, y)"""
board = []
for i in range(len(self.tile_matrix)):
for j in range(len(self.tile_matrix[0])):
if self.tile_matrix[i][j] is not None:
board.append((i - 75, j - 75, self.tile_matrix[i][j].code7x7, self.tile_matrix[i][j].orientation,
self.tile_matrix[i][j].pawns_in_7x7()))
return board
def putTile(self, tile, x, y):
"""Put tile on coordinates x, y"""
x += 75
y += 75
if y - 1 >= 0 and self.tile_matrix[x][y - 1] != None:
tile.leftTile = self.tile_matrix[x][y - 1]
(self.tile_matrix[x][y - 1]).rightTile = tile
if x - 1 >= 0 and self.tile_matrix[x - 1][y] != None:
tile.downTile = self.tile_matrix[x - 1][y]
(self.tile_matrix[x - 1][y]).upTile = tile
if y + 1 <= 149 and self.tile_matrix[x][y + 1] != None:
tile.rightTile = self.tile_matrix[x][y + 1]
(self.tile_matrix[x][y + 1]).leftTile = tile
if x + 1 <= 149 and self.tile_matrix[x + 1][y] != None:
tile.upTile = self.tile_matrix[x + 1][y]
(self.tile_matrix[x + 1][y]).downTile = tile
self.tile_matrix[x][y] = tile
def isTileOnBoard(self, tile):
"""Return true if tile is already on board, false otherwise"""
for i in range(len(self.tile_matrix)):
for j in range(len(self.tile_matrix[0])):
if self.tile_matrix[i][j] == tile:
return True
return False
def getTilePositions(self, tile):
"""Return [(x, y)], where x and y are coordinates on board"""
result = []
for i in range(len(self.tile_matrix)):
for j in range(len(self.tile_matrix[0])):
if self.tile_matrix[i][j] is None and self.__hasNeighbour(i, j):
if (self.tile_matrix[i + 1][j] is None or self.tile_matrix[i + 1][j].fit_down(tile)) \
and (self.tile_matrix[i - 1][j] is None or self.tile_matrix[i - 1][j].fit_up(tile)) \
and (self.tile_matrix[i][j - 1] is None or self.tile_matrix[i][j - 1].fit_right(tile)) \
and (self.tile_matrix[i][j + 1] is None or self.tile_matrix[i][j + 1].fit_left(tile)):
result.append((i - 75, j - 75))
return result
def addFinalPoints(self, players):
"""Add points at the end of the game"""
for i in range(len(self.tile_matrix)):
for j in range(len(self.tile_matrix[0])):
if self.tile_matrix[i][j] is not None:
awarded = self.tile_matrix[i][j].after_game()
for p in players:
if p.ifActive() and p.getId() in awarded:
p.addPoints(awarded[p.getId()])
def __hasNeighbour(self, i, j):
"""Return true, if coordinates ixj has neighbour, false otherwise"""
if i > 0 and self.tile_matrix[i - 1][j] is not None:
return True
if i < 149 and self.tile_matrix[i + 1][j] is not None:
return True
if j > 0 and self.tile_matrix[i][j - 1] is not None:
return True
if j < 149 and self.tile_matrix[i][j + 1] is not None:
return True
return False
|
8424b31febfd939c4c5f388a343f626572ba484d
|
Cherevan/gbProj
|
/code_180328/game_1.py
| 481 | 3.96875 | 4 |
import random
words_list = ['автострада', 'бензин', 'инопланетянин', 'самолет', 'библиотека',
'шайба', 'олимпиада']
secret_word = random.sample(words_list, 1)[0]
print(secret_word)
while True:
letter = input('введите букву: ')
if len(letter) != 1:
continue
if letter in secret_word:
print(letter)
else:
print('буквы нет')
|
7ab70f005baace8cffdc612e8624554985cd67c6
|
RadekVlcek/weight
|
/weight.py
| 3,474 | 3.53125 | 4 |
import json
class Weight():
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
def __init__(self, data_file):
self.data_file = data_file
try:
file_exists = open(self.data_file)
except FileNotFoundError:
print(f'Created data file: {self.data_file}')
with open(self.data_file, 'w') as new_data_file:
new_data_file.write('{}')
else:
file_exists.close()
def cls(self):
import os
os.system('cls') if os.name == 'nt' else os.system('clear')
def get_date(self):
from datetime import date
d = date.today()
return [(d.day), self.months[d.month-1], d.year]
def read_file(self, file):
with open(file, 'r') as file:
return file.read()
# Show records for current month
def show_records(self, date, select=0):
records = {}
day = date[0]
month = date[1] if select == 0 else self.months[select-1]
records = self.read_file(self.data_file)
if records == '{}':
print('\n --- NO RECORDS FOUND ---\n')
return 0
records = json.loads(records)
print(f'\n\t| {month} |')
print('\t------------------------------------')
print(f'\t DAY\t WEIGHT \t DIFFERENCE')
if month in records:
prev_weight = 0
for day, weight in records[month].items():
if day == 1 or day == 21 or day == 31:
day = f'{day}st'
elif day == 2 or day == 22:
day = f'{day}nd'
elif day == 3 or day == 23:
day = f'{day}rd'
else:
day = f'{day}th'
diff = weight - prev_weight
if diff == weight:
diff = f' 0.0'
else:
diff = format(diff, '.1f')
if float(diff) > 0.0:
diff = f'+{diff}'
elif float(diff) < 0.0:
diff = f'{diff}'
else:
diff = f' {diff}'
# Store previous weight for comparison
prev_weight = weight
print(f'\t {day}\t {weight} kg \t {diff}kg')
print('\t------------------------------------\n')
if select != 0:
input('Press key to return...')
# Add weight record
def add_record(self, new_weight, date):
day, month = str(date[0]), date[1]
records = {}
# Read from data file
records = self.read_file(self.data_file)
records = json.loads(records)
# Check if month exists
if month in records:
if day not in records[month]:
records[month][day] = float(new_weight)
print(f'Added record for today.')
else:
records[month][day] = float(new_weight)
print(f'Record already existed for today and got overwritten.')
# Create it if not
else:
records[month] = {}
records[month][day] = float(new_weight)
# Write back to data file
with open(self.data_file, 'w') as file:
file.write(json.dumps(records))
|
9a70e482f63529af5a7097c236970ed5c999942e
|
gan3i/Python_second
|
/UnitTesting/test_2.py
| 2,074 | 4.125 | 4 |
def save_change(y):
# with (f as open("list.txt")):
f = open("list.txt", mode="wt", encoding="utf-8")
f.write(y)
l=1
print ("Please input five numbers")
a=int(input("1.:"))
print (a, "is the first number.")
print()
b=int(input("2.:"))
print (b, "is the second number.")
print()
c=int(input("3.:"))
print (c, "is the third number.")
print()
d=int(input("4.:"))
print (d, "is the fourth number.")
print()
e=int(input("5.:"))
print (e, "is the fifth number.")
print()
x=[a, b, c, d, e]
y=sorted(x,reverse=True)
print (y)
save_change()
while l==1:
print()
print ("If you want to delete a number, press D.")
print()
print ("If you want to add a number, press A.")
print()
print ("If you want to change a number, press C.")
print ()
print ("If you want to exit, press Q.")
print ()
z=input("Answer: ")
if z=="A":
f=int(input("Please input another number: "))
x.append(f)
y=sorted(x,reverse=True)
print (y)
elif z=="C":
g=int(input("Input a number you will change: "))
if g in x:
x.remove(g)
print (g, "is removed.")
f=int(input("Put the number you want to replace: "))
x.append(f)
y=sorted(x,reverse=True)
print (y)
elif g not in x:
print ()
print (g, "is not in the list.")
y=sorted(x, reverse=True)
print (y)
elif z=="D":
g=int(input("Input a number you will delete: "))
if g in x:
x.remove(g)
print (g, "is removed.")
y=sorted(x,reverse=True)
print (y)
elif g not in x:
print ()
print (g, "is not in the list.")
y=sorted(x, reverse=True)
print (y)
elif z=="Q":
import sys
print ("Thanks!")
sys.exit
break
else:
print ("Sorry. I could not understand. Try again.")
|
f78f18be418b779fa304e38ced6d1f62f8372c78
|
adambonneruk/millipede
|
/millipede.py
| 1,509 | 3.953125 | 4 |
"""millipede is used for multiple consecutive RegEx search and replace opperations on a single text file"""
import re
def multi_search_and_replace(rows, rules):
results = []
row_count = len(rows) # count of the row array (e.g. lines in the .txt file)
rule_count = len(rules) # count of RegEx search and replace rules
for i in range(0,row_count):
results.append(rows[i])
for j in range(0,rule_count):
results[i] = re.sub(rules[j][0],rules[j][1],results[i])
""" rule[j] is the current search and replace rule
rule[j][0] is the zeroth column of the rule array, the "search"
rule[j][1] is the first column of the rule array, the "replace" """
return results
def main():
# setup list of RegEx search and replace rules in a 2D array structure
regex_sar_rules = [
[r"[aeiou]", ""], # Remove Vowels
[r"\.", "_"], # Replace PEriod/Full Stop with Underscore
[r" ", ""] # Remove Spaces
]
# read the .txt file in as a 1D array where each line of the file is a new element
text_rows = []
file = open(r'test/foobar.txt', "r")
for line in file:
text_rows.append(line.strip('\n'))
file.close()
# perform the multiple search and replace rules for each line in the input file
results = multi_search_and_replace(text_rows,regex_sar_rules)
# ...and print the output
for result in results:
print(result)
if __name__ == "__main__":
main()
|
dbebea3377cb0e4189f3eb9eea35ff4f8e982829
|
chxj1992/leetcode-exercise
|
/subject_lcof/18/_1.py
| 1,135 | 4 | 4 |
import unittest
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteNode(self, head: ListNode, val: int) -> ListNode:
prehead = ListNode(-1)
prehead.next = head
curr = prehead
while curr and curr.next:
if curr.next.val == val:
curr.next = curr.next.next
curr = curr.next
return prehead.next
class Test(unittest.TestCase):
def test(self):
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
expected = ListNode(1)
expected.next = ListNode(2)
expected.next.next = ListNode(4)
expected.next.next.next = ListNode(5)
s = Solution()
actual = s.deleteNode(head, 3)
while expected:
self.assertEqual(expected.val, actual.val)
expected = expected.next
actual = actual.next
if __name__ == '__main__':
unittest.main()
|
0e319908723b9247e9321a1e75058ce5e5d5b09e
|
patel1643/Hackerrank
|
/minimum swaps 2.py
| 508 | 3.5625 | 4 |
def minimumSwaps(arr):
swapCount = 0
minPos = 0
for i in range(len(arr)):
minPos = i
j = i
while(j < len(arr)):
mini = min(arr[j:])
swapIndex = arr.index(mini)
if (arr[minPos] != mini):
temp = arr[minPos]
arr[minPos] = mini
arr[swapIndex] = temp
swapCount+=1
break
else:
break
return swapCount
print(minimumSwaps([1,3,5,2,4,6,7]))
print(minimumSwaps([2,3,4,1,5]))
print(minimumSwaps([4,3,1,2]))
|
246a1ed8f212e519e0b7879a5d5478cf7ff4982b
|
Vostbur/cracking-the-coding-interview-6th
|
/python/chapter_1/07_rotate.py
| 1,397 | 4.0625 | 4 |
"""Имеется изображение, представленное матрицей NxN;
каждый пиксел представлен 4 байтами.
Напишите метод для поворота изображения на 90 градусов.
Удастся ли вам выполнить эту операцию 'на месте'?"""
import unittest
def rotate(m):
n = len(m)
for row in range(n // 2):
start, end = row, n - row - 1
for col in range(start, end):
element = m[row][col]
m[row][col] = m[-col - 1][row]
m[-col - 1][row] = m[-row - 1][-col - 1]
m[-row - 1][-col - 1] = m[col][-row - 1]
m[col][-row - 1] = element
return m
class Test(unittest.TestCase):
data = [
(
[
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
],
[
[21, 16, 11, 6, 1],
[22, 17, 12, 7, 2],
[23, 18, 13, 8, 3],
[24, 19, 14, 9, 4],
[25, 20, 15, 10, 5],
],
)
]
def test_rotate(self):
for [m, result] in self.data:
self.assertEqual(rotate(m), result)
if __name__ == "__main__":
unittest.main()
|
c42e1804d4a295eff0fe5006d9c7355d02a3353a
|
rfelts/wsgi-calculator
|
/calculator.py
| 5,314 | 3.984375 | 4 |
#!/usr/bin/env python3
# Russell Felts
# Assignment 04 WSGI Calculator
import traceback
"""
For your homework this week, you'll be creating a wsgi application of
your own.
You'll create an online calculator that can perform several operations.
You'll need to support:
* Addition
* Subtractions
* Multiplication
* Division
Your users should be able to send appropriate requests and get back
proper responses. For example, if I open a browser to your wsgi
application at `http://localhost:8080/multiple/3/5' then the response
body in my browser should be `15`.
Consider the following URL/Response body pairs as tests:
```
http://localhost:8080/multiply/3/5 => 15
http://localhost:8080/add/23/42 => 65
http://localhost:8080/subtract/23/42 => -19
http://localhost:8080/divide/22/11 => 2
http://localhost:8080/ => <html>Here's how to use this page...</html>
```
To submit your homework:
* Fork this repository (Session03).
* Edit this file to meet the homework requirements.
* Your script should be runnable using `$ python calculator.py`
* When the script is running, I should be able to view your
application in my browser.
* I should also be able to see a home page (http://localhost:8080/)
that explains how to perform calculations.
* Commit and push your changes to your fork.
* Submit a link to your Session03 fork repository!
"""
def info(*args):
"""
Produces a string that describes the site and how to use it
:param args: unused as nothing is being calculated
:return: String containing html describing the site
"""
page = """
<h1>Calculator</h1>
<p>This site is a simple calculator that will add, substract, multiply, and divide two numbers.</p>
<p>Simply enter a url similar to http://localhost:8080/add/23/42 and the answer will be returned.</p>
<p> The possible paths are /add/#/#, /substract/#/#, /multiply/#/#, /divide/#/#</p>
"""
return page
def add(*args):
"""
Adds to ints in a list
:param args: to numbers to add
:return: a STRING with the sum of the arguments
"""
# Convert the args to ints
temp_list = contert_to_int(*args)
total = sum(temp_list)
return str(total)
def subtract(*args):
"""
Subtract two ints
:param args: to numbers to subtract
:return: a STRING with the sum of the arguments
"""
# Convert the args to ints
temp_list = contert_to_int(*args)
total = temp_list[0] - temp_list[1]
return str(total)
def multiply(*args):
"""
Multiply two ints
:param args: to numbers to multiply
:return: a STRING with the sum of the arguments
"""
# Convert the args to ints
temp_list = contert_to_int(*args)
total = temp_list[0] * temp_list[1]
return str(total)
def divide(*args):
"""
Divides two ints
:param args: to numbers to divide
:return: a STRING with the sum of the arguments
"""
temp_list = contert_to_int(*args)
try:
total = temp_list[0] / temp_list[1]
except ZeroDivisionError:
raise ZeroDivisionError
return str(total)
def contert_to_int(*args):
"""
Converts the string args to a list of ints
:param args: Two strings
:return: A list of ints
"""
return [int(arg) for arg in args]
def resolve_path(path):
"""
Take the request and determine the function to call
:param path: string representing the requested page
:return: func - the name of the requested function,
args - iterable of arguments required for the requested function
"""
funcs = {
'': info,
'add': add,
'subtract': subtract,
'multiply': multiply,
'divide': divide
}
# Split the path to determine what the function and arguments
path = path.strip('/').split('/')
func_name = path[0]
args = path[1:]
# Get the requested function from the dictionary or raise an error
try:
func = funcs[func_name]
except KeyError:
raise NameError
return func, args
def application(environ, start_response):
"""
Handle incoming requests and route them to the appropriate function
:param environ: dictionary that contains all of the variables from the WSGI server's environment
:param start_response: the start response method
:return: the response body
"""
headers = [('Content-type', 'text/html')]
try:
path = environ.get('PATH_INFO', None)
if path is None:
raise NameError
func, args = resolve_path(path)
body = func(*args)
status = "200 OK"
except NameError:
status = "404 Not Found"
body = "<h1>Not Found</h1>"
except ZeroDivisionError:
status = "400 Bad Request"
body = "<h1>Bad Request</h1>"
except Exception:
status = "500 Internal Server Error"
body = "<h1>Internal Server Error</h1>"
print(traceback.format_exc())
finally:
headers.append(('Content-length', str(len(body))))
start_response(status, headers)
return [body.encode('utf8')]
if __name__ == '__main__':
from wsgiref.simple_server import make_server
srv = make_server('localhost', 8080, application)
srv.serve_forever()
|
0dda448d2597cedf123f5c5e765cd9460795da7c
|
xunihao1993/haohao_code
|
/test1.py
| 162 | 3.59375 | 4 |
'''
import re
math = re.match('Hello[ \t]*(.*)world','Hello aaa Python world')
print(math.group(1))
'''
a= [123,'spam',1.23]
print(a[:-1])
print(a[1:2])
11
|
eec9c60388f0f7e4da84bec272fe8964b42f5504
|
phoca-lenivica/lesson2
|
/task6_get_sum.py
| 213 | 3.796875 | 4 |
def get_summ():
try:
num_one = int(input())
num_two = int(input())
return num_one + num_two
except ValueError:
print('Проверьте вводимые данные.')
result = get_summ()
print(result)
|
cd639bd38523f9f689ff2457664bbe65c3e63606
|
adamjbc/advent-of-code
|
/day_4/day_4.py
| 2,474 | 3.578125 | 4 |
import re
f = open("input.txt", "r")
all_data = []
for line in f:
entries = line.rstrip().split(" ")
all_data += entries
passports = list()
passport = dict()
for entry in all_data:
if entry == "":
passports.append(passport)
passport = dict()
else:
[key, value] = entry.split(":")
passport[key] = value
passports.append(passport)
count_valid = 0
for passport in passports:
if len(passport) == 8:
count_valid += 1
elif len(passport) == 7 and "cid" not in passport:
count_valid += 1
else:
count_valid += 0
print(count_valid)
count_valid = 0
for passport in passports:
if len(passport) < 7 or (len(passport) == 7 and "cid" in passport):
print(f"invalid")
continue
try:
byr = int(passport["byr"])
if (byr < 1920) or (byr > 2002):
print(f"byr invalid {byr}")
continue
except ValueError:
print(f"byr invalid {byr}")
continue
try:
iyr = int(passport["iyr"])
if (iyr < 2010) or (iyr > 2020):
print(f"iyr invalid {iyr}")
continue
except ValueError:
print(f"iyr invalid {iyr}")
continue
try:
eyr = int(passport["eyr"])
if (eyr < 2020) or (eyr > 2030):
print(f"eyr invalid {eyr}")
continue
except ValueError:
print(f"eyr invalid {eyr}")
continue
try:
hgt = int(passport["hgt"][:-2])
if (passport["hgt"][-2:] == "cm") and ((hgt < 150) or (hgt > 193)):
print(f"hgt invalid a {hgt}")
continue
if (passport["hgt"][-2:] == "in") and ((hgt < 59) or (hgt > 76)):
print(f"hgt invalid b {hgt}")
continue
if not ((passport["hgt"][-2:] == "cm") or (passport["hgt"][-2:] == "in")):
print(f"hgt invalid c {hgt}")
continue
except ValueError:
print(f"hgt invalid d {passport['hgt']}")
continue
if not re.search("^#([a-fA-F0-9]{6})$", passport['hcl']):
print(f"hcl invalid {passport['hcl']}")
continue
if not passport["ecl"] in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]:
print(f"ecl invalid {passport['ecl']}")
continue
if not re.search("^([0-9]{9})$", passport['pid']):
print(f"pid invalid {passport['pid']}")
continue
print("VALID")
count_valid += 1
print(count_valid)
|
381480860df458c87e5cf101bb9259c71ffeca3f
|
yusuke-hi-rei/python
|
/23. pip(external_package)/03. pillow/imageProcessing3.py
| 339 | 3.578125 | 4 |
## Convert to monochrome.
from PIL import Image
#! Exception processing is performed assuming
#! that the image file cannot be opened.
try:
img1 = Image.open("image.jpg", "r")
#! L: grayscale.
img2 = img1.convert("L")
img2.save("image_saved3.jpg", "JPEG")
print("saved...")
except IOError as error:
print(error)
|
5146d11a4d5dc3435ddf37aa4735df7486172d02
|
Philipppy/US_Bikeshare
|
/show_data.py
| 1,639 | 3.671875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 9 19:57:42 2021
@author: Julia und Philipp
"""
import time
import calendar
import datetime
import pandas as pd
import numpy as np
city = 'chicago'
month = 'all'
day = 'all'
#load raw data
bikedata = pd.read_csv(city + ".csv")
#use Start time column to extract months and days of rental events
bikedata['Start Time'] = pd.to_datetime(bikedata['Start Time'])
bikedata['End Time'] = pd.to_datetime(bikedata['End Time'])
#print(bikedata.head(10))
bikedata['month'] = bikedata['Start Time'].dt.month_name()
#print(bikedata.head(10))
bikedata['day'] = bikedata['Start Time'].dt.day_name()
#print(bikedata.head(10))
#filter by month
if month != 'all':
# filter by month to create the new dataframe
bikedata = bikedata[bikedata['month']==month.capitalize()]
#filter by day
if day != 'all':
# filter by month to create the new dataframe
bikedata = bikedata[bikedata['day']==day.capitalize()]
#print(bikedata.head(3))
'----------------------------------------------------------------------------'
'----------------------------------------------------------------------------'
response = input("Do you wish to see 5 rows of trip data?" +
" Please enter yes or no.\n")
df_loc = 0
while True:
if response == 'yes':
print(bikedata.iloc[df_loc:df_loc+5])
df_loc = df_loc+5
elif response == 'no':
print("You decided to quit, Good bye!")
break
response = input("Do you wish to continue?"
+ " Yes will show the next 5 lines, no will quit.\n")
|
9d302fad2d7ee7673cbba5f82b8ed025361d03df
|
Aasthaengg/IBMdataset
|
/Python_codes/p03998/s976944756.py
| 184 | 3.765625 | 4 |
s = [list(input()) for _ in range(3)]
n_row = 0
dic = {0:"A",1:"B",2:"C"}
s_fix = {"a":0,"b":1,"c":2}
while len(s[n_row]):
n_row = s_fix[s[n_row].pop(0)]
print(dic[n_row])
|
009c14b0df17ebea528ab26d74a10578bdd0eba6
|
kr-amitsinha/hackerrank_10days_stats
|
/Day1/day1_interquartile_range.py
| 918 | 4.28125 | 4 |
def find_median(array, length):
#median
mid_point = int(length/2)
if length%2==0:
median = (array[mid_point]+array[ mid_point-1])/2
else:
median = array[mid_point]
return median
length = int(input())
value = list(map(int, str(input()).split(' ')))
frequency = list(map(int, str(input()).split(' ')))
array = []
for i in range(length):
elem = value[i]
for j in range(frequency[i]):
array.append(elem)
import pdb; pdb.set_trace()
array.sort()
#updating the length to the new set length
length = len(array)
#Divide the array into two halves
mid_point = int(length/2)
if length%2 == 0:
lower = array[:mid_point]
upper = array[mid_point:]
else:
lower = array[:mid_point]
upper = array[mid_point+1:]
first_quartile = find_median(lower, len(lower))
third_quartile = find_median(upper, len(upper))
inter_quartile_range = third_quartile - first_quartile
print("{:.1f}".format(inter_quartile_range))
|
7ed392a7da7b347394fbec71e2c4d4e6ae989fd6
|
jaqxues/AL_Info
|
/Cours_2e/C6_Structures/Ex6_9.py
| 396 | 3.796875 | 4 |
from random import random
n = int(input('Enter n: '))
assert n >= 2
values = [random() * 100 for _ in range(n)]
product = 1
for value in values:
product *= value
inverse_sum = 0
for value in values:
inverse_sum += 1 / value
print('Arithmetic mean:', sum(values) / len(values))
print('Geometric mean:', product ** (1 / len(values)))
print('Harmonic mean:', len(values) / inverse_sum)
|
6ab2a1e6bc814c3602fe6c857a5f2fd7556b7dfa
|
nonnonno/step2020
|
/sorted_dictionary.py
| 819 | 3.5 | 4 |
import csv
from operator import itemgetter
def dictionary_sort(dictionary):
new_dictionary = []
for word in dictionary:#new_dictionaryに、小文字・ソート済のものを加えていく
new_dictionary.append([''.join(sorted(word.lower())),word])
sorted_new_dictionary = []
sorted_new_dictionary = new_dictionary.sort(key=itemgetter(0))
with open('/Users/AHiroe/Desktop/STEP/anagram_sorted_dictionary2.csv','w') as f:
writer = csv.writer(f)#new_dictionaryの中身を書き出す
for x in new_dictionary:
writer.writerow(x)
return 0
f = open('/Users/AHiroe/Desktop/STEP/dictionary.words.txt',"r")
list_row = []
for x in f:
list_row.append(x.rstrip("\n"))#list_rowに辞書の中身を書き込み
f.close()
dictionary_sort(list_row)
|
e1f784d12e90e090b5a6e814ff4218150ea1ea0a
|
rajlath/rkl_codes
|
/code-signal/validate_sudoku.py
| 870 | 3.78125 | 4 |
def sudoku2(grid):
for i in range(9):
if not isValidList([grid[i][j] for j in range(9)] or not isValidList([grid[j][i] for j in range(9)])):
return False
for i in range(3):
for j in range(3):
if not isValidList([grid[m][n] for n in range(3 * j, 3 * j + 3) for m in range(3 * i, 3 * i + 3)]):
return False
return True
def isValidList(xs):
xs = [x for x in xs if x != "."]
return len(set(xs)) == len(xs)
grid = [[".",".",".","1","4",".",".","2","."],
[".",".","6",".",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".","1",".",".",".",".",".","."],
[".","6","7",".",".",".",".",".","9"],
[".",".",".",".",".",".","8","1","."],
[".","3",".",".",".",".",".",".","6"],
[".",".",".",".",".","7",".",".","."],
[".",".",".","5",".",".",".","7","."]]
print(sudoku2(grid))
|
4ddc6c833377f8afbbdfc9e9bb966bbca3ee415d
|
jay-95/SW-Academy-Intermediate
|
/6일차/삼성 sw test 21 미로의 거리.py
| 1,274 | 3.765625 | 4 |
def BFS(start_x, start_y):
global result
distance_level = 0
Queue = []
Queue.append((start_x, start_y, 0))
while Queue:
current_x, current_y, distance_level = Queue.pop(0)
if not visited[current_x][current_y]:
visited[current_x][current_y] = True
for dir_index in range(4):
next_x = dx[dir_index] + current_x
next_y = dy[dir_index] + current_y
if 0 <= next_x < N and 0 <= next_y < N and (Maze[next_x][next_y] == 0 or Maze[next_x][next_y] == 3)and visited[next_x][next_y] is False:
Queue.append((next_x, next_y, distance_level+1))
if Maze[next_x][next_y] == 3:
result = distance_level
return result
T = int(input())
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
for test_case in range(1, T + 1):
N = int(input())
Maze = [list(map(int, input())) for _ in range(N)]
visited = [[False for _ in range(N)] for _ in range(N)]
result = 0
for i in range(N):
for j in range(N):
if Maze[i][j] == 2:
start_x = i
start_y = j
break
BFS(start_x, start_y)
print('#'+str(test_case), result)
|
89c83a179abd4f4be8f459c1fc1c76157901171e
|
mostafagafer/Pandas--Udemy-course
|
/Lec-1 .py
| 919 | 4 | 4 |
import pandas as pd
s = pd.Series([10, "Namaste", 23.5, "Hello"])
print(s)
# now we can index it
s[0]
s[1]
# for indexing it by a,b,c,d rather than 0,1,2,3
s = pd.Series([10, "Namaste", 23.5, "Hello"], index=['a', 'b', 'c', 'd'])
print(s)
s['a']
s['b']
# By deict
d = {"Seattle": 1000000, "San Francesco": 5000000, "San Jose": 1500000}
cities = pd.Series(d)
print(cities)
cities["Seattle"]
cities[cities > 1000000]
cities[cities == 1000000]
####
d = {"Seattle": 100, "San Francesco": 500, "San Jose": 150, "London": 1200, "Tokyo": 1600}
cities = pd.Series(d)
cities
cities < 1000
# how to change San francesco from 500 to 600
cities["San Francesco"] = 600
print(cities)
# how to change many cities to 750
cities[cities < 1000] = 750
cities
# divideng all cities by 10
cities/10
# if you want to square them , import numpy
import numpy as np
np.square(cities)
# checking if all the cities has value
cities.isnull()
|
4d3c8678b08961ac9b63e7df29d778d84ccde0fa
|
Tradd-Schmidt/CSC226-Software-Design-and-Implementation
|
/T/T10/t10_schmidtt_bondurantc.py
| 4,698 | 3.828125 | 4 |
######################################################################
# Author: Tradd Schmidt and Conner Bondurant TODO: Change this to your names
# Username: schmidtt and bondurantc TODO: Change this to your usernames
#
# Assignment: T10: Oh, the Places You'll Go!
#
# Purpose: To create a map of locations
# where the user is originally from or has visited,
# and to use tuples and lists correctly.
######################################################################
# Acknowledgements:
#
# Original Authors: Dr. Scott Heggen and Dr. Jan Pearce
# licensed under a Creative Commons
# Attribution-Noncommercial-Share Alike 3.0 United States License.
####################################################################################
import turtle
def parse_file(filename):
"""
Opens a text file, adds the contents into tuples, and then places the tuples into a list
:param filename: name of the file
:return: a list
"""
# FIXME: Add an appropriate docstring for this function.
file_content = open(filename, 'r') # Opens file for reading
str_num = file_content.readline() # The first line of the file is the number of entries
str_num = int(str_num[:-1]) # The '/n' character needs to be removed
places_list = []
for i in range(str_num):
places_list.append(extract_place(file_content)) # Assembles the list of places
file_content.close()
return places_list
def extract_place(file_content):
# FIXME: Add an appropriate docstring for this function
"""
Takes contents of a file and puts them into a formated tuple
:param file_content: the content of a file to be put into a tuple
:return: a tuple
"""
name = file_content.readline()
name = name[:-1]
desc = file_content.readline()
desc = desc[:-1]
x = file_content.readline()
x = float(x[:-1])
y = file_content.readline()
y = float(y[:-1])
color = file_content.readline()
color = color[:-1]
place_tuple = (name, desc, x, y, color)
# TODO Parse the file, line by line. You can read each line of the file using the code above on line 27.
# TODO The order of the lines are: name, location, latitude, longitude, and user color.
# TODO Just like above (line 28), you need to remove the last character (\n).
# TODO Place the elements into the tuple below, and return the tuple.
return place_tuple
def place_pin(window, place):
"""
This function places a pin on the world map.
:param window: the window object where the pin will be placed
:param place: a tuple object describing a place to be put on the map
:return: None
"""
#####################################################
# You do not need to modify this function!
#####################################################
pin = turtle.Turtle()
pin.penup()
pin.color(place[4]) # Set the pin to user's chosen color
pin.shape("circle") # Sets the pin to a circle shape
# Logically, the denominator for longitude should be 360; lat should be 180.
# These values (195 and 120) were determined through testing to account for
# the extra white space on the edges of the map. You shouldn't change them!
pin.goto((place[3] / 195) * window.window_width() / 2, (place[2] / 120) * window.window_height() / 2)
pin.stamp() # Stamps on the location
text = "{0}'s place:\n {1}".format(place[0], place[1]) # Setting up pin label
pin.write(text, font=("Arial", 10, "bold")) # Stamps the text describing the location
def main():
"""
This program is designed to place pins on a world map.
Each place is represented as a tuple.
Each tuple is then added to a list
to make iterating through all the t11_places and adding them to the map easier.
:return: None
"""
# The next three lines set up the world map
wn = turtle.Screen()
wn.setup(width=1100, height=650, startx=0, starty=0)
wn.bgpic("world-map.gif")
# A sample file was created for you to use here: places.txt
in_file = input("Enter the name of the file: ")
place_list = parse_file(in_file) # generates place_list from the file
# Iterates through each item in the list, calling the place_pin() function
for place in place_list:
place_pin(wn, place) # Adds ONE place to the map for each loop iteration
print("Map created!")
wn.exitonclick()
main()
|
6ceb61f99f32e12705f902b7bd71d0295d500314
|
yennanliu/CS_basics
|
/algorithm/python/insertion_sort.py
| 606 | 4.4375 | 4 |
#---------------------------------------------------------------
# INSERTION SORT
#---------------------------------------------------------------
# https://www.geeksforgeeks.org/python-program-for-insertion-sort/
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
arr = [12, 11, 13, 5, 6]
r = insertionSort(arr)
print ("Sorted array is:", r)
|
269cee303398490e60085a0e7c72255516f68f9f
|
CaptainSherry49/Python-Project-Beginner-to-Advance
|
/16 Open(), Read() & Readline() For Reading File.py
| 1,065 | 4.375 | 4 |
# --------------------------- Open File ------------------------------------- #
f = open("Sherry.txt") # f is use as a pointer for this file to handle this file
content = f.read() # This variable is for accessing the content
print(content) # Now print the content
f.close()
f = open("Sherry.txt")
content2 = f.read(25) # Jitna words read karna ha otna numbers likh sakta ha
print(content2)
f.close() # Remember after opening file you should have to close the file also
# -------------------------- Iterating on File ------------------ #
# We can also iterate content of File
s = open("Sherry.txt")
for line in s:
print(line, end='')
s.close()
# ------------------ Readline ------------------ #
# we can also use readline function to read line by line content of a file
print()
b = open('Sherry.txt')
print(b.readline()) # jitni bar readline func chalai ga otni lines print hogi
b.close()
# ---------------------- Readlines ------------------- #
c = open('Sherry.txt')
print(c.readlines()) # readlines func will read lines & return list
c.close()
|
876d6dfbb9c188ba54b5f61188c32d07ffec2a26
|
omtelecom/python0907
|
/modul01/dz2_1.py
| 92 | 3.546875 | 4 |
def square_even(n):
return [i * i for i in range(2, n + 1, 2 )]
print (square_even(7))
|
1a78173b04de5db7ec9f0dbc1cde31c6c7749f51
|
Lucas-vdr-Horst/Mastermind-extraExercises
|
/exercise-1/Testcheck.py
| 337 | 3.78125 | 4 |
def difference_index(str_1, str_2):
for i in range(min(len(str_1), len(str_2))):
if str_1[i] != str_2[i]:
return i
if __name__ == "__main__":
string_1 = input("Geef een string: ")
string_2 = input("Geef een string: ")
print("Het eerste verschil zit op index:", difference_index(string_1, string_2))
|
527ed4eca816393047a1cc652a4fc35fab42bbca
|
Mooophy/DMA
|
/ch03/merge_sort.py
| 968 | 3.765625 | 4 |
def merge(seq, first, mid, last):
(left, right) = (seq[first: mid], seq[mid: last])
(l, r, curr) = (0, 0, first)
(left_size, right_size) = (len(left), len(right))
while l != left_size and r != right_size:
if left[l] < right[r]:
seq[curr] = left[l]
l += 1
else:
seq[curr] = right[r]
r += 1
curr += 1
(x, rest) = (r, right) if (l == left_size) else (l, left)
while x != len(rest):
seq[curr] = rest[x]
(x, curr) = (x+1, curr+1)
def merge_sort(seq, first, last):
if first + 1 < last:
mid = first + (last-first)//2
merge_sort(seq, first, mid)
merge_sort(seq, mid, last)
merge(seq, first, mid, last)
li = [3, 2, 1, 88, 1000, -1]
merge_sort(li, 0, len(li))
print(li)
ls = ["aaa", "1234", "hello", "google", "hi"]
merge_sort(ls, 0, len(ls))
print(ls)
"""
output:
[1, 2, 3, 4]
['1234', 'aaa', 'google', 'hello', 'hi']
"""
|
240a74d9db267042a8b4788f518f6c6eeef889f7
|
JohnWang7802/python-100-
|
/100_10.py
| 405 | 4.0625 | 4 |
#问题010:按照年月日时分秒的形式打印出当前时间,等待一秒后继续打印
#【思路分析】继续学习time模块里的属性
'''
time.localtime()获取当前时间,time.strftime()把时间型变量变成字符串
'''
import time
for a in range(10):
print(time.strftime('今天是:%Y-%m-%d ,现在是%H:%M:%S',time.localtime(time.time())))
time.sleep(1)
|
086ba040691e7521c76060e1efbfe682eeefdf0f
|
Vizonery/Vizonery-Proof-of-Concept
|
/Algorithm2.py
| 3,027 | 3.8125 | 4 |
# Source: https://www.kaggle.com/dileep070/logistic-regression
# import libraries
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import matplotlib.mlab as mlab
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import scipy.stats as st
import statsmodels.api as sm
import numpy as np
import pandas as pd
from statsmodels.tools import add_constant as add_constant
import sklearn
from sklearn import metrics
# suppress warnings
import warnings
warnings.filterwarnings('ignore')
# import dataset
heart_df = pd.read_csv('framingham.csv')
heart_df.drop(['education'], axis=1, inplace=True)
print(heart_df.head())
# rename column name
heart_df.rename(columns={'male': 'Sex_male'}, inplace=True)
print(heart_df.head())
# check for missing values
print(heart_df.isnull().sum())
# count missing values and drop them
count = 0
for i in heart_df.isnull().sum(axis=1):
if i > 0:
count = count+1
print('Total number of rows with missing values is ', count)
print('since it is only', round((count/len(heart_df.index))*100),
'percent of the entire dataset the rows with missing values are excluded.')
heart_df.dropna(axis=0, inplace=True)
print(heart_df.describe())
# check null values again
print(heart_df.isnull().sum())
# add constant
heart_df_constant = add_constant(heart_df)
print(heart_df_constant.head())
# logistic regression
# Chi-square Test
st.chisqprob = lambda chisq, df: st.chi2.sf(chisq, df)
cols = heart_df_constant.columns[:-1]
model = sm.Logit(heart_df.TenYearCHD, heart_df_constant[cols])
result = model.fit()
print(result.summary())
# P-value approach
def back_feature_elem(data_frame, dep_var, col_list):
while len(col_list) > 0:
model = sm.Logit(dep_var, data_frame[col_list])
result = model.fit(disp=0)
largest_pvalue = round(result.pvalues, 3).nlargest(1)
if largest_pvalue[0] < (0.05):
return result
break
else:
col_list = col_list.drop(largest_pvalue.index)
result = back_feature_elem(heart_df_constant, heart_df.TenYearCHD, cols)
# interpreting results: Odds Ration, Confidence Intervals and Pvalues
params = np.exp(result.params)
conf = np.exp(result.conf_int())
conf['OR'] = params
pvalue = round(result.pvalues, 3)
conf['pvalue'] = pvalue
conf.columns = ['CI 95%(2.5%)', 'CI 95%(97.5%)', 'Odds Ratio', 'pvalue']
print((conf))
# splitting data to train and test split
new_features = heart_df[['age', 'Sex_male', 'cigsPerDay',
'totChol', 'sysBP', 'glucose', 'TenYearCHD']]
x = new_features.iloc[:, :-1]
y = new_features.iloc[:, -1]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.20, random_state=5)
logreg = LogisticRegression()
logreg.fit(x_train, y_train)
y_pred = logreg.predict(x_test)
# confusion matrix
confusion_matrix = metrics.confusion_matrix(y_test, y_pred)
print(confusion_matrix)
# model accuracy
print(sklearn.metrics.accuracy_score(y_test, y_pred))
|
6ce13ee09cdde5cb6b92044ce46d43841f813091
|
BarbarianJan/MyRoadtoPython
|
/variables.py
| 1,788 | 3.578125 | 4 |
#!/bin/python3
#Game variables that can be changed!
#game background colour.
BACKGROUNDCOLOUR = 'lightblue'
#map variables.
MAXTILES = 50
MAPWIDTH = 15
MAPHEIGHT = 15
#variables representing the different resources.
DIRT = 0
GRASS = 1
WATER = 2
BRICK = 3
WOOD = 4
SAND = 5
PLANK = 6
GLASS = 7
#a list of all game resources.
resources = [DIRT,GRASS,WATER,BRICK, WOOD, SAND, PLANK, GLASS]
#the names of the resources.
names = {
DIRT : 'dirt',
GRASS : 'grass',
WATER : 'water',
BRICK : 'brick',
WOOD : 'wood',
SAND : 'sand',
PLANK : 'plank',
GLASS : 'glass'
}
#a dictionary linking resources to images.
textures = {
DIRT : 'dirt.gif',
GRASS : 'grass.gif',
WATER : 'water.gif',
BRICK : 'brick.gif',
WOOD : 'wood.gif',
SAND : 'sand.gif',
PLANK : 'plank.gif',
GLASS : 'glass.gif'
}
#the number of each resource the player has.
inventory = {
DIRT : 10,
GRASS : 10,
WATER : 10,
BRICK : 0,
WOOD : 5,
SAND : 1,
PLANK : 0,
GLASS : 0
}
#the player image.
playerImg = 'player.gif'
#the player position.
playerX = 0
playerY = 0
#rules to make new resources.
crafting = {
BRICK : { WATER : 1, DIRT : 2 },
SAND : { WATER : 2, DIRT : 1},
PLANK : {WOOD : 3},
GLASS : {SAND: 2}
}
#keys for placing resources.
placekeys = {
DIRT : '1',
GRASS : '2',
WATER : '3',
BRICK : '4',
WOOD : '5',
SAND : '6',
PLANK : '7',
GLASS : '8'
}
#keys for crafting tiles.
craftkeys = {
BRICK : 'r',
SAND : 'q',
PLANK : 'u',
GLASS : 'g'
}
#game instructions that are displayed.
instructions = [
'Instructions:',
'Use WASD to move'
]
|
1713c86a70ec5a4d83d26ffacca676e91de3ceed
|
nofatclips/euler
|
/python/problem1.py
| 434 | 4.28125 | 4 |
#!/usr/bin/python
#Problem 1
#05 October 2001
# If we list all the natural numbers below 10
# that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
#def sumAll(max):
# return sum(range(max))
def sureshot(max):
return sum([i for i in range(max) if i%3==0 or i%5==0])
print sureshot(10)
print sureshot(1000)
|
6b2e68649b5be95ab51fe21408877702a1d9eefe
|
stephenosullivan/LT-Code
|
/merge-sorted-array.py
| 669 | 3.640625 | 4 |
__author__ = 'stephenosullivan'
class Solution:
# @param {integer[]} nums1
# @param {integer} m
# @param {integer[]} nums2
# @param {integer} n
# @return {void} Do not return anything, modify nums1 in-place instead.
def merge(self, nums1, m, nums2, n):
count = m + n
m -= 1
n -= 1
while m >= 0 and n >= 0:
count -= 1
if nums1[m] > nums2[n]:
nums1[count] = nums1[m]
m -= 1
else:
nums1[count] = nums2[n]
n -= 1
while n >= 0:
count -= 1
nums1[count] = nums2[n]
n -= 1
|
063342912163848b8832259482ab1707a3022131
|
BeauWilliams97/Practical
|
/Prac02/openingTxt.py
| 152 | 3.8125 | 4 |
__author__ = "Beau Williams"
temp_file = open("temp.txt", "w")
user_name = input(str("What's your name: "))
print(user_name, file=temp_file)
temp_file.close()
|
e9b13919fc878710adceabd565048fa194fd4411
|
narru888/PythonWork-py37-
|
/觀念/LeetCode/Medium/Add_Two_Numbers(鏈結數字串列相加).py
| 1,402 | 3.78125 | 4 |
"""
相加兩個數字鏈表
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 高手寫的
# 思路:
# - 透過指針去操縱鏈表(不影響原鏈表)
# - 從尾數開始相加,並計算進位值
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# 先設定一個虛假起始點
dummy_node = ListNode(0)
# 指標
cursor = dummy_node
# 進位
carry = 0
while l1 or l2:
num1 = l1.val if l1 else 0
num2 = l2.val if l2 else 0
sum = num1 + num2 + carry
carry = sum // 10 # 計算進位值
cursor.next = ListNode(sum % 10) # 餘數
cursor = cursor.next # 指標指到下一個節點
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
# 如果最後一位數還有進位值的話,也要為它創造一個節點
if carry:
cursor.next = ListNode(carry)
# dummy_node是我們創來當起始值的假節點,dummy_node.next開始才是真正的答案
return dummy_node.next
l1 = ListNode(2, ListNode(4, ListNode(3)))
l2 = ListNode(5, ListNode(6))
ret = Solution().addTwoNumbers(l1, l2)
while ret:
print(ret.val)
ret = ret.next if ret else None
|
616091b9c30e1540c0795cf2820a5f1df126c8fe
|
JEMeyer/advent-of-code
|
/2022/02/rps.py
| 1,917 | 4.125 | 4 |
#!/usr/bin/env python
"""
Module Docstring
"""
__author__ = "Joe Meyer"
__license__ = "MIT"
move_to_points = {'A': 1, 'B': 2, 'C': 3}
def play_game(opponent, player):
# tie
if opponent == player:
return 3 + move_to_points[player]
# win
elif (opponent == 'A' and player == 'B') or (opponent == 'B' and player == 'C') or (opponent == 'C' and player == 'A'):
return 6 + move_to_points[player]
#loss
else:
return move_to_points[player]
def pick_move(opponent, outcome):
if outcome == 'X': #loss
if opponent == 'A':
return 'C'
elif opponent == 'B':
return 'A'
else:
return 'B'
if outcome == 'Z': #win
if opponent == 'A':
return 'B'
elif opponent == 'B':
return 'C'
else:
return 'A'
else: # draw
return opponent
def convert_player_move(move, opponent_move = ''):
if opponent_move == '': # straight mapping from XYZ to ABC
if move == 'X':
return 'A'
elif move == 'Y':
return 'B'
else:
return 'C'
else:
return pick_move(opponent_move, move)
def solve_puzzle(games, pt2 = False):
total_score = 0
for game in games:
plays = game.split(' ')
opponent_move = plays[0]
user_input = plays[1]
convert_move_second_param = opponent_move if pt2 else ''
total_score = total_score + play_game(
opponent_move,
convert_player_move(user_input, convert_move_second_param)
)
return total_score
def main():
""" Main entry point of the app """
file_input = open('rps_input.txt', 'r')
lines = file_input.read().splitlines()
score = solve_puzzle(lines, True)
print(score)
if __name__ == "__main__":
""" This is executed when run from the command line """
main()
|
b2111bf44d46fa56d221eb57effdd7399802f5fb
|
dongjunchoi/Python
|
/HELLOPYHON/day02/defTest05multi.py
| 121 | 3.859375 | 4 |
def avgsum(a,b,c):
return (a+b+c)/3, a+b+c
myavg, mysum = avgsum(3, 4, 5)
print("myavg:",myavg)
print("mysum:",mysum)
|
a7292be12231218b5b5035ffc5e756136877c891
|
joaabjb/curso_em_video_python_3
|
/desafio025_procurando_string.py
| 225 | 3.96875 | 4 |
nome = input('Digite o seu nome: ')
cond = 'SILVA' in nome.upper()
print(f'O seu nome tem "Silva"? (True/False): {cond}')
#Outra forma
nome = input('Digite o seu nome: ')
print('Tem Silva no nome?', 'silva' in nome.lower())
|
a4cce1654065a7e7aaec40dafd403e76513b2007
|
Yahyakh69/replacenamewithnumber
|
/replacenamewithnumber.py
| 548 | 3.59375 | 4 |
names="yahya ali saied nourhan faisal nour "
count=[]
cnt=1
names1=names.split()
# counting the numbers of letters in names1
for i in names1 :
for j in i :
count.append(cnt)
cnt +=1
#turning it to string
count_string=[str(counts) for counts in count]
count_string1=[]
for i in names1 :
count_string1.append(count_string[0:len(i)]) #Slicing every count_string with
# each matching name and append it to a new list
x=len(count_string1)
for i in range(x):
print(f"{names1[i]} is {''.join(count_string1[i])}")
|
c8dc0352b5c0e86a0406d58dfa8d0a20499b15b6
|
ArtemAkulov/HackerRank
|
/Algorithms/Implementation/find_digits.py
| 470 | 3.59375 | 4 |
############################################
# #
# HackerRank Implementation Challenges #
# #
# Find Digits #
# #
############################################
t = int(input())
for a0 in range(t):
n = int(input())
print(len([x for x in list(filter(lambda _: _ != '0', list(str(n)))) if n % int(x) == 0]))
|
12988ce6788869ea75a2aee632f7da4ae0ff1e53
|
desertSniper87/codewars
|
/python/test_calculator.py
| 774 | 3.765625 | 4 |
# TODO: Replace examples and use TDD development by writing your own tests
# These are some of the methods available:
# test.expect(boolean, [optional] message)
# test.assert_equals(actual, expected, [optional] message)
# test.assert_not_equals(actual, expected, [optional] message)
# You can use Test.describe and Test.it to write BDD style test groupings
import unittest
from calculator_jolaf import *
calc = Calculator()
class TestClass(unittest.TestCase):
def test_calculator(self):
self.assertEqual(calc.evaluate("2 / 2 + 3 * 4 - 6"), 7.0)
self.assertEqual(calc.evaluate("2 - 3 - 4"), -5.0)
self.assertEqual(calc.evaluate("2 + 3 * 4 / 3 - 6 / 3 * 3 + 8"), 8.0)
def main():
unittest.main()
if __name__=="__main__":
main()
|
18597a84f34d34304da443b9c6a5d31e613edc3a
|
blesoft/mapApp_onplay
|
/chainer_tuto/test1-6.py
| 524 | 3.703125 | 4 |
class DateManager:
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
def add_x(self,delta):
self.x += delta
def add_y(self,delta):
self.y += delta
def add_z(self,delta):
self.z += delta
def sum(self):
return self.x + self.y + self.z
date_manager = DateManager(2,3,5)
print(date_manager.sum())
date_manager.add_x(4)
print(date_manager.sum())
date_manager.add_y(0)
print(date_manager.sum())
date_manager.add_z(-9)
print(date_manager.sum())
|
94bb96d8dbf9540053312377e674577ca83a0c52
|
felipeonf/Exercises_Python
|
/exercícios_fixação/Compressão-Listas.py
| 246 | 3.875 | 4 |
lista_palavras = ['gato','rato','coelho']
lista_letras = []
[lista_letras.append(palavra[caracter]) for palavra in ['gato','rato','cachorro'] for caracter in range(len(palavra)) if palavra[caracter] not in lista_letras]
print(lista_letras)
|
2a971d77f7be4700cfe516d3e26b89a88bdeefda
|
DeanHe/Practice
|
/LeetCodePython/MaximumLengthOfaConcatenatedStringWithUniqueCharacters.py
| 1,509 | 4.1875 | 4 |
"""
You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All the valid concatenations are:
- ""
- "un"
- "iq"
- "ue"
- "uniq" ("un" + "iq")
- "ique" ("iq" + "ue")
Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26
Explanation: The only string in arr has all 26 characters.
Constraints:
1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i] contains only lowercase English letters.
hints:
1 You can try all combinations and keep mask of characters you have.
2 You can use DP.
"""
from typing import List
class MaximumLengthOfaConcatenatedStringWithUniqueCharacters:
def maxLength(self, arr: List[str]) -> int:
dp = [set()]
for word in arr:
if len(set(word)) < len(word):
continue
word = set(word)
for candidates in dp[:]:
if word & candidates:
continue
dp.append(candidates | word)
return max(len(candidates) for candidates in dp)
|
9fed4e4c377112e721b89c0c44af178a0f351006
|
MACHEIKH/Datacamp_Machine_Learning_For_Everyone
|
/11_Cluster_Analysis_in_Python/3_K-Means_Clustering/impactOfSeedsOnDistinctClusters.py
| 1,140 | 3.671875 | 4 |
# Impact of seeds on distinct clusters
# You noticed the impact of seeds on a dataset that did not have well-defined groups of clusters. In this exercise, you will explore whether seeds impact the clusters in the Comic Con data, where the clusters are well-defined.
# The data is stored in a Pandas data frame, comic_con. x_scaled and y_scaled are the column names of the standardized X and Y coordinates of people at a given point in time.
# Instructions 1/2
# 50 XP
# Import the random class from numpy and initialize the seed with the integer 0.
# Instructions 2/2
# Change your code from the earlier step so that the seed is initialized with a list [1, 2, 1000].
# Import random class
from numpy import random
# Initialize seed
# For instruction 2, random.seed([1,2,1000])
random.seed(0)
# Run kmeans clustering
cluster_centers, distortion = kmeans(comic_con[['x_scaled', 'y_scaled']], 2)
comic_con['cluster_labels'], distortion_list = vq(comic_con[['x_scaled', 'y_scaled']], cluster_centers)
# Plot the scatterplot
sns.scatterplot(x='x_scaled', y='y_scaled',
hue='cluster_labels', data = comic_con)
plt.show()
|
0c259ff231a67ac6c6f3ca13c48624008bcaf32c
|
androdri1998/algorithms
|
/recursion/index.py
| 1,173 | 4.15625 | 4 |
def find_key(arr, current_position):
if(len(arr) == current_position):
return None
if(str(arr[current_position]) == "box_with_key"):
return current_position
return find_key(arr, current_position + 1)
# function's use case
my_arr_with_key = ["box_without_key", "box_without_key", "box_without_key",
"box_without_key", "box_with_key", "box_without_key", "box_without_key", "box_without_key"]
my_arr_without_key = ["box_without_key", "box_without_key", "box_without_key",
"box_without_key", "box_without_key", "box_without_key", "box_without_key"]
index_key_from_my_arr_with_key = find_key(my_arr_with_key, 0)
index_key_from_my_arr_without_key = find_key(my_arr_without_key, 0)
if(index_key_from_my_arr_with_key != None):
print("Box with key found on index: "+str(index_key_from_my_arr_with_key))
else:
print("Box with key not found")
# Output: Box with key found on index: 4
if(index_key_from_my_arr_without_key != None):
print("Box with key found on index: " +
str(index_key_from_my_arr_without_key))
else:
print("Box with key not found")
# Output: Box with key not found
|
502a31fab5d91684bb844dec6ec7a278e5e05079
|
devyueightfive/lib-chalanger
|
/thread/schedule.py
| 1,539 | 3.515625 | 4 |
import sched
import random
import time
import threading
max_work_time = 1
max_works = 10
def do_work(name):
print("{} performs ...".format(name))
time.sleep(max_work_time)
print("!!! {} completed.".format(name))
class TimeWorker(threading.Thread):
def __init__(self, max_time):
super().__init__()
self.max_time = max_time
def run(self):
for z in range(self.max_time):
print("{} sec".format(z))
time.sleep(1)
if __name__ == "__main__":
# create work list
random.seed()
delays = {}
max_delay = 0
for x in range(max_works):
delays[x] = random.randrange(5)
if max_delay < delays[x]:
max_delay = delays[x]
print("Random delays (name:delay) format: ", delays)
print("Max delay is {}".format(max_delay))
print("Work time is", max_work_time)
import operator
sort_dict = sorted(delays.items(), key=operator.itemgetter(1))
print("Sorted delays (name:delay) format: ", dict(sort_dict))
# create scheduler with delay_func == time.sleep
s = sched.scheduler(time.time, time.sleep)
for number, delay in delays.items():
s.enter(delay, 1, do_work, argument=(number,))
print("Scheduler queue: ", s.queue)
# time_worker
t = TimeWorker(max_delay + max_works * max_work_time)
t.start()
# block till schedule performs
s.run()
print("Scheduler completed. Thank you for your attention.")
# block till time_worker complete
t.join()
print("Bye Bye!!!")
|
cf7389aa56da9c6c4fa89e734bdb32ece894c81e
|
nicolasmonteiro/Python
|
/Aula funções/funcaocomretorno.py
| 735 | 4.28125 | 4 |
'''
funcoes com retorno
return: finaliza a função. Sai da execução da função
podemos ter diferentes retornos sendo apenas um executado)
função podendo retornar qualquer tipo de dados até multiplos
valores
'''
def quadrado_de_7():
return 7*7
# print(quadrado_de_7())
# print(quadrado_de_7())
# sai da função
'''
def diz_oi():
return 'OI'
print('teste') # nunca será executada
print(diz_oi())
'''
'''
# vários returns
def func_retornos():
v = False
if v:
return 4
elif v is None:
return 3
return 't'
print(func_retornos())
'''
'''
retorna múltiplos valores
'''
def outra_func():
return 2, 3, 4
print(outra_func())
#n1, n2, n3 = outra_func()
#print(n1, n2, n3)
|
44da664b7cc2dcef951d59519499462f1aa4b4d9
|
ajayflynavy/Python-1
|
/Jupyter Notebook/earth/asia/mongolia.py
| 1,594 | 4.34375 | 4 |
# Task : Print the FizzBuzz numbers.
# FizzBuzz is a famous code challenge used in interviews to test basic programming skills.
# It's time to write your own implementation.
# Print numbers from 1 to 100 inclusively following these instructions:
# if a number is multiple of 3, print "Fizz" instead of this number,
# if a number is multiple of 5, print "Buzz" instead of this number,
# for numbers that are multiples of both 3 and 5, print "FizzBuzz",
# print the rest of the numbers unchanged.
numbers = list(range(1,100))
list1=[]
for i in (numbers):
if (i % 5 == 0) and (i % 3 == 0):
result = "FizzBuzz"
list1.append(f"{i} = {result}")
elif i % 3 == 0:
result = "Fizz"
list1.append(f"{i} = {result}")
elif i % 5 == 0:
result = "Buzz"
list1.append(f"{i} = {result}")
else:
result = i
print((result))
print(list1)
# number_list=[]
# for i in range(1, 101):
# if i % 15 == 0:
# number_list.append("FizzBuzz")
# elif i % 3 == 0:
# number_list.append("Fizz")
# elif i % 5 == 0:
# number_list.append("Buzz")
# else:
# number_list.append(i)
# for i in number_list:
# print(i, sep="\n")
numbers = range(1,21)
x = list(filter(lambda x: print("FizzBuzz") if x%3==0 and x%5==0 else (print("Buzz") if x%5==0 else (print("Buzz") if x%3==0 else print(x))),numbers))
numbers = range(1,16)
for i in numbers :
print((lambda x: "Fizzbuzz" if x % 3 == 0 and x % 5 == 0 else("fizz" if x % 3 == 0 else ("buzz" if x % 5 == 0 else x)))(i))
|
1db6e5b424a30aa108a81b31da36e109c39bff63
|
mengzhuo/BFS_knight_moves_py
|
/knight.py
| 3,196 | 3.921875 | 4 |
#!/usr/bin/env python
# encoding: utf-8
"""
Author: Meng Zhuo<[email protected]>
Version: 0.1
"""
import sys
class Point(object):
def __init__(self, x, y, step=0, path=[]):
"""
Point object for knight_move
:x: point x
:y: point y
:step: current step
:returns: Point object
"""
self.x = int(x)
self.y = int(y)
self.step = int(step)
self.path = path
def __repr__(self):
return self.__str__()
def __unicode__(self):
return self.__str__()
def __str__(self):
return u"Point<{0.x}, {0.y}> step={0.step}".format(self)
def knight_move(size, pre_point, des_point):
"""
BFS knight movement
:param pre_point: Point that start with
:param x: destination x
:param y: destination y
:returns: point that can solve problem
"""
size = int(size)
board = [[0 for tmp_y in xrange(size)] for tmp_x in xrange(size)]
queue = [pre_point] # init search queue
rules = ((1, 2), (2, 1), # 1
(1, -2), (2, -1), # 4
(-1, -2), (-2, -1), # 3
(-2, 1), (-1, 2)) # 2
while(queue):
pre_point = queue.pop(0) # get first point
if pre_point.x == des_point.x and pre_point.y == des_point.y:
# for line in board:
# print line
return pre_point
for direction in rules:
next_point = Point(pre_point.x + direction[0],
pre_point.y + direction[1],
pre_point.step + 1,)
if (0 <= next_point.x < size and 0 <= next_point.y < size
and not board[next_point.y][next_point.x]):
# check if new point still inside board
# and next_point is valided
next_point.path = pre_point.path + [next_point]
queue.append(next_point)
board[next_point.y][next_point.x] = 1
def usage():
print """Knight less moves from given point to Right Bottom Corner.
Example: python knight.py -s 8 -x 1 -y 3
-h print this help message
"""
sys.exit(1)
if __name__ == '__main__':
import getopt
try:
opts = getopt.getopt(sys.argv[1:], "s:x:y:h:t:")[0]
except getopt.GetoptError:
usage()
try:
for opt, val in opts:
if opt == "-s":
size = int(val)
assert size > 2 # only great than 3 has solution
elif opt == "-x":
x = int(val)
assert size > x >= 0
elif opt == "-y":
y = int(val)
assert size > y >= 0
elif opt == "-h":
usage()
result = knight_move(size, Point(x, y), Point(size - 1, size - 1))
if result:
for point in result.path:
print "step:{0.step} ({0.x},{0.y})".format(point)
else:
print "No solution"
except (ValueError, AssertionError) as err:
if err is ValueError:
print "Please input integer"
else:
print "Please input positive number less than {0}".format(size)
usage()
|
0d6794565d050bd714498031a7ae47da09c7e4a2
|
indo-seattle/python
|
/Suresh/Week1Exercise12.py
| 202 | 4.1875 | 4 |
#Write a Python program that takes x = 1, y = 1.1, and z = 1.2j and print their data type using type function. Ex: print(type(x))
x = 1
y = 1.1
z = 1.2j
print (type(x))
print (type(y))
print (type(z))
|
d7b540fb3d31d4bb45493e5b2fa989928bbf41c6
|
furas/python-examples
|
/pyqt5/replace-content-in-window/main.py
| 1,657 | 3.703125 | 4 |
# date: 2019.08.26
# https://stackoverflow.com/questions/57656340/how-to-show-another-window
from PyQt5 import QtWidgets
class MainWidget(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__()
self.parent = parent
self.button = QtWidgets.QPushButton("Show Second Window", self)
self.button.clicked.connect(self.show_second_window)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button)
self.show()
def show_second_window(self):
self.close()
self.parent.set_content("Second")
class SecondWidget(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__()
self.parent = parent
self.button = QtWidgets.QPushButton("Close It", self)
self.button.clicked.connect(self.show_second_window)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button)
self.show()
def show_second_window(self):
self.close()
self.parent.set_content("Main")
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QVBoxLayout(self)
self.set_content("Main")
self.show()
def set_content(self, new_content):
if new_content == "Main":
self.content = MainWidget(self)
self.layout.addWidget(self.content)
elif new_content == "Second":
self.content = SecondWidget(self)
self.layout.addWidget(self.content)
app = QtWidgets.QApplication([])
main = MainWindow()
app.exec()
|
a8cf75168b60d4a0ec3e0765582457d3d38d36c6
|
f-leno/checkers-AI
|
/experiment/experiment.py
| 7,253 | 3.546875 | 4 |
"""
Tic Tac Toe Experiment Class.
This class will define which agents_checker will be learning in the environment,
whether if a GUI should be shown, and initiate all learning process.
Author: Felipe Leno ([email protected])
"""
from agents.expertCheckersAgent import ExpertCheckersAgent
from environment.checkersEnvironment import CheckersEnvironment
from output.nullExperimentRecorder import NullExperimentRecorder
class ExperimentCheckers:
agentO = None #Agent playing with O marker
agentX = None #Agent playing with X marker
totalEpisodes = None # Maximum number of Episodes (when applicable)
totalSteps = None #Maximum number of Steps (when applicable)
stopByEps = None
experimentRecorder = None #Class for saving experimental results
showGUI = None #Should the GUI be shown?
storeVideo = None #Should the video of the game play be recorded?
currentEpisode = None #Current number of episodes
currentStep = None #Current number of steps
#In case the training process finishes during a game, and then agentX wins the game
#right after the return to the training phase, an error might happen without these variables
recordStateO = None
recordActionO = None
countFict = None
def __init__(self,agentO =None, agentX = None, environment = None, totalEpisodes = None,
totalSteps = None, countFict = True, experimentRecorder = None, showGUI = False, storeVideo=False):
"""
agentO,agentX: Agents playing with O and X markers. Both should be objects of the abstract class Agent.
Omit the parameter to create an expert agent.
environment: The environment representing the task to be solved
totalEpisodes: maximum number of episodes to execute (omit this parameter if stopping learning by number of steps)
totalSteps: Maximum number of steps to execute (omit this parameter if stopping learning by episodes)
countFict: Should the experiment recorder count steps taken when facing the simulated agent?
showGUI: Should the game be displayed in a screen (much slower).
storeVideo: If true, a video of the agent playing will be recorded
"""
#Basically, initializing variables
if(totalEpisodes == None):
self.stopByEps = False
else:
self.stopByEps = True
if agentO == None:
self.agentO = ExpertCheckersAgent()
else:
self.agentO = agentO
if agentX == None:
self.agentX = ExpertCheckersAgent()
else:
self.agentX = agentX
self.totalEpisodes = totalEpisodes
self.totalSteps = totalSteps
self.showGUI = showGUI
self.storeVideo = storeVideo
self.environment = CheckersEnvironment()
if experimentRecorder == None:
self.experimentRecorder = NullExperimentRecorder()
else:
self.experimentRecorder = experimentRecorder
self.currentEpisode = 0
self.currentStep = 0
self.countFict = countFict
def swap_agents(self):
"""
The agents_checker swap side
"""
aux = self.agentO
self.agentO = self.agentX
self.agentX = aux
self.agentO.set_marker("O")
self.agentX.set_marker("X")
def run(self):
"""
Runs the experiment according to the given parameters
"""
#Give references to agents_checker and environment
self.agentO.set_environment(self.environment, "O")
self.agentX.set_environment(self.environment, "X")
self.environment.set_agents(self.agentO,self.agentX)
rewardO = 0
actionO = None
#Main perception-action loop
while not self.stop_learning():
doubleUpdate = False
#In this loop the turn of the two agents_checker will be processed, unless the game is over
stateX = self.environment.get_state()
#Get agent action
actionX = self.agentX.select_action(stateX)
#Applies state transition
self.environment.step(actionX)
#If this is a terminal state, "O" lost the game and should be updated,
#If this is not the case, the agent makes its move
stateO = self.environment.get_state()
if not self.environment.terminal_state():
#Making the move...
actionO = self.agentO.select_action(stateO)
self.environment.step(actionO)
doubleUpdate = True
#Updating...
statePrime = self.environment.get_state()
#Process rewards for agent O
if self.recordStateO is not None:
self.environment.process_rewards(pastState = self.recordStateO,currentState=stateO,agentMarker='O')
rewardO = self.environment.get_last_rewardO()
self.agentO.observe_reward(self.recordStateO,self.recordActionO,stateO,rewardO)
self.recordStateO = stateO
self.recordActionO = actionO
if self.environment.terminal_state() and doubleUpdate:
self.environment.process_rewards(pastState = stateO,currentState=statePrime,agentMarker='O')
rewardO = self.environment.get_last_rewardO()
self.agentO.observe_reward(stateO,actionO,statePrime,rewardO)
#Process rewards for agent X
self.environment.process_rewards(pastState = stateX,currentState=statePrime,agentMarker='X')
rewardX = self.environment.get_last_rewardX()
#Update agent policy
self.agentX.observe_reward(stateX,actionX,statePrime,rewardX)
#Record step, if required
self.experimentRecorder.track_step(stateX,actionX,actionO,statePrime,rewardX,rewardO)
self.currentStep += 1
#Check if the episode is over
if self.environment.terminal_state():
self.currentEpisode += 1
self.recordStateO = None
self.recordActionO = None
self.experimentRecorder.end_episode(finalState = self.environment.currentState)
self.environment.reset()
rewardO = 0
rewardX = 0
#Changes the learning agent side
self.swap_agents()
#Reseting environment
self.currentEpisode = 0
self.currentStep = 0
def stop_learning(self):
"""Checks if the experiment should stop now"""
stop = False
if self.stopByEps:
if self.currentEpisode >= self.totalEpisodes:
stop = True
else:
if self.currentStep >= self.totalSteps:
stop = True
return stop
|
b10f63c68a06d6624ed214a3cc6be391540a2b97
|
chronologie7/killps
|
/killps.py
| 2,198 | 3.671875 | 4 |
#!/usr/bin/env python3
import psutil
import sys
import re
def psListFunc(psName):
pslist = psutil.pids()
psListMach = []
for psid in pslist:
p = psutil.Process(psid)
if psName in p.name().lower():
psListMach.append({p.name(): psid})
return psListMach
def psTerminate(psList):
if len(psList) == 1:
for id in psList[0].values():
psid = id
p = psutil.Process(psid)
p.terminate()
p.wait()
elif len(psList) > 1:
print("Process list match:")
psnum = 0
for data in psList:
for name in data.keys():
print(f"{psnum}. {name}")
psnum += 1
try:
psnum = int(input("Choice what process terminate (number): "))
except KeyboardInterrupt:
print("\nKeyboard Interruption")
return None
for id in psList[psnum].values():
psid = id
p = psutil.Process(psid)
p.terminate()
p.wait()
else:
print("the process not exist.")
def help():
print("SCRIPT by chronologie")
print("TERMINATE PROCESS SCRIPT HELP\n")
print("use mode")
print("example:\n")
print("> terminate_process.py <process name>\n")
print("The named process passed by argument that will be the name of this or\nthat it contains in its name will be stopped\n")
print("The script only accepts one argument, two or more arguments will send\nyou to the help guide.\n")
print("If two or more processes match the name passed as an argument, a list\nwill be displayed for you to choose the process you want to terminate.")
def run():
psName = sys.argv[1].lower()
psList = psListFunc(psName)
psTerminate(psList)
def nameCheck():
result = re.search(r"^[\w\.-]+$", sys.argv[1])
if result == None:
return False
else:
return True
sys.argv
if len(sys.argv) == 1 or len(sys.argv) > 2 or "?" in sys.argv[1]:
help()
elif len(sys.argv) == 2:
if nameCheck():
run()
else:
print("process name format incorrect")
|
21b07e5c812f9785f336a072ce8440055c2d4d26
|
robbaralla/sql
|
/sqlSelect.py
| 202 | 3.609375 | 4 |
#select data
import sqlite3
with sqlite3.connect("new.db") as connection:
c = connection.cursor()
for row in c.execute("SELECT firstname, lastname from\
employees"):
print (row[0], row[1])
|
576af3e15f565562a0090f307a94c5531364913d
|
agalyaswami/phython
|
/power.py
| 84 | 3.828125 | 4 |
x=int(input("input a number:"))
y=int(input("input a number:"))
z=pow(x,y)
print(z)
|
ab1c1ca2df9d9aacdf6ad35a8e89352e60b21a79
|
devitos/Task2
|
/task2.py
| 1,605 | 3.5625 | 4 |
import hashlib
import os
import sys
def read_sum_file(sum_file='sum_file.txt'):
sumfile_list = list()
with open(sum_file, 'r') as sum1:
data = list(sum1.read().split('\n'))
for line in data:
if line:
sumfile_list.append({'file_name': line.split(' ')[0],
'hash_method': line.split(' ')[1],
'file_sum': line.split(' ')[2]
})
return sumfile_list
def scan_file(dir_path, input_file, hash_method):
file_dir = os.listdir(dir_path)
if input_file['file_name'] in file_dir:
for file in file_dir:
if file == input_file['file_name']:
with open(os.path.join(dir_path, file), 'rb') as f:
if input_file['file_sum'] == hashlib.new(hash_method, f.read()).hexdigest():
result = 'OK'
else:
result = 'FAIL'
else:
result = 'NOT FOUND'
return result
def check_sum_file(sum_file, dir_path):
sum_file_list = read_sum_file(sum_file)
for file in sum_file_list:
result = scan_file(dir_path, file, file['hash_method'])
print(file['file_name'], result)
return
if __name__ == '__main__':
if len(sys.argv) == 3:
check_sum_file(sys.argv[1], sys.argv[2])
else:
print('Неверное количество аргументов!')
check_sum_file('D:\\NEW_Project\\Task2\\sum_file.txt', 'D:\\NEW_Project\\Task2')
|
8f19be7dd5628375e37eb6cbf0ff186af6c412de
|
RosemaryDavy/Python-Code-Samples
|
/Problem2CheckRange.py
| 492 | 4.15625 | 4 |
#Rosemary Davy
#February 25, 2021
#Problem 2: Write a Python function to check whether a
#number is in a given range. Use range(1,10).
#Print whether the number is in or not in the range
import math
def checkRange(x): #define how to check if a number is in the range
if num in range (1, 10):
print("The number" , num , "is in the range (1,10).")
else:
print("The number" , num , "is outside the range (1,10).")
num = int(input("Please enter a number:"))
checkRange(num)
|
46e15a9a2c027751d8b638a637eb83fb8521d5bf
|
albininovics/python
|
/car.py
| 405 | 3.703125 | 4 |
class Cars:
def __init__(self, name, price, colour):
self.name = name
self.price = price
self.colour = colour
def start(self):
print(self.name + "Engine Started")
car1 = Cars("Kia", 25000, "Red")
car2 = Cars("Tata", 15000, "white")
car1.colour = "Blue"
print(car1.name, car1.price, car1.colour)
print(car2.name, car2.price, car2.colour)
car1.start()
car2.start()
|
5fabfa7022c300bbe1f0cea99be5956ac4d56df4
|
ManuelBerrueta/CPTS437-Machine_Learning
|
/3HW_HumanActivity/3HW.py
| 8,584 | 3.703125 | 4 |
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.metrics import roc_curve
from sklearn.metrics import confusion_matrix
# Majority Classifier
from sklearn.dummy import DummyClassifier
# Tree
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
from matplotlib import lines
from mpl_toolkits.mplot3d import Axes3D
def read_data(fileName):
data = np.genfromtxt(fileName, delimiter=',', dtype="str")
# print("DATA:\n", data)
return data
print("Load DATA\n")
indata = read_data("alldata.csv")
#! Split Features & Target Label from Data
X_features = indata[:, :-1] # Get all the data but the last column
y_label = indata[:, -1] # Load the 3rd feature6
print("Features:\n", X_features)
print("Target Labels:\n", y_label)
#! Split the data, keep 1 third for testing
print("Split Data\n")
X_trainfeatures, X_testfeatures, y_traininglabels, y_testlabels = train_test_split(
X_features, y_label, test_size=.3) # , random_state = 7919)
print("Target Labels Test:", y_traininglabels)
'''First, write code to calculate accuracy and a macro f-measure using 3-fold
cross validation for two classifiers: a majority classifier and a decision tree
classifier. You can use the sklearn libraries for the classifiers but write
your own code to perform cross validation and calculation of the
performance measures.'''
def accuracy(TP, FP, TN, FN):
P = TP + FN
N = TN + FP
return ((TP + TN) / (P + N))
def precision(TP, FP):
return (TP / (TP + FP))
def recall(TP, FN):
return (TP / (TP + FN))
def F_Measure(TP, FP, TN, FN):
P = precision(TP, FP)
R = recall(TP, FN)
F = ((2 * P * R) / (P + R))
return F
# def get_TPR()
# TODO: Code to macro f-measure using 3-fold cross validation
def cross_validate(algo, data, K):
pass
clfMajority = DummyClassifier()
clfMajority.fit(X_trainfeatures, y_traininglabels)
clfMajorityPrediction = clfMajority.predict(X_testfeatures)
tn, fp, fn, tp = confusion_matrix(y_testlabels, clfMajorityPrediction).ravel()
clfMajority_conf_matrix = confusion_matrix(y_testlabels, clfMajorityPrediction)
print("Accuracy of Majority Classifier: " + str(accuracy(tp, fp, tn, fn)))
print("F-Measure of Majority Classifier: " + str(F_Measure(tp, fp, tn, fn)))
clfTree = DecisionTreeClassifier(criterion="entropy") # Unbounded
clfTree.fit(X_trainfeatures, y_traininglabels)
clfTreePrediction = clfTree.predict(X_testfeatures)
tn, fp, fn, tp = confusion_matrix(y_testlabels, clfTreePrediction).ravel()
clfTree_conf_matrix = confusion_matrix(y_testlabels, clfTreePrediction)
print("Accuracy of Decision Tree Classifier: " + str(accuracy(tp, fp, tn, fn)))
print("F-Measure of Decision Tree Classifier: " + str(F_Measure(tp, fp, tn, fn)))
'''Second, provide your observations on the results. Why do the two performance
measures provide such different results? Why do the two classifiers perform
so differently on this task?'''
''' They provide such different results because of their biases and they way
they categorize the data. They perform so different because the Majority
Classifier is really an either or classifier where literally the majority wins,
where as the Tree will branch out to look at the possibilities of being in one
class or another. '''
'''Third, write code to generate and plot an ROC curve
(containing at least 10 points). Generate two ROC curves, one based on a
decision tree classifier with a depth bound of 2 and one with an unbounded
decision tree. You can use the sklearn predict_proba function to provide a
probability distribution over the class values, but create your own
ROC curve rather than using the sklearn roc_curve function. Ideally you
would generate the ROC curve on a holdout subset of data, but for
simplicity in this case you can build it using the entire dataset.'''
# TODO: predict_proba - How does it help?
# TODO: ROC Curve - How To
""" def get_ROC_Curve_points(y_clf_proba_predicted, y_test):
roc_points = {}
for prob_threshold in np.arange(0.0, 1.0, 0.05):
#y_pred = [0 if ypp[0] >= prob_threshold else 1 for ypp in y_clf_proba_predicted]
#tp, fp, tn, fn = compute_confusion_matrix(y_test, y_pred)
tp, fp, fn, tp = confusion_matrix(
y_testlabels, y_clf_proba_predicted).ravel()
tpr = float(tp) / float(tp + fn)
fpr = float(fp) / float(fp + tn)
if fpr in roc_points:
roc_points[fpr].append(tpr)
else:
roc_points[fpr] = [tpr]
x1 = []
y1 = []
for fpr in roc_points:
x1.append(fpr)
tprs = roc_points[fpr]
avg_tpr = sum(tprs) / len(tprs)
y1.append(avg_tpr)
#return x1, y1
return roc_points """
""" def get_ROC_Curve_points(y_pred_proba, y_test):
roc_points = {}
for prob_threshold in np.arange(0.0, 1.0, 0.05):
y_pred = [0 if ypp[0] >=
prob_threshold else 1 for ypp in y_pred_proba]
tp, fp, tn, fn = confusion_matrix(y_test, y_pred)
tpr = float(tp) / float(tp + fn)
fpr = float(fp) / float(fp + tn)
if fpr in roc_points:
roc_points[fpr].append(tpr)
else:
roc_points[fpr] = [tpr]
x1 = []
y1 = []
for fpr in roc_points:
x1.append(fpr)
tprs = roc_points[fpr]
avg_tpr = sum(tprs) / len(tprs)
y1.append(avg_tpr)
return x1, y1 """
boundedTree = DecisionTreeClassifier(criterion="entropy", max_depth=2)
boundedTree.fit(X_trainfeatures, y_traininglabels)
boundedPrediction = boundedTree.predict(X_testfeatures)
tn, fp, fn, tp = confusion_matrix(y_testlabels, boundedPrediction).ravel()
bounded_conf_matrix = confusion_matrix(y_testlabels, boundedPrediction)
print("Confusion Matrix")
print("TN: %d | FP: %d | FN: %d | TP: %d" % (tn, fp, fn, tp))
print(bounded_conf_matrix)
""" boundScore = boundedTree.predict_proba(X_testfeatures)
boundScore = np.array(boundScore)
print("Bounbded Score:")
print(boundScore)
"""
#! For calculating ROC Curve Points
boundedPrediction = boundedTree.predict_proba(X_testfeatures)
boundedPrediction = np.array(boundedPrediction)
y_testlabels_bin = label_binarize(y_testlabels, neg_label=0, pos_label=1, classes=[0, 1])
y_testlabels_bin = np.hstack((1 - y_testlabels_bin, y_testlabels_bin))
# * TESTING***
print("Proba Prediction")
print(boundedPrediction)
print("y_test")
print(y_testlabels_bin)
boundedPrediction = boundedTree.predict(X_testfeatures)
#bounded_x, bounded_y = get_ROC_Curve_points(boundedPrediction, y_testlabels)
#points = get_ROC_Curve_points(boundedPrediction, y_testlabels)
#points = get_ROC_Curve_points(boundedPrediction, y_testlabels_bin)
#! testing new roc_curve
x, y = get_ROC_Curve_points(boundedPrediction, y_testlabels_bin)
print("POINTS")
print(x, y)
unboundedTree = DecisionTreeClassifier(criterion="entropy") # Unbounded
unboundedTree.fit(X_trainfeatures, y_traininglabels)
unboundedPrediction = unboundedTree.predict(X_testfeatures)
tn, fp, fn, tp = confusion_matrix(y_testlabels, unboundedPrediction).ravel()
unbounded_conf_matrix = confusion_matrix(y_testlabels, unboundedPrediction)
print("Confusion Matrix")
print(tn, fp, fn, tp)
print(unbounded_conf_matrix)
""" unboundedScore = unboundedTree.predict_proba(X_testfeatures)
unboundedScore = np.array(unboundedScore)
print("Unbounbded Score:")
print(unboundedScore)
"""
#! For calculating ROC Curve Points
unboundedPrediction = unboundedTree.predict(X_testfeatures)
#unbounded_x, unbounded_y = get_ROC_Curve_points(unboundedPrediction, y_testlabels)
points = get_ROC_Curve_points(boundedPrediction, y_testlabels)
""" print("Unbounded_x")
print(unbounded_x)
print("Unbounded_y")
print(unbounded_y)
for xpoint in unbounded_x:
print(xpoint);
for ypoint in unbounded_y:
print(xpoint); """
print("ROC POINTS TEST")
print(points)
# SKlearn roc curve for testing
""" plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.legend(loc = 'lower right')
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.tile("ROC Curve)
plt.show() """
|
06886571d599a96edf291a391a8686f04425b200
|
unsortedtosorted/elgoog
|
/Easy/dp/climbStairs.py
| 584 | 3.625 | 4 |
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
self.v={}
def climb(n):
if n in self.v:
return self.v[n]
if n<=0:
return 0
elif n==1:
return 1
elif n==2:
return 2
else:
x = climb(n-1)+climb(n-2)
self.v[n]=x
return climb(n-1)+climb(n-2)
return climb(n)
|
be28ab57d0a0d6923e5b14ed685b112b810a4fb5
|
calam1/coursera
|
/ucsd_algorithms/ucsd_course_1/week_2/greatest_common_divisor.py
| 623 | 3.5625 | 4 |
#python3
import sys
input = input()
inputs = [int(i) for i in input.split()]
a = inputs[0]
b = inputs[1]
#print('a {} b {}'.format(a, b))
def naive_gcd(a, b):
maximum = -sys.maxsize-1
for i in range(1, a+b+1):
if a % i == 0 and b% i == 0:
maximum=i
return maximum
def euclidean_solution(A, B):
# base case
if B == 0: return A
remainder = A % B
#print('remainder {}'.format(remainder))
return euclidean_solution(B, remainder)
#print('naive solution {}'.format(naive_gcd(a, b)))
#print('euclidean solution {}'.format(euclidean_solution(a, b)))
print(euclidean_solution(a, b))
|
6c9180a85d22827a9063789f4c099e7c5947ecae
|
parhamgh2020/kattis
|
/Riječi.py
| 290 | 3.671875 | 4 |
n = int(input())
s = 'A'
for i in range(1, n + 1):
if i == 1:
s = s.replace('A', 'B')
elif i == 2:
s += 'A'
elif s[-1] == 'A':
s += 'B'
elif s[-1] == 'B' and s[-2] == 'B':
s += 'A'
else:
s += 'B'
print(s.count('A'), s.count('B'))
|
c3012e45d00a12646232fa63c7eaa43cae9c565f
|
alex-gehrig/geoextractor
|
/geoextractor.py
| 1,803 | 3.515625 | 4 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import glob
import csv
"""Grab the country-codes out of already existing txt-files which
contain the results of 'whois' and write them in a csv-file ordered
descending by occurance"""
# define an empty list to store the temporary results
country_list = []
# assuming that every file containing the whois-data has a filename
# of the type in the brackets of glob.glob
for file in glob.glob('whois*.txt'):
with open(file) as source:
data = source.readlines() # all the lines will be read at once
for line in data:
line = line.strip()
# we want only the lines starting with "country:"
if line.startswith('country:') or line.startswith('Country:'):
country_list.append(line)
break
#defining an empty dictionary for counting the country-codes
lst = {}
# looping through the list, splitting the elements and exctracting only the country-code
for item in country_list:
pieces = item.strip().split(":")
c_code = pieces[1].strip()
# print(c_code) # for debugging purposes
lst[c_code] = lst.get(c_code, 0) + 1
# creating an empty list as "hitlist"
hitlist = []
# loop through the dictionary, write the tuples within the created list with the count
# as the first entry followed by the corresponding country-code
for c_code, count in lst.items():
hitlist.append((count, c_code))
# sort the hitlist in descending order based on how often the ip-address was detected
hitlist.sort(reverse=True)
# write results in a csv-file
target = open("countries.csv", "w")
for item in hitlist:
csv.writer(target).writerow(item)
last_row = [len(country_list), "Total"]
csv.writer(target).writerow(last_row)
target.close() # close the target-file when work is done
|
0ed31e700c3f744fb8d38f0d0ab3331abdae694f
|
zhangjiang1203/Python-
|
/作业/第一天作业/01-zuoye.py
| 2,938 | 3.6875 | 4 |
import os
def login():
flag = True
while flag:
# 用户是否存在
users = getUseraccount()
for user in users:
print(user)
isexist = False
account = input('请输入您的账号:')
psw = input("请输入您的密码:")
for user in users:
if account in user.values():
isexist = True
flag = int(user['loginCount'])
if flag == 3:
print('您登录密码输入错误次数过多,账号已被锁定')
flag = False
break
#拿到对应的password和count值
if psw == user['password']:
print('登录成功')
#重置用户登录次数
users.remove(user)
user['loginCount'] = 0
users.append(user)
changAllAccount(users)
flag = False
break
else:
flag+=1
#修改用户信息
users.remove(user)
user['loginCount'] = flag
users.append(user)
changAllAccount(users)
if flag == 3:
print('密码输入错误3次,账号已被锁定')
flag = False
break
else:
print('密码输入错误%s次,请重试' %flag)
break;
if not isexist:
print('用户不存在,请重试')
#编辑用户
file_name = 'account.txt'
def getUseraccount():
#文件是否存在
if os.path.isfile(file_name):
with open(file_name, 'r+') as file_object:
contents = file_object.readlines()
users = []
for line in contents:
templine = line.strip()
if not len(templine) or line.startswith('#'):
continue
#字符串转字典
users.append(eval(templine));
return users
else:
with open(file_name, 'a+') as object:
users = [{'account': 'zhang', 'password': '123456', 'loginCount': 2},
{'account': 'wang', 'password': '123456', 'loginCount': 0},
{'account': 'guo', 'password': '123456', 'loginCount': 1},
{'account': 'xiang', 'password': '123456', 'loginCount': 0}]
for value in users:
account = str(value)
object.write(account + '\n')
return users
#存储修改用户的群组
def changAllAccount(account):
with open(file_name, 'w+') as file_object:
for value in account:
user = str(value)
file_object.write(user + '\n')
#开始登录
# login()
|
4315f9e173190d09f7c6503af70764beaddff525
|
Kadus90/PyChex
|
/start.py
| 1,470 | 3.546875 | 4 |
""" This is the main module for PyChex. """
import sys, pygame, logging
from constants import *
from Board import Board
from Square import Square
# start pygame
pygame.init()
screen = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE))
screen.fill(SCREEN_BACKGROUND)
done = False
clock = pygame.time.Clock()
while not done:
# check to see if user pressed a key or click a mouse
pressed = pygame.key.get_pressed()
clicked = pygame.mouse.get_pressed()
# check for Control modifier key
ctrl_held = pressed[pygame.K_LCTRL] or pressed[pygame.K_RCTRL]
for event in pygame.event.get():
# check if user presses x button in corner to close window
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
# check if ctrl_w is pressed to to close window
if event.key == pygame.K_w and ctrl_held:
done = True
# esc also closes window
if event.key == pygame.K_ESCAPE:
done = True
# Watches for mouse clicks
if event.type == pygame.MOUSEBUTTONDOWN:
game_board.click_check()
# instantiate game board and draw to screen
game_board = Board(True, BOARD_WIDTH, BOARD_HEIGHT, BACKGROUND, FOREGROUND, MARGIN_SIZE, SQUARE_SIZE)
game_board.draw(screen)
"""
# Generates pieces
game_board.piece_start(screen)
"""
pygame.display.flip()
|
7bbf26670a2e6dee11d2cad0ab96f15a2b0e52c1
|
Saurabh-153/IMP_OOPS_Python
|
/3. self, cls, static method/3. Class Static Method and Static Method.py
| 4,239 | 3.953125 | 4 |
'''
Difference between Instance Variable and Class Variable ?
How to change a regular method to a class method ?
A regular method is the one which takes self as a 1st argument, where as a
class method takes class as an 1st argument. This can be acheived by adding
@classmethod on top of any method know as decorator.
Just like instance is called by self, class is called by cls
Self Method: Passes self as argument
Class Method - Passes cls as argument
Static Method - Passes nothing as argument'''
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay*1.04) # 4% can be made a class variable
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
print(emp_1.pay)
emp_1.apply_raise()
print(emp_1.pay)
# Class Variable
class Employee:
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
# raise_amount can be accessed only by passing class name or self to it.
# self.raise_amount, or Employee.raise_amount
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
print(emp_2.pay)
emp_2.apply_raise()
print(emp_2.pay)
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
# Updating raise amount using class
# Employee.raise_amount = 1.05
'''In this only raise amount related to both emp_1, 2 are changed'''
# print(Employee.raise_amount)
# print(emp_1.raise_amount)
# print(emp_2.raise_amount)
# Updating raise amount using class
'''In this only raise amount related to emp_1 is changed'''
emp_1.raise_amount = 1.05
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
'''Above concept palys imp role as func apply_raise will give different results
if we apply self or Employee to it'''
############################################################################
'''Example of a case where self will not make sense. Creating no of employees and class
varaible and incrementing it as we add more employees as object.'''
class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amt = amount
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay)
@staticmethod
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
Employee.set_raise_amt(1.05)
print(Employee.raise_amt)
print(emp_1.raise_amt)
print(emp_2.raise_amt)
print('Method 1')
emp_str_1 = 'John-Doe-70000'
emp_str_2 = 'Steve-Smith-30000'
emp_str_3 = 'Jane-Doe-90000'
first, last, pay = emp_str_1.split('-')
new_emp_1 = Employee(first, last, pay)
print(new_emp_1.first)
print(new_emp_1.last)
print(new_emp_1.pay)
print(new_emp_1.email)
print('\nMethod 2')
new_emp_2 = Employee.from_string(emp_str_2)
print(new_emp_2.first)
print(new_emp_2.last)
print(new_emp_2.pay)
print(new_emp_2.email)
import datetime
my_date = datetime.date(2016, 7, 11)
print(Employee.is_workday(my_date))
|
aa145075cfa5d12b11e214f96db502753b24c6a3
|
badlydrawnrob/python-playground
|
/python-bootcamp/object_oriented.py
| 1,356 | 4.15625 | 4 |
## A basic object
class Circle(object):
pi = 3.14
def __init__(self, radius=1):
self.radius = radius
def area(self):
return self.radius * self.radius * self.pi
def setRadius(self, radius):
self.radius = radius
def getRadius(self):
return self.radius
c = Circle()
c.setRadius(2)
print('Radius is: {}'.format(c.getRadius()))
print('Area is: {}'.format(c.area()))
## An inherited object
class Animal(object):
def __init__(self):
print("Animal created")
def whoAmI(self):
print("Animal")
def eat(self):
print("Eating")
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print("Dog created")
def whoAmI(self):
print("Dog")
def bark(self):
print("Woof!")
d = Dog()
print(d.whoAmI(), d.bark())
## Special methods
class Book(object):
def __init__(self, title, author, pages):
print("A book is created")
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f'Title: {self.title}, author: {self.author}, pages: {self.pages}'
def __len__(self):
return self.pages
def __del__(self):
print("A book is destroyed")
book = Book("Python rocks!", "Jose Portilla", 159)
print(book)
print(len(book))
del(book)
|
cd8a30211d1011c8912d764aadaaf5eeee4d268e
|
Axmaaa/mipt_is_proj
|
/header.py
| 5,053 | 3.625 | 4 |
"""Module for working with header of encrypted file."""
import header_pb2
import hashpw
import kdf
import utils
from algorithm import Algorithm
class Header:
"""Class for storing information from the encrypted file header."""
def __init__(self):
self._header = header_pb2.Header()
# Length of the size of header in bytes
self.header_size_len = 8
@property
def algorithm(self):
"""Encryption algorithm."""
return self._header.algorithm # pylint: disable=no-member
@algorithm.setter
def algorithm(self, algorithm):
self._header.algorithm = algorithm
@property
def hash_function(self):
"""Function to hash password."""
return self._header.hash_function # pylint: disable=no-member
@hash_function.setter
def hash_function(self, hash_function):
self._header.hash_function = hash_function
@property
def data_length(self):
"""The length of the payload."""
return self._header.data_length # pylint: disable=no-member
@data_length.setter
def data_length(self, data_length):
self._header.data_length = data_length
def write(self, ofstream):
"""Writes the header to file stream."""
header_bin = self._header.SerializeToString()
header_bin_size = len(header_bin)
ofstream.write(header_bin_size.to_bytes(self.header_size_len, byteorder='little'))
ofstream.write(header_bin)
def read(self, ifstream):
"""Reads a header from a file stream."""
header_size = int.from_bytes(ifstream.read(self.header_size_len), byteorder='little')
header_bin = ifstream.read(header_size)
self._header.ParseFromString(header_bin)
def add_user(self, symmkey, password=None, pubkey_file=None):
"""Adds to the header a user who can decrypt the file.
:param symmkey: key for symmetric key algorithm
:type symmkey: bytes
:param password: password (in case of symmetric-key encryption)
:type: bytes|NoneType
:param pubkey_file: file with public key (in case of hybrid encryption)
:type pubkey_file: str|NoneType
"""
algorithm = Algorithm(self.algorithm)
if algorithm.is_symmetric() and password is None:
raise ValueError('Algorithm is symmetric, but password is None')
if not algorithm.is_symmetric() and pubkey_file is None:
raise ValueError('Algorithm is hybrid, but public key file is None')
user = self._header.users.add() # pylint: disable=no-member
if algorithm.is_symmetric():
user.key_salt = kdf.gensalt()
key_pw_hash = kdf.kdf(password, user.key_salt, algorithm.key_data_size)
hashf_cls = hashpw.HashFunc(self.hash_function).cls
_hash = hashf_cls(password)
user.pw_salt = _hash.salt
user.uid = _hash.hash()
user.enkey = utils.xor_bytes(key_pw_hash, symmkey)
else:
public_cipher = algorithm.public_cipher()
public_key = public_cipher.import_key(pubkey_file)
padded_symmkey = utils.pad(symmkey, public_cipher.max_data_size)
user.uid = public_key.export_key('DER')
user.enkey = public_cipher.encrypt(public_key, padded_symmkey)
def key(self, password=None, privkey_file=None):
"""Checks if the password matches one of the users.
:param password: password to check (in case of symmetric-key encryption)
:type password: str|Nonetype
:param privkey_file: file with private key (in case of hybrid encryption)
:type privkey_file: str|NoneType
:rtype: bytes|NoneType
:return: the key if the user was found, otherwise None
"""
algorithm = Algorithm(self.algorithm)
if algorithm.is_symmetric() and password is None:
raise ValueError('Algorithm is symmetric, but password is None')
if not algorithm.is_symmetric() and privkey_file is None:
raise ValueError('Algorithm is hybrid, but private key file is None')
for user in self._header.users: # pylint: disable=no-member
if algorithm.is_symmetric():
hashf_cls = hashpw.HashFunc(self.hash_function).cls
_hash = hashf_cls(password, user.pw_salt)
if _hash.check(user.uid):
key_pw_hash = kdf.kdf(password, user.key_salt, algorithm.key_data_size)
return utils.xor_bytes(user.enkey, key_pw_hash)
else:
public_cipher = algorithm.public_cipher()
private_key = public_cipher.import_key(privkey_file)
if private_key.public_key().export_key('DER') == user.uid:
padded_symmkey = public_cipher.decrypt(private_key, user.enkey)
return utils.unpad(padded_symmkey, algorithm.key_data_size)
return None
def __repr__(self):
return self._header.__repr__()
|
ac703a0c45ca5c6e45e8e8cd93cd465aa63e1b42
|
panekwojciech/DC
|
/ProjectEuler/5-Smallest multiple.py
| 456 | 3.578125 | 4 |
'''
25/07/2018
https://projecteuler.net/problem=5
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
#All numbers from 1 to 20 factorized to primes and insert into array without unnecesarry repetitions.
array = [2, 2, 2, 2, 3, 3, 5, 7, 11, 13, 17, 19]
a = 1
for i in array:
a *= i
print(a)
|
75d20db12aeb6ceb8500856ba81ca3d82278742b
|
dltjrgks/Bigdata
|
/01_Jump_to_Python/Chap03/function_type.py
| 478 | 3.78125 | 4 |
# coding:cp949
def my_sum1(num1, num2) : # Է, ϴ ̽
result = num1 + num2
return result # , Ͻ
num1 = int(input("ù ° Էϼ."))
num2 = int(input(" ° Էϼ."))
result = my_sum1(num1,num2)
print("%d+%d=%d"%(num1, num2, result))
num1 = input("ù ° Էϼ.")
num2 = input(" ° Էϼ.")
|
a8c2e408b1610c97b03a730aac731d5523dbf132
|
sanyamsxn/competetive_coding
|
/hackerrank/python/Arithmetic_operators.py
| 293 | 3.5625 | 4 |
n_1=int(input())
n_2=int(input())
addition=[n_1,n_2]
print(sum(addition)) #sum(iterable,start): sum all no.s in list + start
#iterable can be list, tuple ,dict but should contain no.
sub=(n_1-n_2)
print(sub)
prod=(n_1*n_2)
print(prod)
|
06af754463772fd8e5c1e6dcb1d4ff1c21feb7db
|
andreisharshov/FailGoldbah
|
/FailGoldbah.py
| 1,585 | 3.625 | 4 |
# coding: utf-8
# In[149]:
mnozh_set = set()
mnozh_set.add(1)
simple_num = set()
simple_num.add(1)
simple_list = []
simple_list.append(1)
def SimpleNum(num):
i = 2
ans_list = []
num_main = num
while num != 1:
if num%i == 0:
num = num/i
mnozh_set.add(i)
else:
i += 1
if len(mnozh_set) > len(ans_list):
for i in mnozh_set:
ans_list.append(i)
ans_list.sort()
ans_list.reverse()
if ans_list[0] == num_main:
return True
else:
return False
def FindSimpleNumLess(num):
board = simple_list[-1]
for j in range(board, num+1):
if SimpleNum(j) == True:
simple_num.add(j)
else:
continue
if len(simple_num) > len(simple_list):
for i in simple_num:
simple_list.append(i)
simple_list.sort()
return simple_list
def GoldbahTest(y, x):
stop = 0
for b in x:
jack = (((y - b)/2)**0.5)%1
if jack == 0:
stop += 1
break
if stop == 0:
return False
elif stop == 1:
return True
FindNumber = 0
z = 3
while True:
if SimpleNum(z) == True:
simple_list.append(z)
z += 2
else:
x = FindSimpleNumLess(z)
if GoldbahTest(z, x) == False:
FindNumber += z
break
elif GoldbahTest(z, x) == True:
z += 2
print(FindNumber, 'не удовлетворяет Гольдбаха')
# In[146]:
|
7718cf4230ce43e2acfb7e763ef9c786aa28cab6
|
Keydrain/MapReduce
|
/generateTriangles.py
| 849 | 4 | 4 |
#!/usr/local/bin/python3
import random
def main(sizeOfArray):
'''Generates a 2D graph of vertexes that contains an unknown number of triangles.
'''
data = [[0 for x in range(sizeOfArray)] for x in range(sizeOfArray)]
#print(data)
a = 0
for y in range(sizeOfArray):
b = random.randint(0,sizeOfArray-1)
c = random.randint(0,sizeOfArray-1)
d = random.randint(0,sizeOfArray-1)
data[a][b] = 1
data[a][c] = 1
data[b][a] = 1
data[b][c] = 1
data[c][a] = 1
data[c][b] = 1
data[d][a] = 1 #connect the data to come point
data[a][d] = 1
a = d
for i in range(sizeOfArray):
data[i][i] = 0 #Cancel out looping back on ourselves
#print('[', end="")
#for z in range(len(data)):
# print(data[z], end="")
# if z != len(data)-1:
# print(",")
# else:
# print(']')
return data
if __name__ == '__main__':
main(15)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.