blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
549659b57129e8bb0b85738015f4f4d6d4e7ebc0
Machine-builder/python-uno
/scripts/game_logic.py
5,222
3.5625
4
from . import card_logic class UnoPlayer(): def __init__(self): self.hand = [] class UnoGame(): def __init__(self): # create a shuffled uno deck self.deck = card_logic.make_deck() self.players = [] self.players_turn = 0 self.turn_direction = 1 self.upfacing_card = None self.debug = False self.stacked_plus = 0 self.winner = None def debug_msg(self, msg=''): if self.debug: print(msg) def start_game(self, players: int = 5, hand_size: int = 7): """start a game and deal hands""" _ = self.deal_hands(players, hand_size) while 1: if self.upfacing_card is not None: self.put_card(self.upfacing_card) self.upfacing_card = self.take_card() if self.upfacing_card is not None: if self.upfacing_card[0] != '_' and not self.upfacing_card[1] in 'srp': break def deal_hands(self, players: int = 5, size: int = 7): """deals cards from the deck to players returns a list of lists representing each player's hand, also saves UnoPlayer instances in .players attribute""" if players*size > len(self.deck): size = int(len(self.deck)/players) hands = [] for i in range(players): hand = [] for j in range(size): hand.append(self.take_card()) hands.append(hand) new_player = UnoPlayer() new_player.hand = hand self.players.append(new_player) return hands def take_card(self, card=None) -> str: """get the top card off the deck, or a specific card from the deck""" if len(self.deck) == 0: self.deck.extend(card_logic.make_deck()) if card is None: return self.deck.pop(0)[:2] self.deck.remove(card) def put_card(self, card): """put a card into the end of the deck""" self.deck.append(card) def take_turn(self, player_index: int, turn: tuple) -> bool: """let a player take a turn turn[0] can be either 'play' or 'pickup' if turn[0] is 'play', turn[1] must be the card name""" if 0 > player_index >= len(self.players): # player does not exist return False if not turn[0] in ('play', 'pickup'): # turn not valid return False if turn[0] == 'play' and len(turn) != 2: # no card name provided with 'play' turn return False player_obj = self.players[player_index] print(f'[{player_index}] : {turn}') if turn[0] == 'play': card_name = card_logic.real_card_name(turn[1]) if not card_name in player_obj.hand: # player doesn't have card return False if not card_logic.card_playable(card_name, self.upfacing_card): # card not playable return False card_type = card_logic.card_type(card_name) used_plus = False is_special = card_type == 'special' if is_special: if card_name[1] == 'p': # a plus card plus_count = 2 if card_name[0] == '_': plus_count = 4 self.stacked_plus += plus_count used_plus = True if used_plus or self.stacked_plus==0: self.put_card(self.upfacing_card) self.upfacing_card = turn[1] player_obj.hand.remove(card_name) if is_special: if card_name[1] == 's': # a skip card self.players_turn += self.turn_direction elif card_name[1] == 'r': # a reverse card self.turn_direction *= -1 else: for i in range(self.stacked_plus): player_obj.hand.append(self.take_card()) self.stacked_plus = 0 self.players_turn += self.turn_direction self.players_turn %= len(self.players) return True elif turn[0] == 'pickup': if self.stacked_plus == 0: top_card = self.take_card() player_obj.hand.append(top_card) else: for i in range(self.stacked_plus): player_obj.hand.append(self.take_card()) self.stacked_plus = 0 self.players_turn += self.turn_direction self.players_turn %= len(self.players) return True def check_winner(self): for player in self.players: if len(player.hand) == 0: self.winner = player return True if len(self.players) == 1: self.winner = self.players[0] return True return False
43f6c58538bb2bef37b90e942489e7075af2807c
ah4d1/anoapycore
/src/anoapycore/data/null/__init__.py
1,550
3.65625
4
import numpy as __np import pandas as __pd def count (a_data) : """ Count null in dataframe. You can also use a_data[a_column] or a_data[[a_column1,a_column2,...]] """ return a_data.isnull().sum() def fill (a_data,a_columns,b_fill_with='NA') : a_data[a_columns] = a_data[a_columns].fillna(b_fill_with) return a_data # check in any rows had more null than specific number # def greater_than (a_data,a_max_null) : # return a_data[a_data.isnull().sum(axis=1) > a_max_null] def percentage (a_data) : missing_info = __pd.DataFrame(__np.array(a_data.isnull().sum().sort_values(ascending=False).reset_index())\ ,columns=['Columns','Missing_Percentage']).query("Missing_Percentage > 0").set_index('Columns') return 100*missing_info/a_data.shape[0] def replace (a_data,a_column,b_method='mean') : """ Replace null value with another value. The options of b_method are 'mean' (default), 'median'. This function has no return. """ if b_method == 'mean' : a_data[a_column].fillna(a_data[a_column].mean(),inplace=True) elif b_method == 'median' : a_data[a_column].fillna(a_data[a_column].median(),inplace=True) def replace_text (a_data,a_column,a_text) : """ Replace null value (which stated by string or text) with another value. This function has no return. """ a_data[a_column].replace(a_text,__np.nan,inplace=True) a_data[a_column].fillna(a_data[a_column].mode()[0],inplace=True)
aaa05eaea50ea34481a5a79b59d4350b747579e6
kdm1171/programmers
/python/programmers/level2/P_땅따먹기.py
1,138
3.78125
4
# https://programmers.co.kr/learn/courses/30/lessons/12913 # DP 문제 # 첫번째 리스트와 두번째 리스트를 비교해서 갈 수 있는 가장 큰 값을 찾고, 두 값을 더한 리스트를 반환하여 마지막 리스트에서 가장 큰 값을 찾음 def getNextList(list1, list2): result = [] for i in range(len(list2)): e = 0 for j in range(len(list1)): if i == j: continue if e < list1[j]: e = list1[j] result.append(list2[i] + e) return result def solution(land): resultList = land[0] for i in range(1, len(land)): resultList = getNextList(resultList, land[i]) answer = max(resultList) return answer if __name__ == '__main__': print(solution([[1, 2, 3, 5], [5, 6, 7, 8], [4, 3, 2, 1]])) # 16 print(solution([[1, 2, 3, 4], [5, 6, 7, 10], [4, 3, 2, 1]])) # 17 print(solution([[1, 2, 3, 4], [5, 6, 7, 10], [5, 6, 7, 10], [4, 3, 2, 1]])) # 25
79457ef52eb3f8bc1de24b46048bdd915b7e95e9
kdm1171/programmers
/python/programmers/level2/P_행렬의_곱셈.py
541
3.6875
4
# https://programmers.co.kr/learn/courses/30/lessons/12949 def solution(arr1, arr2): m = len(arr1) # row n = len(arr2[0]) # col l = len(arr1[0]) answer = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): for k in range(l): answer[i][j] += arr1[i][k] * arr2[k][j] return answer if __name__ == '__main__': print(solution([[1, 4], [3, 2], [4, 1]], [[3, 3], [3, 3]])) print(solution([[2, 3, 2], [4, 2, 4], [3, 1, 4]], [[5, 4, 3], [2, 4, 1], [3, 1, 1]]))
034168d792c48d2c2117d1f89e5a914487485ab1
kdm1171/programmers
/python/programmers/level2/P_뉴스_클러스터링.py
1,324
3.8125
4
# https://programmers.co.kr/learn/courses/30/lessons/17677 import re def solution(str1, str2): pattern = '[A-Z|a-z]' multiSet1 = [] multiSet2 = [] for i in range(1, len(str1)): s = ''.join(str1[i - 1:i + 1]).upper() if len(re.findall(pattern, s)) == 2: multiSet1.append(s) for i in range(1, len(str2)): s = ''.join(str2[i - 1:i + 1]).upper() if len(re.findall(pattern, s)) == 2: multiSet2.append(s) sorted(multiSet1) sorted(multiSet2) intersections = [] unions = [] for i in multiSet1: if i in multiSet2: intersections.append(i) multiSet2.remove(i) unions.append(i) for i in multiSet2: unions.append(i) a = len(intersections) b = len(unions) if a == b: return 65536 return int(a / b * 65536) if __name__ == '__main__': print(solution("FRANCE", "french")) print(solution("french", "FRANCE")) print() print(solution("handshake", "shake hands")) print(solution("shake hands", "handshake")) print() print(solution("aa1+aa2", "AAAA12")) print(solution("AAAA12", "aa1+aa2")) print() print(solution("E=M*C^2", "e=m*c^2")) print(solution("e=m*c^2", "E=M*C^2")) print(solution("AABBCCDD", "ABCDDCC"))
0a74706da29946c50e28d4ffe12a16f25a243d22
kdm1171/programmers
/python/programmers/level2/P_스킬트리.py
584
3.53125
4
# https://programmers.co.kr/learn/courses/30/lessons/49993 def solution(skill, skill_trees): answer = 0 for skill_tree in skill_trees: skill_comp = [i for i in skill] isMatched = False for s in skill_tree: if s in skill_comp: e = skill_comp.pop(0) if e != s: isMatched = False break isMatched = True if isMatched: answer += 1 return answer if __name__ == '__main__': print(solution("CBD", ["BACDE", "CBADF", "AECB", "BDA"]))
8584992389409fee8982a810415847603a5d7728
kdm1171/programmers
/python/programmers/level2/P_전화번호_목록.py
502
3.65625
4
# https://programmers.co.kr/learn/courses/30/lessons/42577 def solution(phone_book): l = sorted(phone_book, key=lambda x: len(str(x))) for i, a in enumerate(l): for j, b in enumerate(l): if i == j: continue if str(b).startswith(str(a)): return False return True if __name__ == '__main__': print(solution([119, 97674223, 1195524421])) print(solution([123, 456, 789])) print(solution([12, 123, 1235, 567, 88]))
07d0e6234ff5ea5faa2b45699616270713889447
Pride7K/Python
/Listas/lista_exercicio8.py
261
3.71875
4
vetor = [] media = 0; for i in range(0,4): vetor.append(int(input("Digite a nota: "))); print(""); for i in vetor: media += i media = media /4 print(f'{vetor[0]} {vetor[1]} {vetor[2]} {vetor[3]} equivale a média = {media}');
4918e2a6e919cbaefc031bdf611398a5a085438a
Pride7K/Python
/Exercicios/for.py
244
3.5
4
contador = 0; for i in range(1,500): validador = 0; validador2 = 0; validador = i % 3; validador2 = i % 2; if validador == 0: if validador2 != 0: contador = contador + i; print(contador);
0e44d31802705bb1c7082d846f7ae35ff161229c
Pride7K/Python
/Listas/lista_exercicio5.py
374
3.90625
4
contador = 0; print("Checando se uma expressão é valida através dos parenteses \n"); expressao = input("Digite a expressão: "); print(""); for i in expressao: if i == "(" or i == ")": contador = contador + 1 contador = contador % 2 if contador == 0: print("Expressão valida !"); else: print("Expressão invalida !");
a609dd67af83c1bf8302578ec639d3bdfe6fcb8a
Pride7K/Python
/Dicionario/dicionario_exercicio2.py
1,069
4.09375
4
from datetime import datetime pessoa = {} now = datetime.now(); now = now.year pessoa["nome"] = input("Digite o seu nome: "); pessoa["ano de nascimento"] = int(input("Digite o seu ano de nascimento: ")); pessoa["cdt"] = int(input("Digite o sua carteira de trabalho(caso nao tenha digite 0): ")); if(pessoa["cdt"] !=0): pessoa["ano_contrato"] = int(input("Digite o ano de sua contratação: ")); pessoa["salario"] = int(input("Digite o seu salario: ")); pessoa["aposentar"] = pessoa["ano_contrato"] + 35; print(""); print(f'O seu nome é {pessoa["nome"]} \n'); print(f'A sua idade é {now - pessoa["ano de nascimento"]} \n'); print(f'A sua carteira de trabalho é {pessoa["cdt"]} \n'); print(f'A sua contratação foi em {pessoa["ano_contrato"]} \n'); print(f'O seu salario é {pessoa["salario"]} \n'); print(f'O Você ira se aposentar em {pessoa["aposentar"]} \n'); else: print(f'O seu nome é {pessoa["nome"]} \n'); print(f'A sua idade é {now - pessoa["ano de nascimento"]} \n');
9ef4f0332e5bdf6d72be3bc23ef5d5dcc7ae8038
Pride7K/Python
/Listas/lista_exercicio7.py
148
3.90625
4
vetor = [] for i in range(0,10): vetor.append(float(input("Digite um numero: "))); print(""); print(sorted(vetor,reverse=True));
f7c61b747436cfcd105a925edd695ac3c8d97279
ksheetal/python-codes
/hanoi.py
654
4.1875
4
def hanoi(n,source,spare,target): ''' objective : To build tower of hanoi using n number of disks and 3 poles input parameters : n -> no of disks source : starting position of disk spare : auxillary position of the disk target : end position of the disk ''' #approach : call hanoi function recursively to move disk from one pole to another assert n>0 if n==1: print('Move disk from ',source,' to ',target) else: hanoi(n-1,source,target,spare) print('Move disk from ',source,' to ',target) hanoi(n-1,spare,source,target)
1ad945d852351c2fed94dc05e75eade79aff7c48
austonnn/ucsd_bio_2
/bio 2 week 4/1.3.4.py
1,106
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 21 15:23:09 2018 @author: xiangyin """ """ Spectral Convolution Problem: Compute the convolution of a spectrum. Input: A collection of integers Spectrum. Output: The list of elements in the convolution of Spectrum. If an element has multiplicity k, it should appear exactly k times; you may return the elements in any order. """ def Convolution_Spectrum(Spectrum): ans_list = [] tmp_list = [0] tmp_list.extend(Spectrum) for i in tmp_list: for j in Spectrum: if i > j: ans_list.append(i - j) pass ans_list = sorted(ans_list) return ans_list with open('dataset_104_4.txt') as handle: Spectrum = handle.read() #.splitlines() Spectrum = Spectrum.split() tmp_list = [] for item in Spectrum: tmp_list.append(int(item)) Spectrum = tmp_list ans = Convolution_Spectrum(Spectrum) #print(ans) text = '' for item in ans: text += str(item) text += ' ' print(text) with open('output.txt', 'w') as handle: handle.write(text)
baf66093d37d83826dd906d458484c653e804597
austonnn/ucsd_bio_2
/bio 2 week 3/1.5.py
2,198
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 14 11:57:07 2018 @author: xiangyin """ #Counting Peptides with Given Mass Problem: Compute the number of peptides of given mass. # Input: An integer m. # Output: The number of linear peptides having integer mass m. aminoAcid = ['G', 'A', 'S', 'P', 'V', 'T', 'C', 'I', 'N', 'D', 'K', 'E', 'M', 'H', 'F', 'R', 'Y', 'W'] aminoAcidMass = [ 57, 71, 87, 97, 99, 101, 103, 113, 114, 115, 128, 129, 131, 137, 147, 156, 163, 186] aminoAcid_dict = dict(zip(aminoAcid, aminoAcidMass)) def get_seqs(total_mass): #tmp_num = 0 #mass_dict = {} text_list = [] for i in aminoAcid: tmp_text = '' tmp_text += i if total_mass - aminoAcid_dict[i] < 0: #print(tmp_text) break #print(total_mass - aminoAcid_dict[i]) elif total_mass - aminoAcid_dict[i] > 0: for item in get_seqs(total_mass - aminoAcid_dict[i]): tmp_item = tmp_text + item text_list.append(tmp_item) elif total_mass - aminoAcid_dict[i] == 0: #text_list.append(tmp_text) #print(i) #print(tmp_num) text_list.append(tmp_text) return text_list return text_list mass_dict = {} def count_seqs(total_mass): tmp_num = 0 #text_list = [] for i in aminoAcid: if (total_mass - aminoAcid_dict[i]) in mass_dict.keys(): tmp_num += mass_dict[(total_mass - aminoAcid_dict[i])] elif total_mass - aminoAcid_dict[i] < 0: #print(tmp_text) #mass_dict[(total_mass - aminoAcid_dict[i])] = 0 break #print(total_mass - aminoAcid_dict[i]) elif total_mass - aminoAcid_dict[i] == 0: #text_list.append(tmp_text) #print(i) #print(tmp_num) tmp_num += 1 return tmp_num elif total_mass - aminoAcid_dict[i] > 0: tmp_num += count_seqs(total_mass - aminoAcid_dict[i]) mass_dict[total_mass] = tmp_num return tmp_num total_mass = 1334 ans_num = count_seqs(total_mass) print(ans_num)
c94f35aaf3c6231e4b07cccc6133fb5f5e490566
psmith586/directory-parsing-python
/filewalker.py
1,877
4.09375
4
#Author: Phillip Smith #recursive keyword search/directory data display #using os library to walk the directory import os #using matplotlib to create xy graph of data import matplotlib.pyplot as plt #init root dir and keyword vars from user root_dir = input("Please enter directory path: ") keyword = input("Please enter keyword: ") #this method will be used to accumulate files with the keyword and populate array def CheckKey(r, k): #will accumulate number of files with keyword total = 0 #populate array with the sub dirs and the number of files with keyword arr = {} #check dirs/subdirs for files for fname in os.listdir(r): #use join to create the new path to check on each iteration newPath = os.path.join(r, fname) #this will confirm an object in the dir is a txt file to be read if os.path.isfile(newPath): #strip the file name out to check if it contains keyword s = newPath.split('\\')[-1].split('.')[0] #if the keyword is in the current file name and contents increment total if k in s and k in open(newPath, 'r').read(): total += 1 #add the number value to associate with the dir key arr[r] = total #return each key/value object tot final array return arr[r] #init new array to recursively add results finalArr = {} #use os walk and searchkey to search through dirs, subdirs, files for root, dirs, files in os.walk(root_dir): finalArr[root] = CheckKey(root, keyword) #display final array print("Number of Files Containing Keyword by Directory: ", finalArr) #break finalArr into a seperate arrays #x = keys, y = values x = [] y = [] #iterate through each key/value pair and append to new arrays for key, value in finalArr.items(): x.append(key) y.append(value) #use matplotlib to display line graph of data plt.plot(x,y) plt.show()
de64db2e733e592558b5459e7fb4fcfd695abd1b
moogzy/MIT-6.00.1x-Files
/w2-pset1-alphabetic-strings.py
1,220
4.125
4
#!/usr/bin/python """ Find longest alphabetical order substring in a given string. Author: Adrian Arumugam (apa@moogzy.net) Date: 2018-01-27 MIT 6.00.1x """ s = 'azcbobobegghakl' currloc = 0 substr = '' sublist = [] strend = len(s) # Process the string while the current slice location is less then the length of the string. while currloc < strend: # Append the character from the current location to the substring. substr += s[currloc] # Our base case to ensure we don't try to access invalid string slice locations. # If current location is equal to the actual length of the string then increment # the current location counter and append the substring to our list. if currloc == strend - 1: currloc += 1 sublist.append(substr) # Continute processing the substring as we've still got slices in alphabetical order. elif s[currloc+1] >= s[currloc]: currloc += 1 # Current slice location broken the alphabetical order requirement. # Append the current substring to our list, reset to an empty substring and increment the current location. else: sublist.append(substr) substr = '' currloc += 1 print("Longest substring in alphabetical order is: {}".format(max(sublist, key=len)))
abb1b3042edbbf6dee7201817177000cb9bc7d39
theworldcitizen/Web-2021
/cycle3.py
128
3.59375
4
a = int(input()) b = int(input()) for i in range(a, b + 1): if(i**(1/2) == round(i**(1/2))): print(i, end=" ")
5cd4cd9e965fdce1148584357b0fc9e2fc1709df
theworldcitizen/Web-2021
/cycle11.py
98
3.5
4
ans = 0 n = int(input()) for i in range(n): a = int(input()) ans = ans + a print(ans)
65882ab6d3f039036a778f6763725231dc69458c
jadsonpp/ordenacao
/src/PersonHandler.py
954
3.703125
4
class Person: def __init__(self,email,gender,uid,birthdate,height,weight): self.email = email self.gender = gender self.uid = uid self.birthdate = birthdate self.height = height self.weight = weight def showData(self): print("E-mail: "+self.email) print("Gender: "+self.gender) print("Uid: "+self.uid) print("birthdate: "+self.birthdate) print("height: "+self.height) print("weight: "+self.weight) def showUid(self): print("uid:"+ self.uid) #Compare two classes and return -1 if p1 is lower, 0 if both are equals, 1 if p1 is higher def compareTo(p1:Person , p2:Person): if(p1.uid > p2.uid): return 1 elif (p1.uid < p2.uid): return -1 #caso não ache. return 0 def showUids(persons:list): for person in persons: person.showUid()
fda220a40796a2b8dd83b752bc0cf350830b95ea
ishaniMadhuwanthi/Semester-6
/CO544-Machine Learning and Data Mining/Lab2-Numpy and Pandas/randomWalk.py
303
3.8125
4
#implement basic version of random walk. import random import matplotlib.pyplot as plt xrange = range position =0 walk = [position] steps = 500 for i in xrange(steps): step = 1 if random.randint(0,1) else -1 position += step walk.append(position) plt.plot(walk) plt.show()
d9b0a9947e1704fda375f2fddda419d3604cd7f9
iamhemantgauhai/Digital-Hotel-Menu
/digital-menu-code.py
6,664
3.984375
4
print(''' Welcome to Gauhai's Hotel गौहाई के होटल में आपका स्वागत है''') a=True while a==True: user=int(input(''' 1:Breakfast 2:Lunch 3:Snack 4:Dinner Order Number Please: ''')) if user==1: user1=int(input(''' 1:Tea 2:Dal ka Paratha 3:Namkeen Seviyaan 4:Aloo Paratha 5:Bread Pakora Order Number Please: ''')) if user1==1: print(''' 10rs''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==2: print(''' 20rs half plate, 40rs full plate''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==3: print(''' 30rs half plate, 5ors full plate''') back=input('''Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==4: print('''40rs half plate, 70rs full plate''') back=input('''Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==5: print('''20rs half plate, 40rs full plate''') back=input('''Any more order? (yes/no) : ''') if back!='''yes''': a=False else: print('''invalid input''') back=input('''Any more order? (yes/no) : ''') if back!='''yes''': a=False back=input('''Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user==2: print(''' 1:Chole bhature 2:Kadhi Rice 3:Biryani 4:Rajma Rice 5:Dal Makhani''') user1=int(input(''' Order Number Please: ''')) if user1==1: print(''' 50rs per plate''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==2: print(''' half plate 40rs, full plate 70rs''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==3: print(''' 80rs per plate''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==4: print(''' half plate 50rs, full plate 80rs''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==5: print(''' 60rs per plate''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False else: print(''' invalid input''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user==3: print(''' 1:Dal Ki Kachori 2:Bonda 3:Dahi vada 4:Halva 5:Momo''') user1=int(input(''' Order Number Please: ''')) if user1==1: print(''' 25rs per plate''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==2: print(''' 99rs medium size''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==3: print(''' 20rs per cup''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==4: print(''' half plate 30rs, full plate 50rs''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==5: print(''' 30rs''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False else: print(''' invalid input''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user==4: print(''' 1:Butter Chicken Roti 2:Chicken Korma Roti 3:Fish Roti 4: Tandoori Chops Roti 5:Egg Roti''') user1=int(input(''' Order Number Please: ''')) if user1==1: print(''' 4 eggs 4 roti 100rs plate''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==2: print(''' half plate chicken 4 roti 150rs plate''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==3: print(''' half plate mutton 4 roti 200rs plate''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==4: print(''' half plate chicken corma 4 roti 200rs plate''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False elif user1==5: print(''' half plate 80rs full plate 150rs''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False else: print(''' invalid input''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False else: print(''' invalid input''') back=input(''' Any more order? (yes/no) : ''') if back!='''yes''': a=False
2e23437ffd15f9ca5ec0383f172fba7fcb4f48af
AmirZimhony/University-Projects
/Assignment 4/create_db.py
3,084
3.984375
4
import sqlite3 import os import sys def main(): database_name = "schedule.db" is_database_exists = os.path.isfile(database_name) if not is_database_exists: # if database does not exists - we're going to create it. connection_to_database = sqlite3.connect(database_name) with connection_to_database: # this promises to close the connection when we're done with it cursor = connection_to_database.cursor() # this enables us to go through the database. cursor.execute("""CREATE TABLE courses (id INTEGER PRIMARY KEY, course_name TEXT NOT NULL, student TEXT NOT NULL, number_of_students INTEGER NOT NULL, class_id INTEGER REFERENCES classrooms(id), course_length INTEGER NOT NULL)""") cursor.execute("""CREATE TABLE students (grade TEXT PRIMARY KEY, count INTEGER NOT NULL)""") cursor.execute("""CREATE TABLE classrooms (id INTEGER PRIMARY KEY, location TEXT NOT NULL, current_course_id INTEGER NOT NULL, current_course_time_left INTEGER NOT NULL)""") with open(sys.argv[1]) as f: file = f.read() input = file.split('\n') for line in input: list = line.split(', ') if list[0] == "C": # course cursor.execute("""INSERT INTO courses (id, course_name, student, number_of_students, class_id, course_length) VALUES(?,?,?,?,?,?)""", (list[1], list[2], list[3], list[4], list[5], list[6])) elif list[0] == "S": # student cursor.execute("""INSERT INTO students (grade, count) VALUES(?,?)""", (list[1], list[2])) elif list[0] == "R": # classroom cursor.execute("""INSERT INTO classrooms (id, location, current_course_id, current_course_time_left) VALUES(?,?,?,?)""", (list[1], list[2], 0, 0)) # we will now print the database: print("courses") cursor.execute("SELECT * FROM courses") courses = cursor.fetchall() for course in courses: print(course) print("classrooms") cursor.execute("SELECT * FROM classrooms") classrooms = cursor.fetchall() for classroom in classrooms: print(classroom) print("students") cursor.execute("SELECT * FROM students") students = cursor.fetchall() for student in students: print(student) connection_to_database.commit() if __name__ == '__main__': main()
97428ffc166ec44c733e2bda85f6421c922540d7
boris-vasilev/kalah
/kalah/kalahboard.py
6,177
4.15625
4
class KalahBoard: """ A implementation of the game Kalah Example layout for a 6 bin board: <--- North ------------------------ 12 11 10 9 8 7 13 6 0 1 2 3 4 5 ------------------------ South ---> """ bins = 0 seeds = 0 board = [] player = 0 def __init__(self, bins, seeds): self.bins = bins self.seeds = seeds self.board = [seeds]*(bins*2+2) self.board[bins] = 0 self.board[2*bins + 1] = 0 if not self._check_board_consistency(self.board): raise ValueError('The board created is not consistent, some error must have happened') self._player_houses = { 0: self.bins*(1), 1: self.bins*(2) + 1} def copy(self): board = KalahBoard(self.bins, self.seeds) board.set_board(list(self.board)) board.set_current_player(self.player) if not board._check_board_consistency(board.board): raise ValueError('The board that was copied is not consistent, some error must have happened') return board def reset(self): self.board = [self.seeds]*(self.bins*2+2) self.board[self.bins] = 0 self.board[2*self.bins + 1] = 0 self.player = 0 def pretty_print(self): print(self.get_board()) def move(self, b): if b not in self.allowed_moves(): return False old_board = list(self.board) seeds_to_distribute = self.board[b] self.board[b] = 0 other_player = 1 if self.current_player() == 0 else 0 current_bin = b while seeds_to_distribute > 0: current_bin = current_bin+1 if current_bin >= len(self.board): current_bin -= len(self.board) if current_bin == self._get_house(other_player): continue self.board[current_bin] += 1 seeds_to_distribute -= 1 # Seed in empty bin -> take seeds on the opponents side if ( current_bin != self.get_house_id(self.current_player()) and self.board[current_bin] == 1 and current_bin >= self._get_first_bin(self.current_player()) and current_bin < self._get_last_bin(self.current_player()) ): opposite_bin = current_bin + self.bins+1 if opposite_bin >= len(self.board): opposite_bin -= len(self.board) if self.board[opposite_bin] > 0: self.board[self._get_house(self.current_player())] += self.board[opposite_bin] + self.board[current_bin] self.board[opposite_bin] = 0 self.board[current_bin] = 0 # All seeds empty, opponent takes all his seeds if self._all_empty_bins(self.current_player()): for b in range(self.bins): self.board[self._get_house(other_player)] += self.board[other_player*self.bins + other_player + b] self.board[other_player*self.bins + other_player + b] = 0 if current_bin != self.get_house_id(self.current_player()): self.player = 1 if self.current_player() == 0 else 0 if not self._check_board_consistency(self.board): raise ValueError('The board is not consistent, some error must have happened. Old Board: ' + str(old_board) + ", move = " + str(b) +", new Board: " + str(self.get_board())) return True def _get_first_bin(self, player): return player*self.bins + player def _get_last_bin(self, player): return self._get_first_bin(player) + self.bins - 1 def _all_empty_bins(self, player): player_board = self._get_player_board(player) for seed in player_board[:-1]: if seed > 0: return False return True def _check_board_consistency(self, board): expected_seeds = 2*self.seeds*self.bins actual_seeds = 0 for s in board: actual_seeds += s return actual_seeds == expected_seeds def _get_house(self, player): return self._player_houses[player] def get_board(self): return list(self.board) def current_player(self): return self.player def _get_player_board(self, player): return self.get_board()[player*self.bins + player : player*self.bins + player + self.bins + 1] def game_over(self): player_board_one = self._get_player_board(0) player_board_two = self._get_player_board(1) player_one_empty = True for seed in player_board_one[:-1]: if seed > 0: player_one_empty = False player_two_empty = True for seed in player_board_two[:-1]: if seed > 0: player_two_empty = False return player_one_empty or player_two_empty def score(self): return [self.board[self.bins], self.board[2*self.bins + 1]] def allowed_moves(self): allowed_moves = [] player_board = self._get_player_board(self.current_player()) for b in range(len(player_board)-1): if player_board[b] > 0: allowed_moves.append(b + self.current_player()*self.bins + self.current_player()) return allowed_moves def set_board(self, board): if len(board) != self.bins*2 + 2: raise ValueError('Passed board size does not match number of bins = ' + str(self.bins) + ' used to create the board') if not self._check_board_consistency(board): raise ValueError('The board is not consistent, cannot use it') self.board = list(board) def set_current_player(self, player): if player >= 0 and player < 2: self.player = player else: raise ValueError('Passed player number is not 0 or 1') def current_player_score(self): return self.score()[self.current_player()] def get_house_id(self, player): return self._get_house(player)
4aa122bf3782a63b4d7680c9f24bd5f70ef0a7c2
MirjahonMirsaidov/interviewPrep
/merge_sort_linked_list.py
1,754
4.09375
4
import random from linked_list import LinkedList def merge_sort(linked_list): if linked_list.size() == 1 or linked_list.head is None: return linked_list left_half, right_half = split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half) return merge(left, right) def split(linked_list): if linked_list is None or linked_list.head is None: left, right = linked_list, None else: mid = linked_list.size()//2 mid_node = linked_list.node_at_index(mid - 1) left = linked_list right = LinkedList() right.head = mid_node.next_node mid_node.next_node = None return left, right def merge(left, right): new_linked_list = LinkedList() new_linked_list.add(0) current = new_linked_list.head left_head = left.head right_head = right.head while left_head or right_head: if left_head is None: current.next_node = right_head right_head = right_head.next_node elif right_head is None: current.next_node = left_head left_head = left_head.next_node else: left_data = left_head.data right_data = right_head.data if left_data < right_data: current.next_node = left_head left_head = left_head.next_node else: current.next_node = right_head right_head = right_head.next_node current = current.next_node new_linked_list.head = new_linked_list.head.next_node return new_linked_list linked_list = LinkedList() for i in range(11): linked_list.add(random.randint(1, 100)) print(linked_list) print(merge_sort(linked_list))
dc81b34ba79a23123018f6a0b2c026c47d49e4f4
makarandmadhavi/intermediate-python-course
/dice_roller.py
848
3.796875
4
import random def main(): dice_sum = 0 pname = [0,0] pscore = [0,0] pname[0] = input('Player 1 what is your name? ') pname[1] = input('Player 2 what should we call you? ') dicerolls = int(input('How many dice would you like to roll? ')) dice_size = int(input('How many sides are the dice? ')) for j in range(0,2): for i in range(0,dicerolls): roll= random.randint(1,dice_size) pscore[j] += roll if roll == 1: print(f'{pname[j]} rolled a {roll}! Critical Fail') elif roll == dice_size: print(f'{pname[j]} rolled a {roll}! Critical Success!') else: print(f'{pname[j]} rolled a {roll}') print(f'{pname[j]} have rolled a total of {dice_sum}') if(pscore[0]>pscore[1]): print(f'{pname[0]} Wins!') else: print(f'{pname[1]} Wins!') if __name__== "__main__": main()
fdc8270e35fde55df9e9daf93194db8f51ee6b07
JonathanQu/Testing2
/2015-2016 Spring Term Homework/list-1.py
2,048
4.03125
4
import random def merge (firstList, secondList): OutputList = [] SmallerList = [] smallestListSize = 0 #determine what list is bigger and smaller if len(firstList) > len(secondList): OutputList=firstList SmallerList=secondList smallestListSize = len(secondList) elif len(secondList) >= len(firstList): OutputList=secondList smallestListSize = len(firstList) SmallerList=firstList #determine the first comparison outside of the while loop to prevent an out of index range error if OutputList[0] >= SmallerList[0]: OutputList.insert(0,SmallerList[0]) else: OutputList.insert(1,SmallerList[0]) firstCounter = 1 secondCounter = 0 EndThis = 0 #the while loop excluding comparing the last number of the longer string because there is no number that exists after the last while firstCounter < (len(OutputList) - 1): while secondCounter < len(SmallerList) and EndThis == 0: if SmallerList[secondCounter] < OutputList[firstCounter] and SmallerList[secondCounter] >= OutputList[firstCounter - 1]: OutputList.insert(firstCounter,SmallerList[secondCounter]) EndThis = 1 else: secondCounter += 1 secondCounter = 0 EndThis = 0 firstCounter += 2 if OutputList[(len(OutputList)-1)] >= SmallerList[smallestListSize-1]: OutputList.insert((len(OutputList)-1),SmallerList[smallestListSize-1]) else: OutputList.append(SmallerList[smallestListSize-1]) return OutputList g1 = [0, 2, 4, 6, 8] g2 = [1, 3, 5, 7] print merge(g1, g2) def randomList(n): listCon = [] counter = 0 while counter < n: listCon.append(random.randrange(-10,11)) counter += 1 return listCon print randomList(5) def doublify(aList): counter = 0 while counter < len(aList): aList[counter] = aList[counter] * 2 counter += 1 return aList print doublify( [3, 5, -20, 45] ) def barGraph(aList): counter = 0 while counter < len(aList): print str(counter) + ":" + ("=" * aList[counter]) counter += 1 x = [3,4,1,0,5] barGraph(x)
b08dd793de1d6f63d90d5c42b740fc8f57ded57e
rafiud1305/Rafi-ud-Darojat_I0320079_Aditya-Mahendra_Tugas-3
/I0320079_Exercise 3.6.py
174
4.09375
4
dict = {'Name':'Zara','Age': 7,'Class':'First'} dict['Age'] = 8; dict['School'] = "DPS School" print("dict['Age']:", dict['Age']) print("dict['School']:", dict['School'])
27ebcf2e51a5a9184d718ad14097aba5fb714d94
tanawitpat/python-playground
/zhiwehu_programming_exercise/exercise/Q006.py
1,421
4.28125
4
import unittest ''' Question 6 Level 2 Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24 Hints: If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26) In case of input data being supplied to the question, it should be assumed to be a console input. ''' def logic(input_string): c = 50 h = 30 input_list = input_string.split(",") output_list = [] output_string = "" for d in input_list: output_list.append(str(int((2*c*int(d)/h)**0.5))) for i in range(len(output_list)): if i == 0: output_string = output_string+output_list[i] else: output_string = output_string+","+output_list[i] return output_string class TestLogic(unittest.TestCase): def test_logic(self): self.assertEqual( logic("100,150,180"), "18,22,24", "Should be `18,22,24`") if __name__ == '__main__': unittest.main()
ca33cf3f9132ec9aa4d3e4b77a995fabdd67971c
ivafer00/MiniCrypto
/classic/Vigenere.py
1,300
3.578125
4
class Vigenere(): def __init__(self): self.plaintext = "" self.ciphertext = "" self.key = [] def set_plaintext(self, message): self.plaintext = message def set_ciphertext(self, cipher): self.ciphertext = cipher def set_key(self, k): self.key = [] for i in range(len(k)): self.key.append(int(k[i])) def cipher(self): self.ciphertext = "" for i in range(len(self.plaintext)): if self.plaintext[i].isalpha(): code_ascii = 97 if self.plaintext[i].isupper(): code_ascii = 65 self.ciphertext += chr(((ord(self.plaintext[i]) % code_ascii + self.key[i % len(self.key)]) % 26) + code_ascii) else: self.ciphertext += self.plaintext[i] def decipher(self): self.plaintext = "" for i in range(len(self.ciphertext)): if self.ciphertext[i].isalpha(): code_ascii = 97 if self.ciphertext[i].isupper(): code_ascii = 65 self.plaintext += chr(((ord(self.ciphertext[i]) % code_ascii - self.key[i % len(self.key)]) % 26) + code_ascii) else: self.plaintext += self.ciphertext[i]
9fa5ecf1948273aa4e80924f56b63343a63e37cb
raquelmachado4993/omundodanarrativagit
/python/funcoes_busca_intermediario.py
2,370
3.828125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- import re import funcoes as fun def verifica_escola(texto): result="" contador=0 substring1 = "escola" if substring1 in texto: result+=substring1+" " contador+=1 return result,contador def encontra_esportes(texto): result="" contador=0 pesquisar_esportes = ['futebol', 'volei', 'tênis de mesa', 'natação', 'futsal', 'capoeira', 'skate', 'skatismo', 'surf', 'vôlei de praia', 'badminton', 'frescobol', 'judô', 'atletismo', 'críquete', 'basquete', 'hockey na grama', 'hockey no gelo', 'beisebol', 'fórmula 1', 'Rugby', 'futebol americano', 'golfe', 'handebol', 'queimado', 'hipismo', 'ginástica olímpica', 'Triatlo', 'maratona', 'canoagem', 'peteca', 'jiu-jitsu', 'esgrima', 'vale-tudo', 'karatê', 'corrida', 'ciclismo', 'boxe', 'MMA', 'Taekwondo'] # print(len(pesquisar_esportes)) for i in pesquisar_esportes: if i in texto: result+=i+" " contador+=1 return result,contador def busca_batalha_luta_guerra(texto): result="" contador=0 palavras_crivo_intermediario = ['lut','guerr','batalha'] # palavras_crivo_intermediario = ''.join(palavras_crivo_intermediario_inicio) # palavras_crivo_intermediario = palavras_crivo_intermediario_inicio.split() # palavras_crivo_intermediario_encontradas = [] for i in palavras_crivo_intermediario: if i in texto: result+=i+" " contador+=1 return result,contador def busca_amizade(texto): result="" contador=0 palavras_crivo_amizade = ['amig', 'amiz', 'migux','amigos','amigas'] for i in palavras_crivo_amizade: if i in texto: result+=i+" " contador+=1 return result,contador def busca_jogo(texto): result="" contador=0 substring = "jog" if substring in texto: result+=substring+" " contador+=1 return result,contador def proc_inter(texto): result="" contador=0 r,c =encontra_esportes(texto) result+=r contador+=c r,c =busca_batalha_luta_guerra(texto) result+=r contador+=c r,c =busca_amizade(texto) result+=r contador+=c r,c =busca_jogo(texto) result+=r contador+=c return result,contador
3e63333e7ddfc297059762314bc608723cb3b246
raquelmachado4993/omundodanarrativagit
/python/RASCUNHOS/teste_regex_findall.py
162
3.5625
4
# -*- coding: utf-8 -*- import re sentence = "Eu amava amar você" word = "ama" for match in re.finditer(word, sentence): print (match.start(), match.end())
4cbc0f8a14c5b9ec8ae6d9c4dc5b4741ad43700c
raquelmachado4993/omundodanarrativagit
/python/dao/mysql_connect.py
1,636
3.609375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- import mysql from mysql.connector import Error def connect(): """ Connect to MySQL database """ try: conn = mysql.connector.connect(host="", # your host, usually localhost user="", # your username passwd="", # your password db="") # name of the data base # conn = mysql.connector.connect(host="raqueleluis.ddns.net", # your host, usually localhost # user="jogonarrativa", # your username # passwd="k9kbg1tmMAeK", # your password # db="omundo88_jogonarrativa") # name of the data base #print("estou aqui vivo") return conn except Error as e: print(e) def buscar(sql): cnx = connect() cur = cnx.cursor() cur.execute(sql) myresult = cur.fetchall() cnx.close() return myresult ## def busca2(sql): ## cnx = connect() ## cur = cnx.cursor(dictionary=True) ## return cur.execute(sql) ## cnx.close() ## return cur def alterar(sql): # cnx = connect() # cur = cnx.cursor() # cur.execute(sql) # cur.execute(sql) # myresult = cnx.commit() # return myresult return("ainda nao implementado") def inserir(sql): try: cnx = connect() cur = cnx.cursor() cur.execute(sql) cnx.commit() cnx.close() except Error as error: print(error) print(sql) finally: cur.close() cnx.close() def escapa(sql): return mysql.escape_string(sql)
1503bb3b33f20f77499db340de8b33523043ea56
digitalMirko/PythonReview
/python_review08_functions.py
1,175
3.78125
4
# Python Programming Review # file name: python_review08_functions.py # JetBrains PyCharm 4.5.4 under Python 3.5.0 import random # random number generator import sys # sys module import os # operating system # functions allow us to both re-use and write more readable code # define a function that adds numbers # define a function, function name (parameters it receives) def addNumber(fNum, lNum): sumNum = fNum + lNum return sumNum # return something to the caller of this function # make sure you define your functions before you call them # calling function below print(addNumber(1, 4)) # outputs: 5 # also assign it to a String string = addNumber(1, 4) # works the same way when called # note even though sumNum is created inside the variable up above # it is not available outside it, it doesnt exist outside # unresolved reference error thrown, its not defined, out of scope # print(sumNum) # get input from the user print('What is your name') # outputs: What is your name # get input from user using sys.stdin.readline() name = sys.stdin.readline() # prints out Hello with persons name entered print('Hello ', name) # outputs Hello Mirko
4a30e4eb36ebcc74d1f0bc0f7a6249ed5b8a0951
digitalMirko/PythonReview
/python_review14_inheritance.py
3,567
4.21875
4
# Python Programming Review # file name: python_review14_inheritance.py # JetBrains PyCharm 4.5.4 under Python 3.5.0 import random # random number generator import sys # sys module import os # operating system class Animal: __name = "" __height = 0 __weight = 0 __sound = 0 def __init__(self, name, height, weight, sound): self.__name = name self.__height = height self.__weight = weight self.__sound = sound def set_name(self, name): self.__name = name def set_height(self, height): self.height = height def set_weight(self, weight): self.__weight = weight def set_sound(self, sound): self.__sound = sound def get_name(self): return self.__name def get_height(self): return self.__height def get_weight(self): return self.__weight def get_sound(self): return self.__sound def get_type(self): print("Animal") #outputs: Animal def toString(self): return "{} is {} cm tall and {} kilograms and says {}".format(self.__name, self.__height, self.__weight, self.__sound) cat = Animal('Whiskers', 33, 10, 'Meow') print(cat.toString()) # outputs: Whiskers is 33 cm tall and 10 kilograms and says Meow # Inheritance: all it means is when you inherit from another class that your # automatically going to get all the variables, methods or functions that # are created in the class you are inheriting from. # Class called Dog, inherit from the Animal class class Dog(Animal): # automatically get every variable and function already in the Animal class # give it a name like owner __owner = "" # every dog but not Animal gonna have an owner # then over right the constructor for the Animal class # i want to do something more specific here since its a dog # still require them to enter a: name, height, weight, sound # but now i also require them to enter an owner name def __init__(self, name, height, weight, sound, owner): # set the owner, make it equal to the owner value they passed in self.__owner = owner # if we want the name, height, weight, sound to be handled by # the Animal super classes constructor on top # super, its a super class, then Dog, self, init then pass in # the name, height, weight, sound super(Dog, self).__init__(name, height, weight, sound) # Allow them to set the owner, owner passed here def set_owner(self, owner): # self owner, owner value passed in self.__owner = owner # Do the same thing to get the owner def get_owner(self, owner): return self.__owner # define get type def get_type(self): # print we are using a Dog object print("Dog") # override functions on our super class, change the toSting, add the __owner def toString(self): return "{} is {} cm tall and {} kilograms and says {} His owner is {}".format(self.__name, self.__height, self.__weight, self.__sound, self.__owner)
3314f67d5a12e55b836587554f792d7f5653cf1b
easternHong/pythonStudy
/Lesson3/Func.py
332
3.953125
4
# 偏函数的使用 def func(): print(int('2222')) print(int('2222', base=8)) print(int2('533', 8)) print(int_custom('533')) def int2(x, base=2): return int(x, base) def int_custom(x): kw = {'base': 8} return int(x, **kw) if __name__ == '__main__': print('''偏函数的使用''') func()
cb3fb384955f9767077db0d80a5b1374c82c1674
BurnFaithful/KW
/Programming_Practice/Python/Base/Bigdata_day1001/Input05.py
304
4.1875
4
# 문자열은 인덱스 번호가 부여됨 strTemp = input("아무 문자열이나 입력하세요: ") print("strTemp : ", strTemp) print("strTemp : {}".format(strTemp)) print("strTemp[0] : {}".format(strTemp[0])) print("strTemp[1] : {}".format(strTemp[1])) print("strTemp[2] : {}".format(strTemp[2]))
dd7a778882684ed3a30f3ae0df1465977d46d51d
BurnFaithful/KW
/Programming_Practice/Python/Base/Bigdata_day1015/FUNCTION11.py
219
3.640625
4
def func3(num): # 매개변수로 선언된 것도 지역변수 print(f"func3() num: {num}") def func4(n1, n2, n3): print(f"func4() n1, n2, n3 -> {n1}, {n2}, {n3}") num = 0 func3(num) print("num : ", num)
3ab7e81a15e1efa8bd293f6ba35cc5bd8e6a7e23
BurnFaithful/KW
/Programming_Practice/Python/Base/Bigdata_day1011/WINDOW06.py
241
3.671875
4
from tkinter import * from tkinter import messagebox def clickLeft(event): messagebox.showinfo("마우스", "마우스 왼쪽 버튼 클릭됨.") window = Tk() button = Button() window.bind("<Button-1>", clickLeft) window.mainloop()
53fa58a6f7b911378a298d8e96e81dec0423f927
BurnFaithful/KW
/Programming_Practice/Python/Base/Bigdata_day1011/LIST06.py
384
3.78125
4
heros = ["스파이더맨", "헐크", "캡틴마블", "아이언맨", "앤트맨", "토르", "배트맨"] srhName = input("찾을 영웅 이름: ") for i in heros: if i == srhName: print("찾음") break else: print("없음") delName = input("삭제할 이름: ") for i in heros: if heros.index(delName): heros.remove(delName) print(heros)
d333885fa35681071ef0c8c01efd9163b7244fdf
BurnFaithful/KW
/Programming_Practice/Python/Base/Bigdata_day1008/STRING05.py
230
3.703125
4
# 문자열 반대로 출력 inStr = "" outStr = "" count = 0 inStr = input("문자열을 입력하시오: ") count = len(inStr) for i in range(0, count): outStr += inStr[count - (i + 1)] print(outStr) # print(inStr[::-1])
a9c300955bbfb4d7187b8018d0319a4912c76454
BurnFaithful/KW
/Programming_Practice/Python/MachineLearning/Keras/keras13_lstm5_ensemble.py
3,182
3.5625
4
# LSTM(Long Short Term Memory) : 연속적인 data. 시(Time)계열. import numpy as np from keras.models import Sequential, Model from keras.layers import Dense, LSTM, Input #1. 데이터 x = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10, 11], [10, 11, 12], [20, 30, 40], [30, 40, 50], [40, 50, 60]]) y = np.array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 50, 60, 70]) x1_train = x[:10] x2_train = x[10:] y1_train = y[:10] y2_train = y[10:] # print(x) # print("x.shape :", x.shape) # print("y.shape :", y.shape) # x = x.reshape((x.shape[0], x.shape[1], 1)) # print(x) # print("x.shape :", x.shape) print(x1_train) print(x2_train) print("x1_train.shape :", x1_train.shape) print("x2_train.shape :", x2_train.shape) x1_train = x1_train.reshape((x1_train.shape[0], x1_train.shape[1], 1)) x2_train = x2_train.reshape((x2_train.shape[0], x2_train.shape[1], 1)) print("x1_train.shape :", x1_train.shape) print("x2_train.shape :", x2_train.shape) # y1_train = y1_train.reshape((y1_train.shape[0], 1)) # y2_train = y2_train.reshape((y2_train.shape[0], 1)) print("y1_train.shape :", y1_train.shape) print("y2_train.shape :", y2_train.shape) #2. 모델 구성 # model = Sequential() # model.add(LSTM(100, activation='relu', input_shape=(3, 1))) # (column, split) # model.add(Dense(50)) # model.add(Dense(60)) # model.add(Dense(70)) # model.add(Dense(40)) # model.add(Dense(60)) # model.add(Dense(90)) # model.add(Dense(30)) # model.add(Dense(60)) # model.add(Dense(1)) input1 = Input(shape=(3, 1)) input1_lstm = LSTM(40)(input1) hidden1 = Dense(50, activation='relu')(input1_lstm) hidden1 = Dense(60)(hidden1) hidden1 = Dense(70)(hidden1) hidden1 = Dense(40)(hidden1) middle1 = Dense(60)(hidden1) input2 = Input(shape=(3, 1)) input2_lstm = LSTM(50)(input2) hidden2 = Dense(90, activation='relu')(input2_lstm) hidden2 = Dense(40)(hidden2) hidden2 = Dense(60)(hidden2) hidden2 = Dense(70)(hidden2) middle2 = Dense(60)(hidden2) # model.summary() # concatenate를 할 때 input, target arrays의 크기를 맞춰야 한다. from keras.layers.merge import concatenate merge = concatenate([middle1, middle2]) output1 = Dense(60)(merge) output1 = Dense(1)(output1) output2 = Dense(80)(merge) output2 = Dense(1)(output2) model = Model(inputs=[input1, input2], outputs=[output1, output2]) #3. 실행 model.compile(optimizer='adam', loss='mse', metrics=['mse']) from keras.callbacks import EarlyStopping early_stopping = EarlyStopping(monitor='loss', patience=100, mode='auto') # x1_train = np.swapaxes(x1_train, 1, 0) # x2_train = np.swapaxes(x2_train, 1, 0) # model.fit(x, y, epochs=200, batch_size=1, verbose=2) # verbose = 1 default # model.fit(x, y, epochs=10000, batch_size=1, verbose=2, callbacks=[early_stopping]) model.fit([x1_train, x1_train], [y1_train, y1_train], epochs=10000, batch_size=1, verbose=2, callbacks=[early_stopping]) # verbose = 0 : 결과만 보여줌 # verbose = 1 : 훈련과정 상세히 # verbose = 2 : 훈련과정 간략히 # x_input = np.array([25, 35, 45]) # x_input = x_input.reshape((1, 3, 1)) # yhat = model.predict(x_input) # print(yhat)
9a3a6a0f2b2ef12a06cac9ac23f397afba331605
BurnFaithful/KW
/Programming_Practice/Python/Base/Bigdata_day1011/LIST03.py
308
3.9375
4
# 문자열 길이를 이용한 출력 letter = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'] print(letter) length = len(letter) for i in range(length): print(letter[i], end=' ') print(' '.join(letter)) shopping = [] shopping.append("두부") shopping.append("양배추")
5144e5d9fb45e8de24f2801c7dfeb3f0cb19cb16
Anuragjain20/Data-structure-and-algo
/Queue/stackusingqueue.py
922
3.9375
4
from queue import Queue class Stack: def __init__(self): self.q1 = Queue() self.q2 = Queue() self.curr_size = 0 def push(self, x): self.curr_size += 1 self.q2.put(x) while (not self.q1.empty()): self.q2.put(self.q1.queue[0]) self.q1.get() self.q = self.q1 self.q1 = self.q2 self.q2 = self.q def pop(self): if (self.q1.empty()): return data = self.q1.get() self.curr_size -= 1 return data def top(self): if (self.q1.empty()): return -1 return self.q1.queue[0] def size(self): return self.curr_size def isEmpty(self): return self.curr_size == 0 s = Stack() s.push(12) s.push(13) s.push(14) while s.isEmpty() is False: print(s.pop())
b5a083008411fb0bef68ebabaee024e39eb3ea28
Anuragjain20/Data-structure-and-algo
/Linked List/singlylinkedlist.py
4,071
4.09375
4
""" class Node: def __init__(self,value =None): self.value = value self.next = Node class SLinkedList: def __init__(self): self.head = None self.tail = None singlyLinkedList = SLinkedList() node1 = Node(1) node2 = Node(2) singlyLinkedList.head = node1 singlyLinkedList.head.next = node2 singlyLinkedList.tail = node2 """ class Node: def __init__(self,value =None): self.value = value self.next = None class SLinkedList: def __init__(self): self.head = None self.tail = None def __iter__(self): node = self.head while node: yield node node = node.next # insertion in sll def insertSLL(self,value,location): newNode = Node(value) if self.head is None: self.head = newNode self.tail = newNode else: if location == 0: newNode.next = self.head self.head = newNode elif location == 1: newNode.next = None self.tail.next = newNode self.tail = newNode else: try: tempNode = self.head index =0 while index < location-1: tempNode = tempNode.next index +=1 nextNode = tempNode.next tempNode.next = newNode newNode.next = nextNode except : print("no such loaction "+ str(location)) #traversal def traverseSLL(self): if self.head is None: print("The Singly Linked List does not exist") else: node = self.head while node is not None: print(node.value) node = node.next #search def searchSLL(self,nodeValue): if self.head is None: return "the list does not exist" else: index = 0 node = self.head while node is not None: if node.value == nodeValue: return "value is : " + str(node.value) + " it is present at : "+ str(index) node= node.next index+=1 return "The value does not exist in this list" #delete node def deleteNode(self,location): if self.head is None: print("the SLL does not exists") else: if location == 0: if self.head == self.tail: self.head = None self.tail = None else: self.head = self.head.next elif location == 1: if self.head == self.tail: self.head = None self.tail = None else: n = self.head while n is not None: if n.next == self.tail: break n = n.next n.next = None self.tail = n else: try: index = 0 n = self.head while index<location-1: n = n.next index +=1 n1 = n.next n.next = n1.next except: print("no such location : " + str(location)) #delete entire list def deleteEntireSLL(self): if self.head is None: print("the sll does not exits") else: self.head = None self.tail = None s = SLinkedList() s.insertSLL(1,1) s.insertSLL(2,1) s.insertSLL(3,1) s.insertSLL(4,1) print([node.value for node in s]) s.deleteNode(4) s.traverseSLL() s.searchSLL(3) s.deleteEntireSLL() print([node.value for node in s])
7211d015be01620d979bd50c16fe4dfc85b97ec1
Anuragjain20/Data-structure-and-algo
/Queue/queueUsingStack.py
970
3.8125
4
class QueueStack: def __init__(self): self.__s1 = [] self.__s2 = [] def enqueue(self,data): if self.__s1 == []: self.__s1.append(data) return while self.__s1 != []: r= self.__s1.pop() self.__s2.append(r) self.__s1.append(data) while self.__s2 != []: r= self.__s2.pop() self.__s1.append(r) def dequeue(self): if self.__s1 == []: print("empty queue") return return self.__s1.pop() def front(self): if self.__s1 == []: print("empty queue") return return self.__s1[-1] def size(self): return len(self.__s1) def isEmpty(self): return len(self.__s1) == 0 st = QueueStack() st.enqueue(10) st.enqueue(11) st.enqueue(12) st.enqueue(13) while st.isEmpty() == False: print(st.dequeue())
edeec7a377a1133c62ab763a5f214706d29c0493
Anuragjain20/Data-structure-and-algo
/Queue/reverseKqueue.py
508
3.796875
4
from queue import Queue def reverseKqueue(q,k): if q.empty() == True or k > q.qsize(): return if k<= 0: return stack = [] for i in range(k): stack.append(q.queue[0]) q.get() while len(stack) != 0: q.put(stack[-1]) stack.pop() for i in range(q.qsize()- k ): q.put(q.queue[0]) q.get() q = Queue() for i in range(10,40,3): q.put(i) reverseKqueue(q,3) for i in range(10): print(q.get())
985645ba73baf9e3e4e0e0891124f47843c4214b
Aakash-Rajbhar/Calculator
/Calculator.py
4,677
4.125
4
import tkinter from tkinter import * root = Tk() root.geometry('303x467') root.title("Aakash's Calculator") e = Entry(root, width=25,font=("Callibary",15) ,bg="light grey" ,borderwidth=10) e.grid(row=0, column=0, columnspan=10) def btn_click(number): c = e.get() e.delete(0,END) e.insert(0,str(c)+str(number)) def clear(): return e.delete(0, END) def add(): try: first_number = e.get() global f_num global math math = "addition" f_num = float(first_number) e.delete(0,END) except: e.insert(0,"INVALID!!!") def subtract(): try: first_number1 = e.get() global f_num global math math = "subtraction" f_num = float(first_number1) e.delete(0,END) except: e.insert(0,"INVALID!!!") def multiply(): try: first_number1 = e.get() global f_num global math math = "multiplication" f_num = float(first_number1) e.delete(0,END) except: e.insert(0,"INVALID!!!") def divide(): try: first_number1 = e.get() global f_num global math math = "division" f_num = float(first_number1) e.delete(0,END) except: e.insert(0,"INVALID!!!") def sqr_root(): try: first_number1 = e.get() global f_num global math math = "sqr root" f_num = float(first_number1) e.delete(0,END) e.insert(0,f_num**(1/2)) except: e.insert(0,"INVALID!!!") def equal(): try: second_number = e.get() e.delete(0,END) if math=="addition" : e.insert(0,f_num + float(second_number)) elif math=="subtraction" : e.insert(0,f_num - float(second_number)) elif math=="multiplication" : e.insert(0,f_num * float(second_number)) elif math=="division": e.insert(0,f_num / float(second_number)) except: e.insert(0,"NOT DEFINED") btn1 = Button(root, text="1",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(1)) btn2 = Button(root, text="2",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(2)) btn3 = Button(root, text="3",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(3)) btn4 = Button(root, text="4",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(4)) btn5 = Button(root, text="5",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(5)) btn6 = Button(root, text="6",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(6)) btn7 = Button(root, text="7",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(7)) btn8 = Button(root, text="8",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(8)) btn9 = Button(root, text="9",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(9)) btn0 = Button(root, text="0",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(0)) btndot = Button(root, text=".",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(".")) btn_clear = Button(root,text="clear", font=("callibary",11, "bold"),padx=26, pady=20, command= clear) btn_add = Button(root, text="+",font=("callibary",11, "bold"), padx=40, pady=20,command=add ) btn_subtract = Button(root, text="-",font=("callibary",11, "bold"), padx=42, pady=20, command=subtract) btn_multiply = Button(root, text="*",font=("callibary",11, "bold"), padx=40, pady=20, command=multiply ) btn_divide = Button(root, text="/",font=("callibary",11, "bold"), padx=42, pady=20, command=divide ) btn_sqr_root = Button(root, text="sqr root",font=("callibary",11, "bold"), padx=16, pady=20, command=sqr_root ) btn_equal = Button(root, text="=",font=("times new roman",12,"bold") ,padx=39, pady=20, command=equal) btn1.grid(row=3, column=0) btn2.grid(row=3, column=1) btn3.grid(row=3, column=2) btn4.grid(row=2, column=0) btn5.grid(row=2, column=1) btn6.grid(row=2, column=2) btn7.grid(row=1,column=0) btn8.grid(row=1,column=1) btn9.grid(row=1,column=2) btn0.grid(row=4, column=0) btn_clear.grid(row=4, column=1, columnspan=1) btn_add.grid(row=4, column=2) btn_subtract.grid(row=5, column=0) btn_multiply.grid(row=5,column=1) btn_divide.grid(row=5, column=2) btn_equal.grid(row=6, column=1,columnspan=1) btn_sqr_root.grid(row=6,column=0) btndot.grid(row=6, column=2, columnspan=2) root.mainloop()
a5d8b66c92ada51e44ca70d2596a30f0da6f7482
jmlippincott/practice_python
/src/16_password_generator.py
639
4.1875
4
# Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main method. import random, string chars = string.ascii_letters + string.digits + string.punctuation def generate(length): psswd = "".join(random.choice(chars) for i in range(length)) return psswd while True: num = input("How long would you like your new password? ") num = int(num) print(generate(num))
a1bfb994c2cdf4ec03bb660500a757538d67be1f
jmlippincott/practice_python
/src/12_list_ends.py
397
4.09375
4
# Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function. from os import system import random lst_length = random.randint(1,100) lst = [random.randint(0,100) for i in range(lst_length)] print(lst) lst.sort() lst = [lst[0], lst[-1]] print(lst)
58517d054f5f5430f675947ee6f102ca51c42d21
jmlippincott/practice_python
/src/18_cows_and_bulls.py
958
3.859375
4
import random, string from os import system chars = string.digits def generate(digits): return list("".join(random.choice(chars) for i in range(digits))) while True: num_digits_solution = int(input("Enter puzzle size (0-9): ")) solution = generate(num_digits_solution) # print(f"Solution: {solution}") #uncomment to debug guesses = 0 correct = False while correct == False: guesses += 1 bulls = 0 cows = 0 guess = list(input(f"Please enter a {num_digits_solution} digit guess: ")) for i in range(num_digits_solution): if guess[i] == solution[i]: bulls += 1 else: cows += 1 if bulls == num_digits_solution: correct = True else: print(f"Bulls: {bulls}\nCows: {cows}\nGuesses: {guesses}") input(f"Your solution {guess} is correct! Please press <Enter> to start over.") system("clear")
9d5dd5789a533ed84d8f11c82331a87b32095d2d
JagadishThalwar/Python3
/if-else.py
200
3.9375
4
i=20 if(i<15): print("i is smaller than 15") print(" i am in if block") else: print("i is greater than 15") print("i am in else block") print(" i am not in if block and not in else block")
d1e7712d91d57eb33e693963bd33a3cccda59151
Oxidiz3/PythonOneOffs
/FinishedProjects/interpreter.py
3,475
4.0625
4
""" Command Comprehender summary: be able to get a command in a sentence and then understand what it wants and do something with it """ import json data_dict = {} word_type_names = ["action", "object", "target", "actor", "ignore"] command_hint_length = 2 class WordType: def __init__(self, name, d_saved_words): self.name = name try: self.word_list = d_saved_words[name] except KeyError: self.word_list = [] data_dict[self.name] = self def to_dict(self): return { self.name: self.word_list } def read_json_file(): with open("data.json", mode="r+") as json_file: return json.load(json_file) def declare_word_types(read_dict): for name in word_type_names: WordType(name, read_dict) def get_command(): command = input("What is your command? Or x to stop\n").lower() return command def disect_command(command): command_word_list = [] start_num = 0 end_num = 0 for word in command: # If there is a space then that is one word if word == " ": command_word_list.append(command[start_num:end_num]) # Move the start num to the letter after the space start_num = end_num + 1 end_num += 1 # Do once at the end so it gets the last word command_word_list.append(command[start_num:end_num]) return command_word_list def determine_word_type(command_word_list) -> list: l_saved_words = [] l_unsaved_words = [] for key in data_dict: # get every word in the dictionary for word in data_dict[key].word_list: l_saved_words.append(word) # Create a list of all saved words for word in command_word_list: # see if word is in the list of all saved words if word in l_saved_words or word in l_unsaved_words: print(word, "has been saved") else: l_unsaved_words.append(word) return l_unsaved_words def get_word_type(l_unsaved_words): # ask user to input the matching first letters for word in l_unsaved_words: # set a new line print("\n") # label each list from 0 to length wi = 0 # print out data type hints for keys in data_dict: print(keys[0:command_hint_length] + ":" + keys, end="") # if not at the end yet then add a comma if wi < len(data_dict) - 1: print(", ", end="") wi += 1 indicator_letters = input("\nWhat type of word is " + str(word) + "?\n").lower() # then append word using matching list number for key in data_dict: if indicator_letters == key[0:command_hint_length].lower(): data_dict[key].word_list.append(word) def write_to_json(): new_dict = {} for key in data_dict: new_dict.update(data_dict[key].to_dict()) with open("data.json", "w") as write_file: json.dump(new_dict, write_file, indent=2) def __main__(): # setup data d_saved_words = read_json_file() declare_word_types(d_saved_words) # receive input command = get_command() if command.lower() == "x": exit() # interpret input command_word_list = disect_command(command) l_unsaved_words = determine_word_type(command_word_list) get_word_type(l_unsaved_words) # save data write_to_json() __main__() __main__()
f6a05a3977cf18e0a5b424eaec8eb0da10188817
Autonomous-Agent-25/pybits
/sorting/demo/bubble.py
800
4.09375
4
#!/usr/bin/env python # coding: utf-8 #-------------------- """ Bubble sort (Exchange sort family) """ N = 10 import random def bubble_sort(x): print 'Illustrated bubble sort' num_tests = 0 num_swaps = 0 num_passes = 0 unsorted = True while unsorted: num_passes += 1 print 'Pass %i' % num_passes unsorted = False for j in range(1,len(x)): print x num_tests += 1 if x[j-1] > x[j]: num_swaps += 1 x[j-1], x[j] = x[j], x[j-1] unsorted = True print 'Number of tests: %i' % num_tests print 'Number of swaps: %i' % num_swaps return x def main(): a = range(N) random.shuffle(a) a = bubble_sort(a) if __name__ == '__main__': main()
549c2e397f3f0b30aeab13e254242faf8a74f4a1
VYuLinLin/studying-notes
/Python3k/class/dog.py
543
4.03125
4
# 2.7版本呢需要定义object形参 class Dog(): # 一次模拟小狗的简单尝试 def __init__(self, name, age): self.name = name self.age = age def sit(self): # 模拟小狗命令式蹲下 print(self.name.title() + ' is now sitting.') def roll_over(self): # 模拟小狗命名时打滚 print(self.name.title() + ' rolled over!') my_dog = Dog('willie', 6) print('我的小狗的名字是' + my_dog.name.title()) print('我的小狗今年' + str(my_dog.age) + '岁了') my_dog.sit() my_dog.roll_over()
98e13a99f5f668d14d16315f689a6cf5b8981fed
VYuLinLin/studying-notes
/Python3k/pythonCase/hello.py
216
4.0625
4
print("hello world,", "my is python3") name = input('亲,请输入您的姓名,好吗?') # 单行注释 ''' 多行注释 ''' # if name: # else: # print('您还没有输入您的姓名哦!') print(name)
2f20c8687a9fadfe8589c10b3de7c0df51f5b9c8
luiszugasti/adventOfcode2020
/day8/day8.py
2,022
3.671875
4
# day8.py import copy from typing import Tuple from day2.day2 import open_file def parse_input_to_puzzle_scope(puzzle_input): parsed_instructions = [] for entry in puzzle_input: parsed_instructions.append(parse_instruction(entry)) return parsed_instructions def parse_instruction(input): action = input[:3] value = int(input[4:]) return (action, value) def find_value_accumulator(instructions) -> Tuple[int, bool]: seen = [False] * len(instructions) accumulator = 0 program_counter = 0 def _is_cycle(): return seen[program_counter] while (program_counter < len(instructions)): if _is_cycle(): return accumulator, True action, value = instructions[program_counter] seen[program_counter] = True if action == "acc": program_counter = program_counter + 1 if action == "nop": program_counter = program_counter + 1 if action == "jmp": program_counter = program_counter + value if action == "acc": accumulator = accumulator + value return accumulator, False def fix_the_program(instructions): for i in range(len(instructions)): action, value = instructions[i] if action == "nop" or action == "jmp": temp_instructions = copy.deepcopy(instructions) if action == "nop": temp_instructions[i] = "jmp", instructions[i][1] if action == "jmp": temp_instructions[i] = "nop", instructions[i][1] value, isCycle = find_value_accumulator(temp_instructions) if not isCycle: return value if __name__ == '__main__': puzzle_input = open_file("day8_input.txt") parsed_instructions = parse_input_to_puzzle_scope(puzzle_input) answer = find_value_accumulator(parsed_instructions) print("answer: {}".format(answer)) answer = fix_the_program(parsed_instructions) print("answer: {}".format(answer))
7897a1f57d210d621f6262132a6a1e8968ceb34e
allptics/software
/draw.py
1,658
3.96875
4
""" Description: Functions used to render visuals """ import numpy as np import matplotlib.pyplot as plt def draw_paraxial_system(ax, sys): """ Draws a paraxial system ax: plot sys: system """ # plot optical axis ax.axhline(y=0,color="black",dashes=[5,1,5,1],linewidth=1) # plot starting point p = 0 ax.axvline(p, c="green", ls="--", lw=1) # plot lenses for i in sys.elements: if i.id == "thickness": p = p + i.t else: ax.axvline(p, ls=":", lw=1) # plot rays y_max = 0 for ray in sys.rays: x = [] y = [] for pt in ray.pts: x.append(pt[0]) y.append(pt[1]) if pt[1] > abs(y_max): y_max = abs(pt[1]) ax.plot(x, y, lw=1) # plot ending point ax.axvline(p, c="red", ls="--", lw=1) plt.ylim(-y_max*1.2, y_max*1.2) def draw_surface(ax, x, y): """ Description: Used to draw a surface ax: Plot to draw surface on x: x points y: y points """ ax.plot(x, y, 'b', linewidth = 1) def draw_lens(ax, coords): """ Description: Used to draw a lens (mainly just to connect the surfaces) ax: Plot to draw surface on coords: Points from surfaces """ for i in range(len(coords) - 1): ax.plot([coords[i][0][0], coords[i + 1][0][0]], [coords[i][0][1], coords[i + 1][0][1]], 'b', linewidth=1) ax.plot([coords[i][-1][0], coords[i + 1][-1][0]], [coords[i][-1][1], coords[i + 1][-1][1]], 'b', linewidth=1)
fde121bae6e3a8993cd846d8337644a8b8cc3f0e
lizy90/Learn-Project
/Task2.py
1,682
3.546875
4
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分。 输出信息: "<telephone number> spent the longest time, <total time> seconds, on the phone during September 2016.". 提示: 建立一个字典,并以电话号码为键,通话总时长为值。 这有利于你编写一个以键值对为输入,并修改字典的函数。 如果键已经存在于字典内,为键所对应的值加上对应数值; 如果键不存在于字典内,将此键加入字典,并将它的值设为给定值。 """ num_time_dic = {} number_list = [] for i in range(len(calls)): if calls[i][0] not in number_list: number_list.append(calls[i][0]) num_time_dic[calls[i][0]] = int(calls[i][-1]) else: num_time_dic[calls[i][0]] += int(calls[i][-1]) if calls[i][1] not in number_list: number_list.append(calls[i][1]) num_time_dic[calls[i][1]] = int(calls[i][-1]) else: num_time_dic[calls[i][1]] += int(calls[i][-1]) #将字典分离出来放到一个list中,key和value位置调换,排序取最大值。 items = num_time_dic.items() sort_list = sorted([[v[1],v[0]] for v in items]) l_number = sort_list[-1][1] longesttime = sort_list[-1][0] print("<{}> spent the longest time, <{}> seconds, on the phone during September 2016.".format(l_number,longesttime))
4c15d5aa19f8c081321df60ba1d0fa1e21bf01fc
biof309/03-loop-example-watkinsta
/airdata.py
632
3.65625
4
import numpy as np import pandas as pd airdata = pd.read_excel('airdata.xlsx') #Data are measurements of air pollution levels from thousands of #regions throughout the world recorded on WHO. This loop will count how many of #these regions either do or do not meet guidelines - limit is 20 under_count = 0 over_count = 0 for i in airdata['PM10 Annual mean, ug/m3']: if i <= 20: under_count = under_count + 1 elif i > 20: over_count = over_count + 1 print('%d recorded regions do not meet WHO air quality guidelines.' %(over_count)) print('%d recorded regions meet WHO air quality guidelines.' %(under_count))
9d057f9b4c79e82df90153757e7797f593adb009
TasosVellis/Zero
/8.Object Oriented Programming/4_OOPHomework.py
1,425
4.21875
4
import math # Problem 1 # # Fill in the Line class methods to accept coordinates as a # pair of tuples and return the slope and distance of the line. class Line: """ coordinate1 = (3,2) coordinate2 = (8,10) li = Line(coordinate1,coordinate2) li.distance() = 9.433981132056603 li.slope() = 1.6 distance formula = square((x2-x1)^2 + (y2-y1)^2) slope formula = y2-y1 / x2-x1 """ def __init__(self, coor1, coor2): self.coor1 = coor1 self.coor2 = coor2 def distance(self): x1, y1 = self.coor1 x2, y2 = self.coor2 return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) def slope(self): x1, y1 = self.coor1 x2, y2 = self.coor2 return (y2 - y1) / (x2 - x1) coordinate1 = (3, 2) coordinate2 = (8, 10) li = Line(coordinate1, coordinate2) print(li.distance()) print(li.slope()) # Problem 2 # # Fill in the class class Cylinder: """ c = Cylinder(2,3) c.volume() = 56.52 c.surface_area() = 94.2 """ pi = 3.14 def __init__(self, height=1, radius=1): self.height = height self.radius = radius def volume(self): return self.pi * self.radius ** 2 * self.height def surface_area(self): top_bottom = 2 * self.pi * self.radius**2 return top_bottom + 2 * self.pi * self.radius * self.height c = Cylinder(2, 3) print(c.volume()) print(c.surface_area())
f1b22aa04b5b7dd47063d11989529775142c3f88
TasosVellis/Zero
/6.Methods_Functions_builtin/3cardmonty.py
600
4.03125
4
#!/usr/bin/env python from random import shuffle def shuffle_list(mylist): shuffle(mylist) return mylist def player_guess(): guess = '' while guess not in ['0', '1', '2']: guess = input("Pick a number :0, 1 or 2 ") return int(guess) def check_guess(mylist, guess): if mylist[guess] == "O": print("Correct") else: print("Wrong guess") print(mylist) # Initial list my_list = [' ', 'O', ' '] # Shuffle list mixedup_list = shuffle_list(my_list) # User guess guess = player_guess() # Check guess check_guess(mixedup_list, guess)
95728488a63a49f8260cdb346507a16789e42d7a
TasosVellis/Zero
/6.Methods_Functions_builtin/functiopracticeproblems.py
5,789
4.1875
4
# WARMUP SECTION def lesser_of_two_evens(a, b): """ a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd :param a: int :param b: int :return: int lesser_of_two_evens(2,4) --> 2 lesser_of_two_evens(2,5) --> 5 """ if a % 2 == 0 and b % 2 == 0: return min(a, b) else: return max(a, b) def animal_crackers(text): """ a function takes a two-word string and returns True if both words begin with same letter :param text: str :return: bool animal_crackers('Levelheaded Llama') --> True animal_crackers('Crazy Kangaroo') --> False """ wordlist = text.split() return wordlist[0][0] == wordlist[1][0] def makes_twenty(n1, n2): """ Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False :param n1: int :param n2: int :return: bool makes_twenty(20,10) --> True makes_twenty(12,8) --> True makes_twenty(2,3) --> False """ return n1 == 20 or n2 == 20 or (n1 + n2) == 20 # LEVEL 1 def old_macdonald(name): """ Write a function that capitalizes the first and fourth letters of a name¶ :param name: str :return:str old_macdonald('macdonald') --> MacDonald """ if len(name) > 3: return name[:3].capitalize() + name[3:].capitalize() else: return "Name is too short!" def master_yoda(text): """ Given a sentence, return a sentence with the words reversed :param text: str :return: str master_yoda('I am home') --> 'home am I' master_yoda('We are ready') --> 'ready are We' """ return " ".join(text.split()[::-1]) def almost_there(n): """ Given an integer n, return True if n is within 10 of either 100 or 200 :param n:int :return: bool almost_there(90) --> True almost_there(104) --> True almost_there(150) --> False almost_there(209) --> True """ return (abs(100 - n) <= 10) or (abs(200 - n) <= 10) # LEVEL 2 def has_33(nums): """ Given a list of ints, return True if the array contains a 3 next to a 3 somewhere. has_33([1, 3, 3]) → True has_33([1, 3, 1, 3]) → False has_33([3, 1, 3]) → False :param nums:list of ints :return:bool """ for i in range(0, len(nums) - 1): if nums[i] == 3 and nums[i + 1] == 3: return True return False def paper_doll(text): """ Given a string, return a string where for every character in the original there are three characters :param text:str :return:str paper_doll('Hello') --> 'HHHeeellllllooo' paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii' """ new_text = "" for ch in text: new_text += ch * 3 return new_text def blackjack(a, b, c): """ Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 and there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST' :param a: int :param b: int :param c: int :return: int or str blackjack(5,6,7) --> 18 blackjack(9,9,9) --> 'BUST' blackjack(9,9,11) --> 19 """ if sum((a, b, c)) <= 21: return sum((a, b, c)) elif sum((a, b, c)) <= 31 and 11 in (a, b, c): return sum((a, b, c)) - 10 else: return 'BUST' def summer_69(arr): """ Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers. :param arr: list of integers :return: int """ get_result = 0 add = True for num in arr: while add: if num != 6: get_result += num break else: add = False while not add: if num != 9: break else: add = True break return get_result # CHALLENGING PROBLEMS def spy_game(nums): """ Write a function that takes in a list of integers and returns True if it contains 007 in order :param nums: array :return: bool """ code = [0, 0, 7, "x"] for num in nums: if num == code[0]: code.pop(0) # code.remove(num) also works return len(code) == 1 def count_primes(num): """ Write a function that returns the number of prime numbers that exist up to and including a given number :param num: int :return: int """ count = 0 lower = int(input()) upper = int(input()) for num in range(lower, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: count += 1 return count # def count_primes(num): # primes = [2] # x = 3 # if num < 2: # for the case of num = 0 or 1 # return 0 # while x <= num: # for y in range(3,x,2): # test all odd factors up to x-1 # if x%y == 0: # x += 2 # break # else: # primes.append(x) # x += 2 # print(primes) # return len(primes) def print_big(letter): patterns = {1: ' * ', 2: ' * * ', 3: '* *', 4: '*****', 5: '**** ', 6: ' * ', 7: ' * ', 8: '* * ', 9: '* '} alphabet = {'A': [1, 2, 4, 3, 3], 'B': [5, 3, 5, 3, 5], 'C': [4, 9, 9, 9, 4], 'D': [5, 3, 3, 3, 5], 'E': [4, 9, 4, 9, 4]} for pattern in alphabet[letter.upper()]: print(patterns[pattern]) print_big('c')
cabd94e59e8e1dfc0bcb93ca204b7627426279a6
Reiich/Raquel_Curso
/Ejercicio06_MasterMind/main.py
2,591
3.96875
4
# Ejercicio 2 # Escribe un programa que te permita jugar a una versión simplificada del juego # Master Mind. El juego consistirá en adivinar una cadena de números distintos. # Al principio, el programa debe pedir la longitud de la cadena (de 2 a 9 cifras). # Después el programa debe ir pidiendo que intentes adivinar la cadena de números. # En cada intento, el programa informará de cuántos números han sido acertados # (el programa considerará que se ha acertado un número si coincide el valor y la posición). from random import randrange import random def jugar(): len = int(input("Dime una longitud de cadena de numeros entre 2 y 9 cifras:")) probarN = input("Prueba con una cifra : ") aleatorio = crearAleatorio(len) # creo una VAR llamada aleatorio que ejecuta la funcion crear aleatorio print("prueba trampa " + aleatorio) while probarN != aleatorio: #es decir, que no lo adivine COMPLETAMENTE EL NÚM. ALEATORIO eval = evaluar(len, aleatorio, probarN) # creo otra variable total, que llama a la función evaluar print("Con el número " + probarN + " has tenido " + str(eval) + " aciertos.") probarN = input("Intenta adivinar la cadena, dame otro número :") print("FELICIDADES, HAS GANADO!") def crearAleatorio(cad): n_aleat = '' #numero aleatroio debe ser un string para poder concaternar el n1 que resulta. Valor nulo ahora mismo for i in range(cad): x= random.randint(0,9) #tiene que ser string , me devuelve un número entre 0 y 9. Por cada una de las veces que se indica en len x = str(x) n_aleat += x return n_aleat def evaluar(cad, aleatorio, probarN): # creo esta función para que diga si el string (numero) puesto, tiene algun acierto o no cont = 0 a = 0 #empieza desde el cero comprobando si a = b b = 0 for i in range(cad): # va a realizar las comprobaciones hasta alcanzar el rengo dado por len if aleatorio[a] == probarN[b]: cont += 1 #contea el número de veces que sí coinciden los números a += 1 #va avanzando de posición en la comprobación b += 1 #cambia el valor de aleatorio[A] y b. de uno en uno. else: #si no adivina no contea, si no que avanza al siguiente item de la comparación a += 1 b += 1 return cont #una vez que ya ha realizado el bucle FOR, el numero de veces de la longitud de cadena. Devuelve el cont. (contador) # fin de funciones #arranco juego jugar()
599ee94087dc1f1ecca3f354fbcfdaade4bd02b8
Reiich/Raquel_Curso
/receta_15_barrasDesplazamiento/main15.py
2,277
3.5
4
''' uso de la BARRA DE DESPLAZAMIENTO aquí para obtener el valor de la barra, donde el usuario la ha dejado parada se usa: .valueChanged hay que tener en cuenta, que éste método devuelve el valor, que se optine. Automáticamente, si tener que programar nada. Por ello, ucnado definamos la función que mostrará el valor elegido por pantalla, sólo necesitaremos pasar ese valor como parámentro en la función: (de esta manera) def mostrar_azucar(self, valor): self.ui.txt_resultado.setText("Nivel de azucar: {}".format(valor)) #el "valor" lo recoge del parámetro que viene de entrada Es decir, es como si .valueChanged() hiciera un return del punto (Valor) en el que ha quedado la selección. ''' from PyQt5.QtWidgets import QApplication, QDialog, QWidget import sys from niveles_dialog import NivelesDialog class NivelesApp(QDialog): def __init__(self): #todos estos valores se cargan sólo por iniciar la ventana super().__init__() self.ui = NivelesDialog() self.ui.setupUi(self) self.ui.scroll_azucar.valueChanged.connect(self.mostrar_azucar) self.ui.scrollPulso.valueChanged.connect(self.mostrar_pulso) self.ui.sliderColesterol.valueChanged.connect(self.mostrar_colesterol) self.ui.sliderPresion.valueChanged.connect(self.mostrar_presion) self.show() #mostramos la interfaz def mostrar_azucar(self, valor): #este parámetro va a corresponder el el valor de la barra de desplazamiento self.ui.txt_resultado.setText("Nivel de azucar: {}".format(valor)) #el valor lo recoge del parámetro que viene de entrada def mostrar_pulso(self, valor): self.ui.txt_resultado.setText("Pulso: {}".format(valor)) def mostrar_colesterol(self, valor): self.ui.txt_resultado.setText("Nivel colesterol: {}".format(valor)) def mostrar_presion(self, valor): self.ui.txt_resultado.setText("Presión: {}".format(valor)) ############### #inicio aplicacion if __name__ == "__main__": app = QApplication(sys.argv) ventana_inicio = NivelesApp() ventana_inicio.show() sys.exit(app.exec_())
9b5b7c70619cfb3ec1d41bc5288d6a227b7d244d
Reiich/Raquel_Curso
/Ejercicios_ALF_Ficheros/main.py
3,383
3.75
4
''' Created on 21 mar. 2020 @author: Raquel EJERCICIOS - FICHEROS ''' # Ejercicio 1 # Escribir una función que pida un número entero entre 1 y 10 y guarde en un # fichero con el nombre tabla-n.txt la tabla de multiplicar de ese número, # done n es el número introducido. def pideNumero(): n = int(input("Dame un número entero entre el 1 y el 10 : ")) f = open("tabla-" + str(n) + ".txt", "a") #debe se (a) para añadir linea a liea el bucle y no se sobrescriba. for i in range(1, 11): f.write(str(n) + ' x ' + str(i) + ' = ' + str(n * i) + '\n') #puede hacerse todo en una sola línea #la operación tb. Concatenada con STR f.close() #se cierra el archivo ### fin de la función #arranco la función. Programa pideNumero() # Ejercicio 2 # Escribir una función que pida un número entero entre 1 y 10, lea el fichero tabla-n.txt # con la tabla de multiplicar de ese número, done n es el número introducido, y la muestre # por pantalla. Si el fichero no existe debe mostrar un mensaje por pantalla informando de ello. import os def muestraTabla(): while True: # este while hará que pida todo el tiempo un número hasta que el archivo SI SEA ENCONTRADO n = int(input("Dime qué tabla quieres que muestre 1 y el 10 : ")) archivo = "tabla-" + str(n) + ".txt" try: #intenta abrir el archivo para leer "r" archivo = open(archivo, 'r') except FileNotFoundError: # si no encuentra el archivo indicado: print('No existe el fichero con la tabla del', n) else: print(archivo.read()) #si no da error, haz esto. Lee el archivo e imprime por consola break ### fin de la función #arranco la función. Programa muestraTabla() # Ejercicio 3 # Escribir una función que pida dos números n y m entre 1 y 10, lea el fichero tabla-n.txt # con la tabla de multiplicar de ese número, y muestre por pantalla la línea m del fichero. # Si el fichero no existe debe mostrar un mensaje por pantalla informando de ello. import os def muestraTabla(): while True: # este while hará que pida todo el tiempo un número hasta que el archivo SI SEA ENCONTRADO n = int(input("Dime qué tabla quieres que muestre 1 y el 10 : ")) m = int(input("Por qué multiplo? (del 1-10)")) archivo = "tabla-" + str(n) + ".txt" try: #intenta abrir el archivo para leer "r" archivo = open(archivo, 'r') except FileNotFoundError: # si no encuentra el archivo indicado: print('No existe el fichero con la tabla del', n) else: lineas =archivo.readlines() # o convierto en una lista print(lineas[m-1]) # imprimo sólo el elemento de esa lista. break ### fin de la función #arranco la función. Programa muestraTabla() # Ejercicio 4 # # Escribir un programa que acceda a un fichero de internet mediante su url y # muestre por pantalla el número de palabras que contiene. from urllib import request f = request.urlopen('https://raw.githubusercontent.com/asalber/asalber.github.io/master/README.md') f = f.read() print(len(f.split()))
f74f2b5d8ec3cc78ed956c9ad432cf6b428646ac
bhishan/FacebookAutomationDoubleDownCasino
/buychips.py
3,082
3.546875
4
''' Author : Bhishan Bhandari bbhishan@gmail.com The program uses following modules selenium to interact and control the browser time to create pause in the program to behave like we are human pyautogui to find the location of buy chips button in the game to click time is a default module in python which comes installed when installing python. pyautogui and selenium can be installed as follows. In command prompt/terminal type the following and hit enter to install selenium pip install selenium In command prompt/terminal type the following and hit enter to install pyautogui pip install pyautogui ''' from selenium import webdriver import time from selenium.webdriver.common.keys import Keys import pyautogui def main(username, password): try: browser = webdriver.Chrome() except: print "requirement not satisfied." browser.maximize_window() try: browser.get("http://www.codeshareonline.com/doubledown.html") time.sleep(10) codes_paragraph = browser.find_element_by_class_name("paragraph") all_codes = codes_paragraph.find_elements_by_tag_name("a") count = 0 final_codes = [] for codes in all_codes: if "facebook" in codes.get_attribute("href"): print codes.text final_codes.append(codes.text) count += 1 print "Total coupon codes collected : ", count except: print "Could not get coupon codes. " browser.get("https://facebook.com") time.sleep(15) email_field = browser.find_element_by_id("email") password_field = browser.find_element_by_id("pass") email_field.send_keys(username) time.sleep(3) password_field.send_keys(password) password_field.send_keys(Keys.RETURN) time.sleep(20) web_body = browser.find_element_by_tag_name('body') web_body.send_keys(Keys.ESCAPE) for i in range(5): web_body.send_keys(Keys.PAGE_DOWN) time.sleep(2) for i in range(10): web_body.send_keys(Keys.PAGE_UP) time.sleep(2) browser.get("https://apps.facebook.com/doubledowncasino") time.sleep(50) web_body = browser.find_element_by_tag_name('body') web_body.send_keys(Keys.ESCAPE) stat = 0 for i in range(3000): try: time.sleep(5) buy_chips = pyautogui.locateOnScreen("/home/bhishan/bhishanworks/programmingblog/fiverr/facebookgame/buychips.png") button7x, button7y = pyautogui.center(buy_chips) pyautogui.click(button7x, button7y) print "found and clicked" stat = 1 except: print "could not find image of buy chips to click" if stat == 1: break time.sleep(5) for each_code in final_codes: promo_entry = browser.find_element_by_id("package_promo_input") promo_entry.send_keys(each_code) promo_button = browser.find_element_by_id("package_promo_button") promo_button.click() if __name__ == '__main__': main("bbhishan@gmail.com", "password")
162cc8d2c7562d4ca175908fae458dda6b86969c
lmokto/py-designpattern
/singleton/ejemplo-singleton.py
501
3.78125
4
class Singleton (object): instance = None def __new__(cls, *args, **kargs): if cls.instance is None: cls.instance = object.__new__(cls, *args, **kargs) return cls.instance """definimos el objecto""" MySingletonUno = Singleton() MySingletonDos = Singleton() MySingletonUno.nuevo = "hola" print MySingletonDos.nuevo """Creamos otra instancia del mismo objecto, que almacena la variable nuevo""" NuevoSingleton = Singleton() print NuevoSingleton.nuevo
71fb6615811b40c8877b34456a98cdc34650dc92
arvimal/DataStructures-and-Algorithms-in-Python
/04-selection_sort-1.py
2,901
4.5
4
#!/usr/bin/env python3 # Selection Sort # Example 1 # Selection Sort is a sorting algorithm used to sort a data set either in # incremental or decremental order. # How does Selection sort work? # 1. Iterate through the data set one element at a time. # 2. Find the biggest element in the data set (Append it to another if needed) # 3. Reduce the sample space to `n - 1` by the biggest element just found. # 4. Start the iteration over again, on the reduced sample space. # 5. Continue till we have a sorted data set, either incremental or decremental # How does the data sample reduces in each iteration? # [10, 4, 9, 3, 6, 19, 8] - Data set # [10, 4, 9, 3, 6, 8] - [19] - After Iteration 1 # [4, 9, 3, 6, 8] - [10, 19] - After Iteration 2 # [4, 3, 6, 8] - [9, 10, 19] - After Iteration 3 # [4, 3, 6] - [8, 9, 10, 19] - After Iteration 4 # [4, 3] - [6, 8, 9, 10, 19] - After Iteration 5 # [3] - [4, 6, 8, 9, 10, 19] - After Iteration 6 # [3, 4, 6, 8, 9, 10, 19] - After Iteration 7 - Sorted data set # Let's check what the Selection Sort algorithm has to go through in each # iteration # [10, 4, 9, 3, 6, 19, 8] - Data set # [10, 4, 9, 3, 6, 8] - After Iteration 1 # [4, 9, 3, 6, 8] - After Iteration 2 # [4, 3, 6, 8] - After Iteration 3 # [4, 3, 6] - After Iteration 4 # [4, 3] - After Iteration 5 # [3] - After Iteration 6 # [3, 4, 6, 8, 9, 10, 19] - After Iteration 7 - Sorted data set # Observations: # 1. It takes `n` iterations in each step to find the biggest element. # 2. The next iteration has to run on a data set of `n - 1` elements. # 3. Hence the total number of overall iterations would be: # n + (n - 1) + (n - 2) + (n - 3) + ..... 3 + 2 + 1 # Since `Selection Sort` takes in `n` elements while starting, and goes through # the data set `n` times (each step reducing the data set size by 1 member), # the iterations would be: # n + [ (n - 1) + (n - 2) + (n - 3) + (n - 4) + ... + 2 + 1 ] # Efficiency: # We are interested in the worse-case scenario. # In a very large data set, an `n - 1`, `n - 2` etc.. won't make a difference. # Hence, we can re-write the above iterations as: # n + [n + n + n + n ..... n] # Or also as: # n x n = n**2 # O(n**2) # Final thoughts: # Selection Sort is an algorithm to sort a data set, but it is not particularly # fast. For `n` elements in a sample space, Selection Sort takes `n x n` # iterations to sort the data set. def find_smallest(my_list): smallest = my_list[0] smallest_index = 0 for i in range(1, len(my_list)): if my_list(i) < smallest: smallest = my_list(i) smallest_index = i return smallest_index def selection_sort(my_list): new_list = [] for i in range(len(my_list)): smallest = find_smallest(my_list) new_list.append(my_list.pop(smallest)) return new_list print(selection_sort([10, 12, 9, 4, 3, 6, 100]))
06eed5f573e0c33e89a282600aead38f947dd078
dgkimura/sudoku
/src/solver.py
2,506
3.84375
4
# solver.py # # A solver will insert numbers into a grid to solve the puzzle. class Solver: def __init__(self, grid): self._grid = grid def populate(self, nums): for i, n in enumerate(nums): if n is not None: # print i self._grid.cells[i].insert(n) def solve(self): # a = SingleEntry() # a.run(self._grid) b = BruteForce() b.run(self._grid) #print self._grid class SingleEntry: """ Single entry algorithm passes over all cells and marks any cell that has a single valid answer. """ def run(self, grid): updated = True while updated: updated = False for i, c in enumerate(grid.cells): if c.num is not None: continue valid = c.POSSIBLE_ANSWERS - c._row.union(c._col) \ .union(c._box) if (len(valid) == 1): c.num = valid.pop() print "SINGLE ENTRY {0} {1}".format(c.num, i) updated = True class BruteForce: """ Brute force algorithm that tries every possibility and returns the first found answer. """ def run(self, grid): stack = [] while (not self.is_solved(grid.cells)): for i, c in enumerate(grid.cells): if c.num is not None: continue if self.increment(c): stack.append(c) else: while len(stack) > 1: c = stack.pop() if self.increment(c): stack.append(c) break else: c.erase() if len(stack) == 1: c = stack.pop() c.disallow() break def is_solved(self, cells): for c in cells: if c.num is None: return False return True def increment(self, cell): start = (cell.num or 0) + 1 for n in range(start, len(cell.POSSIBLE_ANSWERS) + 1): if n not in cell.disallowed and cell.can_insert(n): if cell.num: cell.erase() cell.insert(n) # print "INCREMENT END {0}".format(self.num) return True return False
3eea539c849e14f831231c3bdceb2193c6138bdb
evgenyneu/ASP3162
/10_integration_python/src/exact_solution.py
1,740
3.9375
4
import numpy as np def exact(x, n): """ Calculate exact solution of Lane-Emden equation. Parameters ---------- x : float or ndarray Value or values of independent variable n : integer Parameter 'n' of the Lane-Emden equation Returns : float or ndarray ------- Value or values of the exact solution """ if n == 0: return 1 - 1/6 * np.power(x, 2) elif n == 1: # We need to calculate sin(x)/x # when x=0, this is equal to 1 a = np.sin(x) b = np.array(x) return np.divide(a, b, out=np.ones_like(a), where=b != 0) elif n == 5: return np.power(1 + 1/3 * np.power(x, 2), -0.5) else: raise ValueError(f"Incorrect n value: {n}") def exact_derivative(x, n): """ Calculate exact values for the derivatives of the solutions of Lane-Emden equation. Parameters ---------- x : float or ndarray Value or values of independent variable n : integer Parameter 'n' of the Lane-Emden equation Returns : float or ndarray ------- Value or values of the exact solution """ if n == 0: return -x/3 elif n == 1: a = np.cos(x) b = np.array(x) # Assign value 0 to terms that have division by zero term1 = np.divide(a, b, out=np.zeros_like(a), where=b != 0) a = np.sin(x) b = np.power(x, 2) # Assign value 0 to terms that have division by zero term2 = np.divide(a, b, out=np.zeros_like(a), where=b != 0) return term1 - term2 elif n == 5: return -x / (3 * np.power(1 + np.power(x, 2) / 3, 3/2)) else: raise ValueError(f"Incorrect n value: {n}")
465d7a23163f564c85cbc09aa09657a310e95393
evgenyneu/ASP3162
/07_upwind_wendroff/plotting/create_movies.py
3,225
3.53125
4
# Create movies of solutions of advection equation import matplotlib.animation as animation from compare_animated import animate, prepare_for_animation import matplotlib import os from plot_utils import create_dir matplotlib.use("Agg") def create_movie(methods, initial_conditions, courant_factor, movie_dir, filename, t_end, nx, fps, ylim): """ Create a movie of solution of advection equation Parameters ---------- methods : list of str Numerical methods to be used: ftcs, lax, upwind, lax-wendroff initial_conditions : str Type of initial conditions: square, sine courant_factor : float Parameter used in the numerical methods movie_dir : str Directory where the movie file is saved filename : str Movie file name t_end : float The largest time of the solution. nx : int Number of x points. fps : int Frames per second for the movie ylim : tuple Minimum and maximum values of the y-axis. """ print("...") Writer = animation.writers['ffmpeg'] writer = Writer(fps=fps, metadata=dict(artist='Evgenii Neumerzhitckii'), bitrate=1800) fig, lines, text, x, y, z = \ prepare_for_animation(methods=methods, initial_conditions=initial_conditions, t_end=t_end, nx=nx, ylim=ylim, courant_factor=courant_factor) timesteps = z[0].shape[0] create_dir(movie_dir) path_to_file = os.path.join(movie_dir, filename) with writer.saving(fig, path_to_file, dpi=300): for i in range(timesteps): animate(i=i, lines=lines, text=text, x_values=x, t_values=y, solution=z) writer.grab_frame() def make_movies(): """ Create movies of solutions of advection equation """ movies_dir = "movies" print( (f"Creating movies in '{movies_dir}' directory.\n" "This will take a couple of minutes.") ) methods = ['Exact', 'Lax-Wendroff', 'Lax', 'Upwind'] t_end = 2 fps = 10 create_movie(methods=methods, initial_conditions='sine', courant_factor=0.5, movie_dir=movies_dir, filename='01_sine_c_0.5.mp4', t_end=t_end, nx=100, ylim=(-1.5, 1.5), fps=fps) create_movie(methods=methods, initial_conditions='square', courant_factor=0.5, movie_dir=movies_dir, filename='02_square_c_0.5.mp4', t_end=t_end, nx=100, ylim=(-0.5, 1.5), fps=fps) create_movie(methods=methods, initial_conditions='sine', courant_factor=1, movie_dir=movies_dir, filename='03_sine_c_1.mp4', t_end=t_end, nx=200, ylim=(-1.5, 1.5), fps=fps) create_movie(methods=methods, initial_conditions='square', courant_factor=1, movie_dir=movies_dir, filename='04_square_c_1.mp4', t_end=t_end, nx=200, ylim=(-0.5, 1.5), fps=fps) if __name__ == '__main__': make_movies()
da6ff2dc49a425b99fde124769ba8fe2567d0b6d
evgenyneu/ASP3162
/05_advection_equation/parts/02_numerical/plotting/solver.py
3,346
3.5
4
# Solve a heat equation import subprocess from plot_utils import create_dir import numpy as np import os import struct import array def read_solution_from_file(path_to_data): """ Read solution from a binary file. Please refer to README.md for description of the binary file format used here. Parameters ---------- path_to_data : str Path to the binary file containing solution data. Returns ------- (x, y, z) tuple x, y, and z values of the solution, where x and y and 1D arrays, and z is a 2D array. """ data = open(path_to_data, "rb").read() # nx: number of x points # ---------- start = 0 end = 4*3 (_, nx, _) = struct.unpack("@iii", data[start: end]) # nt: number of t points # ---------- start = end end = start + 4*3 (_, nt, _) = struct.unpack("@iii", data[start: end]) # x values # --------- start = end + 4 end = start + nx * 8 x_values = array.array("d") x_values.frombytes(data[start:end]) # t values # --------- start = end + 8 end = start + nt * 8 t_values = array.array("d") t_values.frombytes(data[start:end]) # Solution: 2D array # --------- start = end + 8 end = start + nx * nt * 8 solution = array.array("d") solution.frombytes(data[start:end]) solution = np.reshape(solution, (nt, nx), order='C') return (x_values, t_values, solution) def solve_equation(x_start, x_end, nx, t_start, t_end, nt, method): """ Runs Fortran program that solves equation v_t + v v_x = 0 and returns the solution. Parameters ---------- x_start : float The smallest x value x_end : float The largest x value nx : int The number of x points in the grid t_start : float The smallest t value t_end : float The largest t value nt : int The number of t points in the grid method : str Numerical method to be used: centered, upwind Returns ------- (x, y, z, dx, dt, courant) tuple x, y, z : values of the solution, where x and y and 1D arrays, and z is a 2D array. dx, dt : position and time steps dt_dx : ratio dt / dx """ subdir = "tmp" create_dir(subdir) path_to_data = os.path.join(subdir, "data.bin") parameters = [ ( f'../build/main {path_to_data}' f' --x_start={x_start}' f' --x_end={x_end}' f' --nx={nx}' f' --t_start={t_start}' f' --t_end={t_end}' f' --nt={nt}' f' --method={method}' ) ] child = subprocess.Popen(parameters, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) message = child.communicate()[0].decode('utf-8') rc = child.returncode success = rc == 0 if not success: print(message) return None x, y, z = read_solution_from_file(path_to_data) dx = x[1] - x[0] dt = y[1] - y[0] os.remove(path_to_data) os.rmdir(subdir) dt_dx = dt/dx z = np.nan_to_num(z) return (x, y, z, dx, dt, dt_dx)
671a2d1b58e546d9b38a7499d231412d53418de1
systembase-kikaku/python-learn
/deep_learning1/numpy1.py
269
3.53125
4
import numpy as np x = np.array([1.0, 2.0, 3.0]) print(x) v1 = np.array([3, 4, 5]) v2 = np.array([1, 2, 3]) print(v1 + v2) print(v1 - v2) print(v1 * v2) print(v1 / v2) A = np.array([[1, 2], [3, 4], [5, 6]]) print(A.shape) print(A.dtype) print(A + 10) print(A * 10)
48e3534a6cc05a5068103994a6599a20f50c6f39
davidsekielyk/frro-soporte-2018-07
/practico-02/ejercicio-01.py
544
3.984375
4
#Ejercicio 1 print("""Ejercicio 1 Escribir una clase llamada rectángulo que contenga una base y una altura, y que contenga un método que devuelva el área del rectángulo. """) class Triangulo(): def __init__(self, base, altura): self.base = base self.altura = altura def area(self): print("El area del triangulo es:", self.base * self.altura) triangulo = Triangulo(int(input("Ingrese la base del triangulo: ")),int(input("Ingrese la altura del triangulo: "))) print() triangulo.area()
7d53e8a283b5c82d079752eee3465214cbf683da
davidsekielyk/frro-soporte-2018-07
/practico-01/ejercicio-12.py
293
3.859375
4
#Ejercicio 12 print("Ejercicio 12: Determinar la suma de todos los numeros de 1 a N. N es un número que se ingresa por consola.\n") a = int(input("ingrese un numero: ")) rdo = 0 for i in range(a): rdo = rdo + (a - i) print("La suma de todos los numeros de 1 a",a, "es:",rdo)
d528adcaaa0b77ae7adfd71829542fa02eedc1dd
gomgomigom/Exercise_2
/w_1-2/201210_0.py
281
3.703125
4
i = 1 current = 1 previous = 0 while i <= 10: print(current) temp = previous previous = current current = current + temp i += 1 i = 1 current = 1 previous = 0 while i <= 10: print(current) previous, current = current, current + previous i += 1
a287c15b12ed3e3194c5aedac6b2fbb8adeb629b
gomgomigom/Exercise_2
/w_1-2/201210_4.py
2,013
4.125
4
# numbers라는 빈 리스트를 만들고 리스트를 출력한다. # append를 이용해서 numbers에 1, 7, 3, 6, 5, 2, 13, 14를 순서대로 추가한다. 그 후 리스트를 출력한다. # numbers 리스트의 원소들 중 홀수는 모두 제거한다. 그 후 다시 리스트를 출력한다. # numbers 리스트의 인덱스 0 자리에 20이라는 수를 삽입한 후 출력한다. # numbers 리스트를 정렬한 후 출력한다. # 빈 리스트 만들기 numbers = [] print(numbers) numbers.append(1) numbers.append(7) numbers.append(3) numbers.append(6) numbers.append(5) numbers.append(2) numbers.append(13) numbers.append(14) print(numbers) # numbers에서 홀수 제거 i = 0 while i < len(numbers): if numbers[i] % 2 == 1: del numbers[i] i -= 1 i += 1 print(numbers) # numbers의 인덱스 0 자리에 20이라는 값 삽입 numbers.insert(0, 20) print(numbers) # numbers를 정렬해서 출력 numbers.sort() print(numbers) print(type(numbers)) for num in numbers: print(num) for x in range(2, 10, 2): print(x) numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] print(range(len(numbers))) for num in range(len(numbers)): print(f"{num} {numbers[num]}") print(1,2) print(1, 2) for i in range(1,11): print(f'2^{i} = {2 ** i}') i = 1 while i <= 10: print(f'2^{i} = {2 ** i}') i += 1 for i in range(11): print("2^{} = {}".format(i, 2 ** i)) for i in range(1, 10): for j in range(1, 10): print(f"{i} * {j} = {i * j}") i = 1 while i < 10: j = 1 while j < 10: print(f"{i} * {j} = {i * j}") j += 1 i += 1 for i in range(1,10): if i < 10 : a = 1 print("{} * {} = {}".format(a, i, a * i)) print("if문이 실행!") else : a += 1 i = 1 print("else문이 실행!") for a in range(1,1001): for b in range(a,1001): c = 1000 - a - b if a ** 2 + b ** 2 == c ** 2 and a + b + c == 1000 and a < b < c: print(a * b * c) print("완료")
7d9ae260ebd619e69325316d76119ad2ce0b010d
gomgomigom/Exercise_2
/w_1-2/201212_3.py
519
3.65625
4
import random guess = -1 ANSWER = random.randint(1,20) NUM_TRIES = 4 tries = 0 while guess != ANSWER and NUM_TRIES > tries: guess = int(input(f"기회가 {NUM_TRIES - tries}번 남았습니다. 1-20 사이의 숫자를 맞혀 보세요: ")) tries += 1 if ANSWER > guess: print("Up") elif ANSWER < guess: print("Down") if guess == ANSWER: print(f"축하합니다. {tries}번 만에 숫자를 맞히셨습니다.") else: print(f"아쉽습니다. 정답은 {ANSWER}입니다.")
2929a547ca339b6226756026a221d48a7482b5d8
eriksylvan/PythonChallange
/1/1.py
430
3.578125
4
# http://www.pythonchallenge.com/pc/def/map.html # print (ord('a')) # print (ord('.')) # # print (ord('A')) # print (ord('z')) # print (ord(' ')) #hej with open("input") as f: for line in f: for ch in line: asciiNo = ord(ch) if ord('A') <= asciiNo <= ord('z'): print(chr((asciiNo - ord('a') + 2) % 26 + ord('a')), end = '') else: print(ch, end = '')
393888cb2cb65dc22e7c369dc786dd89618d772d
JoseLuisAcv2/Algoritmos-II-Proyecto-II
/listaReproduccion.py
4,251
3.59375
4
# # ALGORITMOS II - PROYECTO II # # REPRODUCTOR DE MUSICA # # AUTORES: # - Jose Acevedo 13-10006 # - Pablo Dario Betancourt 13-10147 # TAD Lista de reproduccion. Implementado con lista circular doblemente enlazada # Modulo from cancion import * # Clase para nodos de la lista enlaada class nodoLista: # Constructor: # Un nodo tiene apuntador al siguiente, al anterior y los datos satelites con la informacion de la cancion def __init__(self,cancion): self.cancion = cancion self.prev = None self.next = None # Implementacion del TAD Lista de Reproduccion class listaReproduccion: # Constructor: # Se implementa con una lista enlazada. Inicialmente vacia def __init__(self): self.head = None self.size = 0 # Funcion para agregar canciones a la lista de reproduccion def agregar(self,cancion): node = nodoLista(cancion) if self.head == None: node.next = node node.prev = node self.head = node self.size += 1 else: if self.buscar(cancion) == None: node.next = self.head self.head.prev.next = node node.prev = self.head.prev self.head.prev = node self.head = node self.size+=1 # Funcion para agregar canciones a la lista de reproduccion al final de la lista def agregar_final(self,cancion): node = nodoLista(cancion) if self.head == None: node.next = node node.prev = node self.head = node self.size += 1 else: if self.buscar(cancion) == None: self.head.prev.next = node node.prev = self.head.prev self.head.prev = node node.next = self.head self.size+=1 # Funcion para buscar si una determinada cancion se encuentra en la lista de reproduccion # En caso de estar presente retorna un apuntador a la cancion. En caso contrario retorna None def buscar(self,cancion): x = self.head for i in xrange(self.size): if x.cancion.esIgual(cancion) : return x x = x.next return None # Funcion que recibe una cancion y la elimina de la lista de reproduccion def eliminar(self,cancion): x = self.buscar(cancion) if x != None: x.prev.next = x.next x.next.prev = x.prev if x == self.head : self.head = x.next self.size-=1 # Funcion que compara dos TADs cancion. # Se pueden comparar por titulo de cancion o por artista de cancion def comp(self,a,b,c): # Comparar por titulo if c == 0: return a.cancion.esMenorTitulo(b.cancion) # Comparar por artista else: return a.cancion.esMenorArtista(b.cancion) # Funcion que ordena la lista de reproduccion por orden lexicografico del titulo # de las canciones. Para ordenar la lista se utiliza el algoritmo Mergesort def ordenarTitulo(self): self.head.prev.next = None self.head.prev = None self.head = self.mergesort(self.head,0) x = self.head while x!=None and x.next != None: x = x.next self.head.prev = x x.next = self.head # Funcion que ordena la lista de reproduccion por orden lexicografico del artista # de las canciones. Para ordenar la lista se utiliza el algoritmo Mergesort def ordenarArtista(self): self.head.prev.next = None self.head.prev = None self.head = self.mergesort(self.head,1) x = self.head while x!=None and x.next != None: x = x.next self.head.prev = x x.next = self.head # Algoritmo Mergesort para ordenar la lista de reproduccion def mergesort(self,head,flag): if head == None or head.next == None: return head second = self.split(head) head = self.mergesort(head,flag) second = self.mergesort(second,flag) return self.merge(head,second,flag) # Sub procedimiento de Mergesort para hacer merge de dos # listas enlazadas def merge(self,head,second,flag): if head == None : return second if second == None : return head if self.comp(head,second,flag): head.next = self.merge(head.next,second,flag) head.next.prev = head head.prev = None return head else: second.next = self.merge(head,second.next,flag) second.next.prev = second second.prev = None return second # Sub procedimiento de Mergesort para dividir una lista # enlazada en dos listas enlazadas def split(self,head): fast = head slow = head while fast.next != None and fast.next.next != None: fast = fast.next.next slow = slow.next tmp = slow.next slow.next = None return tmp
4e3f98f1e05289dc88477754d42d26ec0d7c82ec
DoyKim-20/DoyKim-20.github.io
/Practice02.py
269
3.640625
4
print("2번 과제 시작!") year = 19 pin = '990329-1083599' if pin[7]==3 or pin[7]==4 : year = year + 1 print('김멋사군의 탄생일은 ' + str(year) + str(pin[0:2]) + '년 ' + str(pin[2:4]) + '월 ' + str(pin[4:6]) + '일 입니다') #60192164 김도영
6dd28e4f0b0e2b51deb6a51d4ed0ee636b321616
kevinkepp/ann
/ann/act.py
1,279
3.609375
4
import numpy as np import scipy.special def linear(z): return z def d_linear(a): return 1 def relu(z): return z * (z > 0) def d_relu(a): return a > 0 def tanh(z): return np.tanh(z) def d_tanh(a): return 1 - a ** 2 def sigmoid(z): return scipy.special.expit(z) def d_sigmoid(a): return a * (1 - a) def sigmoid_with_binary_xentropy(z): """To be used in conjunction with loss.binary_xentropy_with_sigmoid""" return sigmoid(z) def softmax(z): exps = np.exp(z - np.max(z, axis=1, keepdims=True)) return exps / np.sum(exps, axis=1, keepdims=True) def softmax_with_xentropy(z): """To be used in conjunction with loss.xentropy_with_softmax""" return softmax(z) def get_d_act(act): if act == linear: return d_linear elif act == relu: return d_relu elif act == tanh: return d_tanh elif act == sigmoid: return d_sigmoid elif act == softmax: # derivative depends on derivative of loss function and thus will be calculated in layer backward method return None elif act == softmax_with_xentropy or act == sigmoid_with_binary_xentropy: # derivative can be simplified and thus will be calculated in layer backward method return None else: raise NotImplementedError("No derivative for activation function '{}'".format(act.__name__))
fa8385e10ce82dcce011f7f0c8b3384c4b4e75f9
Abe27342/project-euler
/src/65.py
583
3.734375
4
import fractions def get_frac(continued_fraction_list): x = continued_fraction_list[::-1] y = fractions.Fraction(x[0]) x.remove(x[0]) while(len(x) > 0): y = x[0] + 1/y x.remove(x[0]) return(y) def get_continued_frac(n, de): d = fractions.Fraction(n,de) x = [] while(int(d) != d): x.append(int(d)) d = 1/(d-int(d)) x.append(int(d)) return(x) def sum_of_digits(n): return(sum([int(i) for i in str(n)])) e = [1]*100 e[0] = 2 for i in range(1,34): e[3*i-1] = 2*i print sum_of_digits(get_frac(e).numerator)
581970e71a706fc9c2eefc33ca0f9afe28042361
Abe27342/project-euler
/src/359.py
2,443
3.71875
4
''' First, a simulation... Evidently, floor 1 contains all triangular numbers. Looking on oeis,... floor 2 contains numbers 2, 7, 9, 16 and then a(n) = 2a(n-1) - 2a(n-3) + a(n-4) a(1) = 2 a(2) = 7 a(3) = 9 a(4) = 16 floor 3 contains a(0) = 1 then a(n) = n^2 - a(n-1) for n >= 1. floor 4 contains blah blah blah it turns out that P(f, r) is something like (r + f)(r + f - 1)/2 + f/2 * (-1)^(r + f). This formula works for even f, and then for odd ones you have to modify it slightly. Should be evident by the simulation. Why it works, I have no idea. Also note that the given number is 2^27 * 3^12. That's how we arrive at the answer. ''' from collections import defaultdict from random import randint squares = {i**2 for i in range(10000)} def is_square(n): return n in squares class Hotel: def __init__(self): self.floors = defaultdict(list) self.next_person_num = 1 def try_place_in_floor(self, person_num, floor_num): floor = self.floors[floor_num] if len(floor) == 0: floor.append(person_num) return True else: last_person = floor[-1] if is_square(last_person + person_num): floor.append(person_num) return True return False def place_person(self, person_num): floor_num = 1 while not self.try_place_in_floor(person_num, floor_num): floor_num += 1 def place_next_person(self): self.place_person(self.next_person_num) self.next_person_num += 1 hotel = Hotel() def P(f, r): while not (f in hotel.floors and r-1 < len(hotel.floors[f])): hotel.place_next_person() return hotel.floors[f][r - 1] def fast_P(f, r): if f == 1: return r * (r + 1) / 2 negative_one_coeff = f / 2 negative_one_power = r + (f % 2) a1 = f - (f % 2) a2 = a1 - 1 return (r + a1) * (r + a2) / 2 + negative_one_coeff * (-1)**(negative_one_power) ''' print P(25, 75) hotel.floors[1] = 0 hotel.floors[2] = 0 hotel.floors[3] = 0 hotel.floors[4] = 0 hotel.floors[5] = 0 print hotel.floors print [fast_P(11, i) for i in range(1, 5)] print hotel.floors[11] experimentation ''' def try_random_sample_case(): f = randint(40, 150) r = randint(100, 200) assert P(f, r) == fast_P(f, r) for i in range(1000): try_random_sample_case() print [fast_P(1, i) for i in range(1, 101)] print [P(1, i) for i in range(1, 101)] n = 2**27 * 3**12 print n total = 0 for p2 in range(28): for p3 in range(13): d = 2**p2 * 3**p3 n_over_d = n / d total += fast_P(n_over_d, d) total %= 10**8 print total
2e31593ab0115bab5ac39d77731cef845f299b4c
Abe27342/project-euler
/src/51.py
1,520
3.609375
4
''' this code sucks also used this: from helpers import isPrime x = sum([isPrime(101010*k+20303) for k in range(1,10)]) print(x) ''' from helpers import sieve import itertools num_set = ['0','1','2','3','4','5','6','7','8','9','*'] primes = sieve(10000000) print('primes generated') def triple_digit(n): n = str(n)[0:-1] x = [n.count(i) for i in n] if(3 in x): indices = [i for i in range(len(x)) if x[i] == 3] return(indices) #print(triple_digit(3221125)) m = [p for p in primes if triple_digit(p) != None] m.sort(key=lambda x:triple_digit(x)) print('first stage done') #print(m) paired_m = [] i = 0 while(i < len(m)): p = m[i] count = 0 while(i+count < len(m) and triple_digit(p) == triple_digit(m[i+count])): count += 1 #print(triple_digit(p),triple_digit(p+count)) paired_m.append([m[j] for j in range(i,i+count)]) i += count #print(paired_m) print('second stage done') for triple_list in paired_m: if(len(triple_list) == 1): print(triple_list) for i in range(len(triple_list)): element = triple_list[i] #i could use enumerate but it's 1am gg indices = triple_digit(element) element = list(str(element)) for c in indices: element[c] = '*' triple_list[i] = ''.join(element) #print(triple_list) for s in triple_list: if(triple_list.count(s) > 5): print(s) break else: triple_list.remove(s)
5dc34de95e32b2e08f8f504fda056c1febfcc5cb
Abe27342/project-euler
/src/287.py
2,675
3.59375
4
# (0,0) is bottom_left # Because I'm too lazy to precompute lmao from helpers import memoize @memoize def get_pow_2(n): return pow(2, n) def is_top_left(N, bottom_right): x,y = bottom_right return x < get_pow_2(N - 1) and y >= get_pow_2(N - 1) def is_bottom_left(N, top_right): x,y = top_right return x < get_pow_2(N - 1) and y < get_pow_2(N - 1) def is_bottom_right(N, top_left): x,y = top_left return x >= get_pow_2(N - 1) and y < get_pow_2(N - 1) def is_top_right(N, bottom_left): x,y = bottom_left return x >= get_pow_2(N - 1) and y >= get_pow_2(N - 1) def square_is_black(N, square): x,y = square middle = get_pow_2(N - 1) return (x - middle) * (x - middle) + (y - middle) * (y - middle) <= middle * middle # Returns the encoding length for block with the given top_left and bottom_right corners in the 2^N by 2^N image. def encoding_length(N, top_left, bottom_right): x_left, y_top = top_left x_right, y_bottom = bottom_right bottom_left = (x_left, y_bottom) top_right = (x_right, y_top) if is_top_left(N, bottom_right): if not square_is_black(N, bottom_right): return 2 # because 11 encoding gets all of the white parts. if square_is_black(N, bottom_right) and square_is_black(N, top_left): return 2 elif is_top_right(N, bottom_left): if not square_is_black(N, bottom_left): return 2 if square_is_black(N, bottom_left) and square_is_black(N, top_right): return 2 elif is_bottom_left(N, top_right): if not square_is_black(N, top_right): return 2 if square_is_black(N, bottom_left) and square_is_black(N, top_right): return 2 elif is_bottom_right(N, top_left): if not square_is_black(N, top_left): return 2 if square_is_black(N, bottom_right) and square_is_black(N, top_left): return 2 current_square_size = y_top - y_bottom + 1 # Fuck this coordinate system :P if current_square_size == 1: return 2 assert current_square_size % 2 == 0 divided_size = current_square_size / 2 top_left1 = top_left top_left2 = (x_left + divided_size, y_top) top_left3 = (x_left, y_bottom + divided_size - 1) top_left4 = (x_left + divided_size, y_bottom + divided_size - 1) bottom_right1 = (x_left + divided_size - 1, y_bottom + divided_size) bottom_right2 = (x_right, y_bottom + divided_size) bottom_right3 = (x_left + divided_size - 1, y_bottom) bottom_right4 = bottom_right return 1 + encoding_length(N, top_left1, bottom_right1) + encoding_length(N, top_left2, bottom_right2) + encoding_length(N, top_left3, bottom_right3) + encoding_length(N, top_left4, bottom_right4) def D(N): return encoding_length(N, (0, pow(2, N) - 1), (pow(2, N) - 1, 0)) print [D(i) for i in range(2, 12)] print D(24)
bb1e8d8a320464f802cd28823c3b551f15906dfe
MilletPu/IR-hw
/IR-hw/index.py
11,196
3.53125
4
# -*- encoding: utf8 -*- from __future__ import absolute_import, division, print_function import VB import collections import functools import math DOCUMENT_DOES_NOT_EXIST = 'The specified document does not exist' TERM_DOES_NOT_EXIST = 'The specified term does not exist' class HashedIndex(object): """ InvertedIndex structure in the form of a hash list implementation. """ def __init__(self, initial_terms=None): """ Construct a new HashedIndex. An optional list of initial terms may be passed which will be automatically added to the new HashedIndex. """ self._documents = collections.Counter() self._terms = {} self._inverted_index = {} self._freeze = False if initial_terms is not None: for term in initial_terms: self._terms[term] = {} def __getitem__(self, term): return self._terms[term] def __contains__(self, term): return term in self._terms def __repr__(self): return '<HashedIndex: {} terms, {} documents>'.format( len(self._terms), len(self._documents) ) def __eq__(self, other): return self._terms == other._terms and self._documents == other._documents def add_term_occurrence(self, term, document): """ Adds an occurrence of the term in the specified document. """ if isinstance(term, tuple): term = term[0] if isinstance(document, tuple): document = document[0] if isinstance(term, unicode): term = term.encode('utf-8') if isinstance(document, unicode): document = document.encode('utf-8') if document not in self._documents: self._documents[document] = 0 if term not in self._terms: if self._freeze: return else: self._terms[term] = collections.Counter() if document not in self._terms[term]: self._terms[term][document] = 0 self._documents[document] += 1 self._terms[term][document] += 1 def get_total_term_frequency(self, term): """ Gets the frequency of the specified term in the entire corpus added to the HashedIndex. """ if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) return sum(self._terms[term].values()) def get_term_frequency(self, term, document, normalized=False): """ Returns the frequency of the term specified in the document. """ if document not in self._documents: raise IndexError(DOCUMENT_DOES_NOT_EXIST) if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) result = self._terms[term].get(document, 0) if normalized: result /= self.get_document_length(document) return result def get_document_frequency(self, term): """ Returns the number of documents the specified term appears in. """ if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) else: return len(self._terms[term]) def get_dict(self): """ Dict with words and its df """ dict = self.items() for postlist in dict: dict[postlist] = len(dict[postlist]) return dict def get_longword(self): dict = self.get_dict().keys() longword = '' for words in dict: longword += str(words) return longword def get_document_length(self, document): """ Returns the number of terms found within the specified document. """ if document in self._documents: return self._documents[document] else: raise IndexError(DOCUMENT_DOES_NOT_EXIST) def get_documents(self, term): """ Returns all documents related to the specified term in the form of a Counter object. """ if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) else: return self._terms[term] def terms(self): return list(self._terms) def documents(self): return list(self._documents) def items(self): return self._terms def get_tfidf(self, term, document, normalized=False): """ Returns the Term-Frequency Inverse-Document-Frequency value for the given term in the specified document. If normalized is True, term frequency will be divided by the document length. """ tf = self.get_term_frequency(term, document) # Speeds up performance by avoiding extra calculations if tf != 0.0: # Add 1 to document frequency to prevent divide by 0 # (Laplacian Correction) df = 1 + self.get_document_frequency(term) n = 2 + len(self._documents) if normalized: tf /= self.get_document_length(document) return tf * math.log10(n / df) else: return 0.0 def get_total_tfidf(self, term, normalized=False): result = 0 for document in self._documents: result += self.get_tfidf(term, document, normalized) return result def generate_feature_matrix(self, mode='tfidf'): """ Returns a feature matrix in the form of a list of lists which represents the terms and documents in this Inverted Index using the tf-idf weighting by default. The term counts in each document can alternatively be used by specifying scheme='count'. A custom weighting function can also be passed which receives a term and document as parameters. The size of the matrix is equal to m x n where m is the number of documents and n is the number of terms. The list-of-lists format returned by this function can be very easily converted to a numpy matrix if required using the `np.as_matrix` method. """ result = [] for doc in self._documents: result.append(self.generate_document_vector(doc, mode)) return result def prune(self, min_value=None, max_value=None, use_percentile=False): n_documents = len(self._documents) garbage = [] for term in self.terms(): freq = self.get_document_frequency(term) if use_percentile: freq /= n_documents if min_value is not None and freq < min_value: garbage.append(term) if max_value is not None and freq > max_value: garbage.append(term) for term in garbage: del (self._terms[term]) def from_dict(self, data): self._documents = collections.Counter(data['documents']) self._terms = {} for term in data['terms']: self._terms[term] = collections.Counter(data['terms'][term]) def inverted_index(self): """ return a dict object of the inverted index with 'unsorted' terms and corresponding 'unsorted' postings :return: unsorted inverted index """ for terms in self._terms.keys(): self._inverted_index[terms] = {} self._inverted_index[terms][self.get_document_frequency(terms)] = self.get_documents(terms) return self._inverted_index def get_sorted_inverted_index(self): """ return an OrderedDict object of the inverted index with 'sorted' terms and corresponding 'sorted' postings :return: sorted inverted index """ for terms in self._terms.keys(): self._inverted_index[terms] = {} self._inverted_index[terms][self.get_document_frequency(terms)] = sorted(self.get_documents(terms)) #or: not sorted documents return collections.OrderedDict(sorted(self._inverted_index.items(), key=lambda t: t[0])) def get_sorted_inverted_index_VB(self): """ return an OrderedDict object of the inverted index with 'sorted' terms and corresponding 'sorted' postings :return: sorted inverted index """ for terms in self._terms.keys(): self._inverted_index[terms] = {} self._inverted_index[terms][self.get_document_frequency(terms)] = sorted(VB.VB(self.get_documents(terms))) #or: not sorted documents return collections.OrderedDict(sorted(self._inverted_index.items(), key=lambda t: t[0])) def get_sorted_posting_list(self, term): """ return a posting list of a single term (i.e. its own inverted index). :param term: term :return: posting list """ posting_list = {term: {}} posting_list[term][self.get_document_frequency(term)] = sorted(self.get_documents(term)) return posting_list def get_corpus_statistics(self, corpus): """ get the statistics about the corpus and index: 1, number of terms 2, number of documents 3*, number of tokens 4*, documents average length *: input "corpus" variable to get tokens_count and documents_average_len :param corpus: corpus :return: """ statistics = {} statistics['terms_count'] = len(self._terms) statistics['documents_count'] = len(self._documents) statistics['tokens_count'] = len(corpus) statistics['documents_average_len'] = int(statistics['tokens_count']/statistics['documents_count']) return statistics def write_index_to_disk(self, filepath): global output try: output = open(filepath, 'w+') output.write(str(self.get_sorted_inverted_index())) output.close() print ('Successfylly write to: ' + filepath) except: print ('An error occurs when writing to: ' + filepath) finally: output.close() def write_index_to_disk_VB(self, filepath): global output try: output = open(filepath, 'w+') output.write(str(self.get_sorted_inverted_index_VB())) output.close() print ('Successfylly write to: ' + filepath) except: print ('An error occurs when writing to: ' + filepath) finally: output.close() def merge(index_list): result = HashedIndex() for index in index_list: first_index = result second_index = index assert isinstance(second_index, HashedIndex) for term in second_index.terms(): if term in first_index._terms and term in second_index._terms: result._terms[term] = first_index._terms[term] + second_index._terms[term] elif term in second_index._terms: result._terms[term] = second_index._terms[term] else: raise ValueError("I dont know how the hell you managed to get here") result._documents = first_index._documents + second_index._documents return result
1c1c21233ee084db1004816005357985b6166e39
lior-ohana/TDD
/test_bubble_sort.py
877
3.734375
4
import unittest from bubble_sort import * class testbublesort(unittest.TestCase): #tests of the function name-bubbleSort(arr) def test_bubblesort1(self): arr1=[4,2,1,7] expected=[1,2,4,7] bubbleSort(arr1) self.assertEqual(expected,arr1) def test_bubblesort2(self): arr1 = ['w', 'a', 'v', 'o'] expected = ['a', 'o', 'v', 'w'] bubbleSort(arr1) self.assertEqual(expected, arr1) def test_bubblesort3(self): arr1 = [] expected = "No array insert" result=bubbleSort(arr1) self.assertEqual(expected, result) # If no elements are lost from the array def test_bubblesort4(self): arr1 = [4, 2, 1, 7] expected = len([1, 2, 4, 7]) bubbleSort(arr1) self.assertEqual(expected,len(arr1))
e0f974c5b42c9c4279fb0ddf8f7030860557ce32
imknott/python_work
/guest_book.py
441
4
4
filename = 'text_files/guestbook.txt' print("Welcome to the terminal, we ask that you please enter the following: \n") while True: name = input("What is your name? ") with open(filename, 'a') as file_object: file_object.write(f'{name} \n') #Find out if someone else would like to take the poll. repeat = input("Would you like to let another person respond? (yes/no)") if repeat == 'no': break
7d2fe2f51f6759be77661c2037c7eb4de4326375
rbrook22/otherOperators.py
/otherOperators.py
717
4.375
4
#File using other built in functions/operators print('I will be printing the numbers from range 1-11') for num in range(11): print(num) #Printing using range and start position print("I will be printing the numbers from range 1-11 starting at 4") for num in range(4,11): print(num) #Printing using range, start, and step position print("I'll print the numbers in range to 11, starting at 2, with a step size of 2") for num in range(2,11,2): print(num) #Using the min built in function print('This is the minimum age of someone in my family:') myList = [30, 33, 60, 62] print(min(myList)) #Using the max built in function print('This is the maximum age of someone in my family:') print(max(myList))
126fac3a8f4a79d89830c94e722f8f7082e816b5
Hiurge/reader
/app_scripts/reader_input_helpers.py
1,225
3.59375
4
import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import re # Reader input helpers: # - Turns reader input into one string text contents weather its a link contents or a pasted text. # Main function to import: get_input_text(contents) # Gets website contents and turns into list of paragraphs (sentences). def url_to_txt(url): html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html, 'html.parser') # "lxml") sentences = soup.find_all('p') sentences = [s.get_text() for s in sentences if s] return sentences # Decides if reader input string is a link or pure text to be taken as a contents. def url_or_text(input_string): if ' ' in input_string: return 'text' else: try: link = re.search("(?P<url>https?://[^\s]+)", input_string).group("url") return 'link' except: try: link = re.search("(?P<url>www.[^\s]+)", input_string).group("url") return 'link' except: return 'text' # Turns link contents into one string of text. def get_input_text(contents): if url_or_text(contents) == 'link': link = contents list_of_p = url_to_txt(link) full_text = ' '.join(list_of_p) return full_text else: full_text = contents return full_text
193df65365239df519e955afc7487f0435628433
Sjord/matasano
/set2/pkcs.py
182
3.5
4
def pad(data, length): pad_length = length - len(data) return data + pad_length * chr(pad_length) assert(pad("YELLOW SUBMARINE", 20) == "YELLOW SUBMARINE\x04\x04\x04\x04")
71876e59efb677256adbcd6ddd99bc483b3f6e30
ktemirbekovna/Moduli
/slide_2.2.py
379
3.890625
4
'''Спросите у пользователя 2 значения через input() а затем через модуль sys проверьте какое из 2-х значений занимает больше памяти.''' import sys a = input("Введите данные: ") b = input("Введите данные: ") print(sys.getsizeof(a)) print(sys.getsizeof(b))
20c9fb839eb1b852be94e76ea437c479b78f0415
hackett123/chess
/model/FEN.py
1,922
3.75
4
""" https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation Fen notation: slashes (/) divide rank information. Within each rank, a lowercase letter denotes black pieces and uppercase denotes white. A number represents a sequence of empty squares in the board. The last segment contains the final rank and extra metadata: - whose turn it is (w or b) - castling information - a dash (-) if nobody can castle, K and/or Q for white can castle king or queen side, and a k and/or q for black can castle king or queen side - en passant target square - a dash(-) if none available currently - halfmoves since last capture - # of full moves, which increases after black moves """ def read_fen(fen): board = [] rank_infos = fen.split('/') last_rank = rank_infos[-1].split(' ')[0] for rank_info in rank_infos: if rank_info == rank_infos[-1]: rank_info = last_rank rank = [] for c in rank_info: if str.isnumeric(c): for i in range(int(c)): rank.append(' ') else: rank.append(c) board.append(rank) return board def castle_info(fen): """ From a FEN, return a tuple of four boolean values denoting if white can castle king/queen side, black can castle king/queen side. """ board_metadata = read_board_metadata(fen) availablity = board_metadata[1] return 'K' in availablity, 'Q' in availablity, 'k' in availablity, 'q' in availablity def who_moves(fen): board_metadata = read_board_metadata(fen) return board_metadata[0] == 'w' def plies_since_capture(fen): board_metadata = read_board_metadata(fen) return int(board_metadata[3]) def move_number(fen): board_metadata = read_board_metadata(fen) return int(board_metadata[4]) def read_board_metadata(fen): return fen.split('/')[-1].split(' ')[1:]
ee45660537cff37311a6081eee6082209b998ea4
shukur-alom/Guess_Game
/Guess game.py
2,180
3.953125
4
#Guess Game print('\n\n --WELCOME TO GUESS GAME-- \n\n') my_hide=23 l=1 Tring_Time=10 try: while l<=100: User_input=int(input("Enter Your Guess: ")) if User_input <=5: print('Incrise the number more more,',end='') print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try') elif User_input==my_hide: print('Successful,',end='') print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try') break elif User_input<=15: print('Incrise the number more,',end='') print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try') elif User_input >=16 and User_input<=20: print('Incrise the number less,',end='') print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try') elif User_input >=21 and User_input<=22: print("Incrise the number a little more,",end='') print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try') elif User_input >=24 and User_input<=27: print("Decrease the number a little more,",end='') print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try') elif User_input >=28 and User_input<=35: print('Decrease the number less,',end='') print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try') elif User_input >=36 and User_input<=41: print('Decrease the number more,',end='') print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try') elif User_input >=42: print('Decrease the number more more,',end='') print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try') if l==Tring_Time: print('Game Over,',end='') print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try') break l+=1 except: print('\n\t\t\t\tInput a number\n')
6db878c7906c9fecbd5f7f9703f2108cbf626976
nasjp/atcoder
/arc065_a.py
962
3.8125
4
# Me def check(s): words = [ 'dream', 'dreamer', 'erase', 'eraser', ] while len(s) != 0: flag = False for w in words: if s[-len(w):] == w: s = s[:-len(w)] flag = True break if not flag: return 'NO' return 'YES' print(check(input())) # Other # これじゃだめだよな def check(s): s = s.replace('eraser', '') s = s.replace('erase', '') s = s.replace('dreamer', '') s = s.replace('dream', '') if len(s) != 0: return 'NO' return 'YES' print(check(input())) # Other S = input() while S: for x in ['dreamer', 'eraser', 'dream', 'erase']: if S.endswith(x): S = S[:-len(x)] break # for に else 節を書ける # for を抜けたあとに実行される else: print('NO') exit() print('YES')
b86322bff277a38ee7165c5637c72d781e9f6ee2
Bbenard/python_assesment
/ceaser/ceaser.py
678
4.34375
4
# Using the Python, # have the function CaesarCipher(str, num) take the str parameter and perform a Caesar Cipher num on it using the num parameter as the numing number. # A Caesar Cipher works by numing all letters in the string N places down in the alphabetical order (in this case N will be num). # Punctuation, spaces, and capitalization should remain intact. # For example if the string is "Caesar Cipher" and num is 2 the output should be "Ecguct Ekrjgt". # more on cipher visit http://practicalcryptography.com/ciphers/caesar-cipher/ # happy coding :-) def CaesarCipher(string, num): # Your code goes here print "Cipertext:", CaesarCipher("A Crazy fool Z", 1)
e026278e161656a19b0d93ec074cbb7d8b0c1a11
hirosato223/Exercism.io-Problems
/python/hangman/hangman.py
1,372
3.65625
4
STATUS_WIN = "win" STATUS_LOSE = "lose" STATUS_ONGOING = "ongoing" class Hangman(object): def __init__(self, word): self.remaining_guesses = 9 self.status = STATUS_ONGOING self.word = word self.maskedWord = '_' * len(word) self.previousGuesses = set() def guess(self, char): if self.remaining_guesses < 0: raise ValueError('No remaining guesses!') if self.status == STATUS_WIN: raise ValueError('You already won the game!') isSuccessfulGuess = False if char not in self.previousGuesses: self.previousGuesses.add(char) for i in range(len(self.word)): if char == self.word[i]: maskedWordCharList = list(self.maskedWord) maskedWordCharList[i] = char self.maskedWord = ''.join(maskedWordCharList) isSuccessfulGuess = True if self.maskedWord == self.word: self.status = STATUS_WIN if isSuccessfulGuess == False: self.remaining_guesses-= 1 if self.remaining_guesses < 0: self.status = STATUS_LOSE else: self.status = STATUS_ONGOING def get_masked_word(self): return self.maskedWord def get_status(self): return self.status
ca33de76147ae37ebd77a1f66b4d5bdabf1e94c9
nicholas-eden/python-algorithms
/sort/selection_sort.py
393
4.0625
4
from typing import List data = [3, 6, 12, 6, 7, 4, 23, 7, 2, 1, 7, 4, 3, 2, 5, 3, 1] def selection_sort(arr: List[int]): low: int for left in range(len(arr) - 1): low = left for right in range(left + 1, len(arr)): if arr[right] < arr[low]: low = right arr[left], arr[low] = arr[low], arr[left] selection_sort(data) print(data)