blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
bb2f29c69461f0a17af6c623f0203381cb7886dd
tianluyuan/project_euler
/euler_043.py
960
3.515625
4
""" The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. """ from utils import lazy_primes from itertools import islice, permutations PRIMES = list(islice(lazy_primes(), 7)) def divisible(perms): snum = ''.join(map(str, perms)) return all((int(snum[idx+1:idx+4]) % prime == 0 for idx, prime in enumerate(PRIMES))) def p43(): return sum(int(''.join(map(str, perm))) for perm in filter(divisible, permutations(range(10))))
d25eb8f84d9ba094a41d1ed219d28e7510f73bf8
priscilamarques/pythonmundo1
/primeiro_comando.py
900
4.125
4
nome = input('Qual seu nome? ') idade = input('Qual sua idade? ') peso = input('Qual seu peso? ') print(nome, idade, peso) ##Desafio 1 #Crie um script Python que leia o nome da pessoa e mostre uma mensagem de boas-vindas de acordo com o valor digitado. nome = input('Qual o seu nome? ') print(f'Olá, {nome}! Prazer em te conhecer!') ##Desafio 2 #Crie um script Python que leia o dia, mës e ano de nascimento de uma pessoa e mostre uma mensagem com a data formatada dia = input('Digite o dia do seu nascimento: ') mes = input('Digite o mês do seu nascimento: ') ano = input('Digite o ano do seu nascimento: ') print(f'Você nasceu no dia {dia} de {mes} do ano de {ano}. Correto?') ##Desafio 3 #Crie um script Python que leia dois números e tente mostrar a soma entre eles. n1 = int(input("Primeiro número: ")) n2 = int(input("Segundo número: ")) soma = n1 + n2 print(f'A soma é {soma}')
1a80f166a6e3d21ee04986431bbb82e8cbb9130c
LizaPersonal/personal_exercises
/Programiz/convertDecimal.py
274
4.34375
4
# Python program to convert decimal number into binary, octal and hexadecimal number system dec = int(input("Enter a decimal number: ")) print("The decimal value of", dec, "is:") print(bin(dec), "in binary.") print(oct(dec), "in octal.") print(hex(dec), "in hexadecimal.")
65bc40493cf99e44605bed86e83435557717322a
calfzhou/lazy-lab
/TestLca/FindLCA.py
4,530
3.796875
4
'''Find the least common ancestor (LCA) of two nodes in the bin-tree. ''' class Node: def __init__(self, val=None, left=None, right=None): self.val = val self.left = left self.right = right self.parent = None if self.left: self.left.parent = self if self.right: self.right.parent = self from sets import Set class Dir: (Undef, Left, Right) = range(3) def FindNodes(root, nodeSet, findAll=True): if not root or not nodeSet: return None pathDict = {} path = [] curr = root while curr or path: while curr: # Go down along left branch path.append((curr, Dir.Left)) if curr in nodeSet: pathDict[curr] = list(path) nodeSet.remove(curr) if not nodeSet or not findAll: return pathDict curr = curr.left (curr, dir) = path.pop() while dir == Dir.Right: # Back from right branch if not path: return pathDict (curr, dir) = path.pop() path.append((curr, Dir.Right)) # Trun to right from left curr = curr.right return pathDict # Compare two pathes def FindLCA_3(root, node1, node2): if not root or not node1 or not node2: return None if node1 is node2: return node1 nodeSet = Set([node1, node2]) pathDict = FindNodes(root, nodeSet) if nodeSet: return None path1 = [i[0] for i in pathDict[node1]] path2 = [i[0] for i in pathDict[node2]] lca = None minLen = min(len(path1), len(path2)) for i in xrange(minLen): if path1[i] is not path2[i]: break lca = path1[i] return lca def FindLCA_4(root, node1, node2): if not root or not node1 or not node2: return None if node1 is node2: return node1 nodeSet = Set([node1, node2]) pathDict = FindNodes(root, nodeSet, False) if not pathDict: return None path1 = [i[0] for i in pathDict.popitem()[1] if i[1] == Dir.Left] node = path1.pop() if FindNodes(node, nodeSet): return node while path1: node = path1.pop() if FindNodes(node.right, nodeSet): return node return None # Get two pathes by parent pointer, then compare def FindLCA_1(node1, node2): if not node1 or not node2: return None if node1 is node2: return node1 path1 = [] while node1: path1.append(node1) node1 = node1.parent path2 = [] while node2: path2.append(node2) node2 = node2.parent lca = None minLen = min(len(path1), len(path2)) for i in xrange(minLen): i = -1 - i if path1[i] is not path2[i]: break lca = path1[i] return lca # Get one path by parent pointer, then check... def FindLCA_2(node1, node2): if not node1 or not node2: return None if node1 is node2: return node1 ancestors1 = Set() while node1: ancestors1.add(node1) node1 = node1.parent while node2: if node2 in ancestors1: return node2 node2 = node2.parent return None from RandomSelector import RandomSelector def Ex1(): rs1 = RandomSelector() rs2 = RandomSelector() nk = Node('K') nj = Node('J', None, nk) ni = Node('I', None, nj) nh = Node('H', ni) nl = Node('L') ng = Node('G', nh, nl) nf = Node('F') nd = Node('D') nc = Node('C', nf, nd) ne = Node('E') nb = Node('B', ne, nc) na = Node('A', nb, ng) for i in xrange(ord('a'), ord('m')): node = eval('n%s' % chr(i)) rs1.AddItem(node) rs2.AddItem(node) return (na, rs1.SelectedItems()[0], rs2.SelectedItems()[0]) def Ex2(): rs1 = RandomSelector() rs2 = RandomSelector() nl = Node('L') ni = Node('I', nl) nf = Node('F', None, ni) nc = Node('C', None, nf) nj = Node('J') nk = Node('K') nh = Node('H', nj, nk) ng = Node('G') nd = Node('D', ng, nh) ne = Node('E') nb = Node('B', nd, ne) na = Node('A', nb, nc) for i in xrange(ord('a'), ord('m')): node = eval('n%s' % chr(i)) rs1.AddItem(node) rs2.AddItem(node) return (na, rs1.SelectedItems()[0], rs2.SelectedItems()[0]) def Test(root, node1, node2): n1 = FindLCA_1(node1, node2) n2 = FindLCA_2(node1, node2) n3 = FindLCA_3(root, node1, node2) n4 = FindLCA_4(root, node1, node2) print print 'LCA of', node1.val, 'and', node2.val, 'is:', print n1 and n1.val or 'None', n2 and n2.val or 'None', print n3 and n3.val or 'None', n4 and n4.val or 'None', if not n1 == n2 == n3 == n4: raise Exception('xxx') def Main(): (root, node1, node2) = Ex1() Test(root, node1, node2) (root, node1, node2) = Ex2() Test(root, node1, node2) if __name__ == '__main__': for i in xrange(10000): Main()
23dabe592b858fbb15e2f56fcf792234f753a561
burdenp/Spruly-AI
/Count.py
603
3.765625
4
import sys import os import string import Stock import collections #purpose is to count the given stocks and figure out how many #there are of each stock and then pass that onto format/weight #takes in a list of stocks, returns a dictionary #takes in the list of stocks and then finds the names #then compares names to the dictionary and if they are already in it #increase the count by one #list of stocks -> dictionary #dictionary is in the format #{StockName : count} def count(l): total = dict for key in l: if key in total: total.key =+ 11 else: total.key = 1 return total
10b19e94dc03410ecc9658ab560a8bfd8cd21aed
Achal08/LeetCode
/Leetcode August Challenge 2020/Leetcode Python/Vector clock.py
1,547
3.921875
4
#This function returns maximum of two vectors def vector_compare(vector1,vector2): vector = [max(value) for value in zip(vector1,vector2)] return vector P = {1:{}, 2:{}, 3:{}} # Inititalized an empty dictionary having 3 process inc = 0 e1 = int(input("Enter the no. of events in Process 1:")) e1 = [i for i in range(1, e1 + 1)] P[1] = {key: [inc + key, 0, 0] for key in e1} e2 = int(input("Enter the no. of events in Process 2:")) e2 = [i for i in range(1, e2 + 1)] P[2] = {key: [0, inc + key, 0] for key in e2} e3 = int(input("Enter the no. of events in Process 3:")) e3 = [i for i in range(1, e3 + 1)] P[3] = {key: [0, 0, inc + key] for key in e3} comm = int(input("Enter the no of communication lines:")) while inc < comm: sent = int(input("Enter the sending process number:")) recv = int(input("Enter the receiving process number:")) sent_event_no = int(input("Enter the sending event number:")) recv_event_no = int(input("Enter the receiving event number:")) if sent <= 3 and recv <= 3: print ("P{} --> P{}".format(sent,recv)) new_vector = vector_compare(P[sent][sent_event_no],P[recv][recv_event_no]) P[recv][recv_event_no] = new_vector print ("New vector value for P{} for event{} is: {}".format(recv,recv_event_no,P[recv][recv_event_no])) if (recv_event_no+1) in P[recv]: P[recv][recv_event_no+1] = vector_compare(P[recv][recv_event_no],P[recv][recv_event_no+1]) else: print ("Enter the sent/recv within existing process") inc += 1
d669cc9090752387ce27f6f05ca08fb846ad9d6f
theonaunheim/tutorials
/python_sessions/202_intro_for_devs_part_2/static/sample_program/program.py
514
4.1875
4
import sys def main(args): '''This program takes arguments, capitalizes them, and writes to stdout. Alternatively: import sys for arg in sys.argv[1:]: sys.stdout.write(arg.upper() + '\n') ''' try: for arg in args: upper_arg = arg.upper() sys.stdout.write(upper_arg + '\n') sys.exit(0) except Exception: sys.stderr.write('Error!\n') sys.exit(1) if __name__ == '__main__': main(sys.argv[1:])
4ec0fcd004621bc498e9ab60e8ef33d000d2e45c
wisebaldone/uq-secat
/scraper/course_description.py
3,860
3.640625
4
class CourseDescription(object): def __init__(self, raw, description, enrolled, responses, rate): self.course = raw[0]['COURSE_CD'] self.description = description.split(":")[0] self.year = raw[0]['SEMESTER_DESCR'].split(",")[1].strip() self.enrolled = int(enrolled) self.responses = int(responses) self.rate = rate if "Summer" in raw[0]['SEMESTER_DESCR']: self.semester = 3 else: self.semester = int(raw[0]['SEMESTER_DESCR'].split(" ")[1].split(",")[0]) index = 0 if index < len(raw) -1 and raw[index]['QUESTION_NAME'][1] == '1': self.q1 = QuestionDescription(raw[index:index+5]) index += 5 else: self.q1 = QuestionDescription() if index < len(raw) -1 and raw[index]['QUESTION_NAME'][1] == '2': self.q2 = QuestionDescription(raw[index:index+5]) index += 5 else: self.q2 = QuestionDescription() if index < len(raw) -1 and raw[index]['QUESTION_NAME'][1] == '3': self.q3 = QuestionDescription(raw[index:index+5]) index += 5 else: self.q3 = QuestionDescription() if index < len(raw) -1 and raw[index]['QUESTION_NAME'][1] == '4': self.q4 = QuestionDescription(raw[index:index+5]) index += 5 else: self.q4 = QuestionDescription() if index < len(raw) -1 and raw[index]['QUESTION_NAME'][1] == '5': self.q5 = QuestionDescription(raw[index:index+5]) index += 5 else: self.q5 = QuestionDescription() if index < len(raw) -1 and raw[index]['QUESTION_NAME'][1] == '6': self.q6 = QuestionDescription(raw[index:index+5]) index += 5 else: self.q6 = QuestionDescription() if index < len(raw) -1 and raw[index]['QUESTION_NAME'][1] == '7': self.q7 = QuestionDescription(raw[index:index+5]) index += 5 else: self.q7 = QuestionDescription() if index < len(raw) -1 and raw[index]['QUESTION_NAME'][1] == '8': self.q8 = QuestionDescription(raw[index:index+5]) index += 5 else: self.q8 = QuestionDescription() return def __str__(self): return str(self.__dict__) def __repr__(self): return str(self.__dict__) class QuestionDescription(object): def __init__(self, raw=None): if raw is None: self.description = "Missing" self.strong_agree = {'value': 0, 'total': 0,'percent': 0.00} self.agree = {'value': 0, 'total': 0,'percent': 0.00} self.neutral = {'value': 0, 'total': 0,'percent': 0.00} self.disagree = {'value': 0, 'total': 0,'percent': 0.00} self.strong_disagree = {'value': 0, 'total': 0,'percent': 0.00} else: self.description = raw[0]['QUESTION_NAME'].split(":")[1].strip() self.strong_agree = {'value': raw[0]['VALUE'], 'total': raw[0]['ANSWERED_QUESTION'], 'percent': round(raw[0]['PERCENT_ANSWER'], 2)} self.agree = {'value': raw[1]['VALUE'], 'total': raw[1]['ANSWERED_QUESTION'], 'percent': round(raw[1]['PERCENT_ANSWER'], 2)} self.neutral = {'value': raw[2]['VALUE'], 'total': raw[2]['ANSWERED_QUESTION'], 'percent': round(raw[2]['PERCENT_ANSWER'], 2)} self.disagree = {'value': raw[3]['VALUE'], 'total': raw[3]['ANSWERED_QUESTION'], 'percent': round(raw[3]['PERCENT_ANSWER'], 2)} self.strong_disagree = {'value': raw[4]['VALUE'], 'total': raw[4]['ANSWERED_QUESTION'], 'percent': round(raw[4]['PERCENT_ANSWER'], 2)} return def __str__(self): return str(self.__dict__) def __repr__(self): return str(self.__dict__)
0b478ec04d673548e10182876df527015a83ad6e
yuehhan/Interviewprep_and_projects
/singlenumber.py
1,053
3.796875
4
<<<<<<< HEAD # Given an array of numbers nums, in which exactly two elements # appear only once and all the other elements appear exactly twice. # Find the two elements that appear only once. def singleNumber(nums): nums.sort() count = 0 while len(nums) > 2: if nums[count] == nums[count+1]: nums.remove(nums[count]) nums.remove(nums[count]) else: count+= 1 return nums print(singleNumber([2,5,5,2,3,7,7,1])) ======= # Given an array of numbers nums, in which exactly two elements # appear only once and all the other elements appear exactly twice. # Find the two elements that appear only once. class Solution: def singleNumber(self, nums: List[int]) -> List[int]: nums.sort() count = 0 while len(nums) > 2: if nums[count] == nums[count+1]: nums.remove(nums[count]) nums.remove(nums[count]) else: count+= 1 return nums >>>>>>> 2cb9e49e883400a268731c5612315df24d5dccef
fb50c0a88132b8fa5428119474662e43d0984a10
adambatchelor2/python
/codewars_spinWords.py
259
3.625
4
strTest = 'i love horses' def loop_through(inStr): word_list = inStr.split() for x,word in enumerate(word_list): if len(word) >= 5: word_list[x] = word[::-1] return ' '.join(map(str, word_list)) print(loop_through(strTest))
1f368f5080bf05577a451fe4491e21740000c535
Phantom586/My_Codes
/Coding/Python_Prgs/Lists.py
1,326
4.25
4
if __name__ == '__main__': # Inputting The no. of operations user wants to perform. N = int(input()) # list to store the Elements after performing operations on it. mine = [] # for loop for N operations. for i in range(N): # List to Store the operation and their required values. com = list(input().split()) # now matching the type of operation the user wants to perform and working according to that. if com[0] == 'insert': # Inserting the Element stored in list(com[2]) at index(com[1]). mine.insert(int(com[1]),int(com[2])) elif com[0] == 'print': print(mine) elif com[0] == 'remove': # Converting the String into an Integer value. n1 = int(com[1]) # Deleting the First Occurrence of the Integer(com[1]). mine.pop(mine.index(n1)) elif com[0] == 'append': # Converting the String into an Integer value. n1 = int(com[1]) mine.append(n1) elif com[0] == 'sort': # Sorting the List. mine.sort() elif com[0] == 'pop': # Removing the last element of the list. mine.pop() elif com[0] == 'reverse': # Reversing the List. mine.reverse()
81b9142c87bc6080803d55b7953ee4859c4896e5
marcelogabrielcn/ExerciciosPython
/exe025.py
149
3.96875
4
nome = input('Digite o nome de uma pessoa: ') if 'Silva' in nome: print('Tem Silva nesse nome!') else: print('Não tem Silva nesse nome!!!')
88058341aff15fa2b61f4d6ef9096d150a2dd25b
shubham-dixit-au7/test
/coding-challenges/Week02/Day 4_30-01-2020/calc_upper_lower.py
601
4.1875
4
#Question- Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. #Answer- def countUpperCase(string): upper= 0 for i in string: if(i.isupper()): upper=upper+1 return upper def countLowerCase(string): lower= 0 for i in string: if(i.islower()): lower=lower+1 return lower string = input("Enter a String -> ") upper = countUpperCase(string) lower = countLowerCase(string) print("Total no. of uppercase characters present in string are " , upper) print("Total no. of lowercase characters present in string are " , lower)
e87884a14ef14bd227b5750faeba244d110a87e6
fernandorssa/CeV_Python_Exercises
/m_115.py
1,298
3.8125
4
def menu(): print('-' * 30) print(f'{"Menu principal":^30}') print('-' * 30) print('1 - Ver pessoas cadastradas') print('2 - Cadastrar nova pessoa') print('3 - Sair do sistema') print('4 - Ver o menu principal') print('5 - Limpar cadastro') print('-' * 30) def cadastro(): dicionario = {} cont = 1 while True: try: option = int(input('Sua opção: ')) if option == 1: abertura = open('d_115.txt', 'r') print(abertura.read()) elif option == 2: abertura = open('d_115.txt', 'a') nome = str(input('Digite o nome da pessoa: ')) idade = int(input('Digite a idade da pessoa: ')) dicionario[f'{cont}'] = nome, idade abertura.write(f'{nome}, {idade} anos\n') cont += 1 elif option == 3: print('Volte sempre!') abertura.close() break elif option == 4: menu() elif option == 5: abertura = open('d_115.txt', 'w') else: print('Opção inválida!') except ValueError: print('É preciso digitar um número inteiro!')
4eb33738e2e5ffecfe818f8d9700d91141232332
ndonyemark/passlock
/program.py
5,396
4.0625
4
from credentials import Credentials from users import Users import time import secrets import string def create_user(username, password): new_user = Users(username, password) return new_user def save_users(user): user.save_user() def del_user(user): user.delete_user() def find_user(username): return Users.find_user(username) def check_user(username): return Users.check_user_exist(username) def display_user(): return Users.display_user() def login(username, password): login = Users.login(username, password) if login != False: return Users.login(username, password) def create_credential(username, account_name, account_password): new_credentials = Credentials(username, account_name, account_password) return new_credentials def save_credentials(credential): credential.save_credentials() def del_credentials(credential): credential.delete_credentials() def find_credentials(account_name): return Credentials.find_by_account_name(account_name) def check_credential(account_name): return Credentials.check_credential_existence(account_name) def display_credentials(): return Credentials.display_credentials() def main(): name = input("Enter your name: ") print(f"Welcome {name}. What would you like to do?") while True: print("""Use these short codes to navigate your way through: 1 => create account 2 => login 3 => list current users 4 => exit""") short_code = int(input()) if short_code == 1: username = input("Enter your username: ") password = input("Enter your password: ") print("Wait while we create your account...") time.sleep(2) save_users(create_user(username, password)) print(f"""your account has been created successfully {username} you can now login""") elif short_code == 2: username = input("Enter your username: ") password = input("Enter your password: ") if login(username, password) == None: print("""Are you sure you have an account? if not please create an account...Ciao""") else: login(username, password) while True: print("""Kindly use these codes to navigate through the menu items: sc => show credentials cc => create credentials pm => go back to previous menu(exit credentials)""") short_code = input().lower() if short_code == "sc": if display_credentials(): print("Getting credentials...") time.sleep(3) for credential in display_credentials(): print(f""" username => {credential.username} account_name => {credential.account_name} password => {credential.account_password}""") else: print("no credentials found...:(") elif short_code == "cc": username = input("please Enter your username: ") account_name = input("Enter the website name: ") print("""How would you like your password? 1 => AutoGenerated 2 => Choose your password""") choice = int(input()) if choice == 1: alphabet = string.ascii_letters + string.digits account_password = ''.join(secrets.choice(alphabet) for i in range(20)) print(f"Autogenerated password => {account_password}") elif choice == 2: account_password = input("Enter your password of choice: ") print("please wait while we create your credentials...") time.sleep(3) save_credentials(create_credential(username, account_name, account_password)) print(f"""the following credentials have been added: user_name => {username} account_name => {account_name} account_password => {account_password}""") elif short_code == "pm": break else: print("Kindly use the short codes provided") elif short_code == 3: print("Wait while we get you the users...") time.sleep(2) if display_user(): for user in display_user(): print(f"{user.username}") else: print("found no users. add one?;)") elif short_code == 4: print(f"It was nice meeting you {name}...Bye") break else: print(f"kindly use the short codes provided {name}") if __name__ == "__main__": main()
a0c560608e73da59d2c92846325f64590942d466
Erick-Paguay/perick885
/funlist2.py
228
3.75
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 30 12:14:13 2020 @author: SEDMQ """ def listacreada(n): lista1=[] for i in range (n): lista1.append(i) return lista1 print(listacreada(11))
1f21520bd6d2f88a21521c94ac26f4944c51340a
stnorbi/AlienInvasion
/characters/ammo.py
785
3.625
4
import pygame from pygame.sprite import Sprite class Bullet(Sprite): def __init__(self,ai_settings,screen,ship): super(Bullet,self).__init__() self.screen=screen #set the place of the bullet self.rect=pygame.Rect(0,0,ai_settings.bullet_w, ai_settings.bullet_h) self.rect.centerx=ship.rect.centerx self.rect.top=ship.rect.top self.y=float(self.rect.y) #set the colour of the bullet self.color=ai_settings.bullet_c #set the speed to the bullet self.speed_fact=ai_settings.bullet_speed # inherited function from Sprite def update(self): self.y -= self.speed_fact self.rect.y=self.y def setBullet(self): pygame.draw.rect(self.screen,self.color,self.rect)
5cf266d879dd16bff182a2575d2c1177236b0599
Rivarrl/leetcode_python
/leetcode/601-900/884.py
757
3.65625
4
# -*- coding: utf-8 -*- # ====================================== # @File : 884.py # @Time : 2019/12/30 23:54 # @Author : Rivarrl # ====================================== from algorithm_utils import * class Solution: """ [884. 两句话中的不常见单词](https://leetcode-cn.com/problems/uncommon-words-from-two-sentences/) """ @timeit def uncommonFromSentences(self, A: str, B: str) -> List[str]: d = {} for e in A.split(' ') + B.split(' '): d[e] = d.get(e, 0) + 1 return [e for e in d if d[e] == 1] if __name__ == '__main__': a = Solution() a.uncommonFromSentences(A = "this apple is sweet", B = "this apple is sour") a.uncommonFromSentences(A = "apple apple", B = "banana")
8d094ed01c4a79f54671b9eac78eb6be516a26f8
Maryam-Rafindadi/Python-Basics
/Python _Basics_Exercise1.py
1,082
4.09375
4
#format method name = 'Maryam Rafindadi' print('Hello, {0}'.format(name)) #grade of student print("student scores") mark = int(input()) score = mark if score >= 70 and score <=100: print ("Your Grade is A") elif score >= 60 and score <= 69: print("Your Grade is B") elif score >= 50 and score <= 59: print ("Your Grade is C") elif score >= 40 and score <= 49: print ("Your Grade is D") else: print ("Your Grade is F") #All even numbers between 1 and 100 using: while and for loop number = 1 while (number <= 100): if (number % 2) == 0: print (number) number + 1 #function argument def my_function(fname, lname): print(fname + " " + lname) my_function("Maryam", "Rafindadi") #program to add two matrix using nested loop A = [[4,5], [6,7]] B = [[1,2], [3,4]] result = [[0,0], [0,0]] for i in range (len(A)): for j in range (len(B)): result[i][j]=A[i][j] + B[i][j] for r in result: print(r)
123686a86e70efcc576cc7092ca24f2d5cfb4bf0
nickpostma/monopoly2
/player.py
776
3.734375
4
import unittest class test(unittest.TestCase): def test_player_class_callable(self): self.assertIsNotNone(Player(id = 0)) def test_player_should_have_id(self): self.assertIsNotNone(Player(id = 0).id) def test_player_should_have_money(self): self.assertIsNotNone(Player(id = 0).Money) def test_when_given_money_increase_money(self): p = Player() originalMoney = p.Money p.GiveMoney(200) self.assertTrue(p.Money > originalMoney) pass class Player(): def __init__(self, id, money = 0): self.id = id self.Money = money def GiveMoney(self, money): self.Money += money pass if __name__ == '__main__': unittest.main(verbosity = 2)
44b83244efb11dd25665199a5a173ce0d28a1dcb
dan2014/Data-Structures
/linked_lists_practice/stack_list.py
949
4.125
4
class Stack: def __init__(self): self.list = [] def __repr__(self): if(self.len() == 0): return "The stack is empty" else: for i in reversed(self.list): print(f"{i}") return "" def push(self, item): self.list.append(item) def pop(self): if( self.len() > 0 ): self.list.pop() else: print( "Cannot pop an element off the stack when the stack is empty" ) return def len(self): return len(self.list) if __name__ == "__main__": test_stack = Stack() test_stack.push(3) test_stack.push(4) test_stack.push(5) print(test_stack) test_stack.pop() print(test_stack) test_stack.push(6) print(test_stack) test_stack.pop() print(test_stack) test_stack.pop() print(test_stack) test_stack.pop() print(test_stack) test_stack.pop()
de83031c9023cb89bed3112eb4ae4e5f0f44d9c1
marpe163/Myne-Sweeper
/TileBoard.py
2,515
3.75
4
import sys from Tile import Tile from random import randint class TileBoard: def __init__(self, width, height): self.board = [[Tile() for j in range(height)] for i in range(width)] self.width = width self.height = height self.isInitialized = False def getTile(self, xIdx, yIdx): if (not xIdx < self.width) and (not yIdx < self.height): print "Index Out of Range" else: return self.board[xIdx][yIdx] def incrementBombCountForAdjacentTiles(self, xIdx, yIdx): for x in range(max([0, (xIdx - 1)]), min([(xIdx + 2), self.width])): for y in range(max([0, (yIdx - 1)]), min([(yIdx + 2), self.height])): #We consider a bomb to be adjacent to itself self.getTile(x,y).incementNumberOfAdjacentBombsByOne() def initializeBoard(self, numberOfBombs): if numberOfBombs > (self.height * self.width): print "Too many bombs" elif numberOfBombs == 0: print "No Bombs!?" else: for i in range(numberOfBombs): while True: randXIdx = randint(0, self.width - 1) randYIdx = randint(0, self.height - 1) currentTile = self.getTile(randXIdx, randYIdx) currentTileIsBomb = self.getTile(randXIdx, randYIdx).isBomb if not currentTileIsBomb: currentTile.setIsBomb(True) self.incrementBombCountForAdjacentTiles(randXIdx, randYIdx) break #For Debugging Purposes def printBoard(self): for it in range(self.height): for jt in range(self.width): currentTileIsBomb = self.getTile(jt, it).isBomb printChar = 'B' if currentTileIsBomb else 'X' sys.stdout.write(printChar) sys.stdout.write('\n') sys.stdout.write('\n') for it in range(self.height): for jt in range(self.width): printChar = (str)(self.getTile(jt,it).numberOfAdjacentBombs) sys.stdout.write(printChar) sys.stdout.write('\n') def printEachTile(self,fcn): for it in range(self.height): for jt in range(self.width): bool1 = "True" if fcn(self.getTile(jt, it)) else "False" sys.stdout.write(bool1) sys.stdout.write('\n') sys.stdout.write('\n')
e5279fa30cd5f4dfc4a5a196f34d48d2e44d85b7
kolligj70/Agnesi-Fractals
/SupportFiles/genSpiral.py
1,739
3.53125
4
#! /usr/bin/python3 """ Generate/plot a spiral. If output of image is desired, include any string as a command line argument. """ import sys import matplotlib.pyplot as plt import numpy as np #### Spiral Parameters #### xCenter = 2.0 yCenter = 4.0 nPts = 300 # Reverse values for inward spiral radius0 = 2.0 # Initial radius radiusF = 5.0 # Final radius nTurns = 3 # Number of turns theta0_deg = 45.0 # Initial rotation angle, degrees ########################### if len(sys.argv) == 2: outFlag = True else: outFlag = False fig = plt.figure(facecolor='lightgrey') ax = fig.add_subplot(111) ax.patch.set_facecolor('black') ax.set_aspect('equal') ax.grid(True, which='both') # Insert X and Y axes ax.axhline(y=0, color='w') ax.axvline(x=0, color='w') # Remove #'s to suppress tick labels #ax.set_xticklabels([]) #ax.set_yticklabels([]) # Radius growth rate across total number of turns b = (radiusF-radius0)/(2.0*np.pi*nTurns) # Convert initial rotation angle to radians theta0 = theta0_deg*np.pi/180.0 # Determine final rotation angle across total number of turns thetaF = 2.0*np.pi*nTurns + theta0 # Array of incremental angles t = np.arange(theta0, thetaF, (thetaF-theta0)/nPts, dtype=float) # (x,y) coordinates of individual points on the spiral x = (radius0+b*t)*np.cos(t)+xCenter y = (radius0+b*t)*np.sin(t)+yCenter print('len(x) = ', len(x)) print('xmin = {0:8.2f} xmax = {1:8.2f}'.format(min(x), max(x))) print('ymin = {0:8.2f} ymax = {1:8.2f}'.format(min(y), max(y))) # s is marker size ax.scatter(x, y, marker='o', s=4.0, color='red') # Conditionally output image if outFlag == True: fig.savefig('genSpiral.png', facecolor='lightgrey', format='png') plt.show()
3b1e9c51752c5d9a33751a0ca3185b39195f7ba4
l3r4nd/Machine-Learning-Notes
/Computer-Vision-Tasks/Paint_Brush.py
1,074
3.734375
4
image = np.zeros((512, 512, 3), np.uint8) drawing = False ix, iy = -1, -1 def draw_circle(event, x, y, flags, param): global ix, iy, drawing #Check to see if the Left mouse button is pressed. if event == cv2.EVENT_LBUTTONDOWN: #enable drawing drawing = True ix, iy = x, y #If mouse is moved while the left mouse button is pressed start drawing elif event == cv2.EVENT_MOUSEMOVE: if drawing: cv2.circle(image, (x,y), 10, (0, 255, 0), -1) #If mouse button is released stop drawing elif event == cv2.EVENT_LBUTTONUP: drawing = False #create a window to draw (Note: you draw on 'blank' named window to see the drawing on 'image' named window) cv2.namedWindow('blank') #create a callback function cv2.setMouseCallback('blank', draw_circle) while True: #display the blank image. cv2.imshow('image', image) key = cv2.waitKey(1) & 0xFF #If 'c' key is pressed at any point in time then break if key == ord('c'): break cv2.destroyAllWindows()
86158d0a53373234e8579e78da89c10761ef8136
vicentegarridoj/Python-Scripts
/FindIPs.py
322
3.515625
4
import re #import Regular Expression Python module ipAddRegex = re.compile(r'\d+\S\d+\S\d+\S\d+') #This is the pattern that I want to match ipList = ''' paste your text which contains IP addresses ''' #Paste the values inside triple-quote syntax ipAddRegex.findall(ipList) #Run this function passing the ipList argument
fbf072dec6015be81d70c32118682e4a1351a8d0
FisicaComputacionalOtono2018/20180829-tareapythoniintial-jordetm5
/productovectorial.py
404
3.96875
4
#Jorge Dettle Meza Dominguez #29/08/2018 #producto cruz c1=0 c2=0 c3=0 a= [] for i in range (0,3): a.append(int(input("dame el valor de la componente de A: "))) b = [] for i in range (0,3): b.append(int(input("dame el valor de la componente de B: "))) c1= (a[1]*b[2]-a[2]*b[1]) c2= (a[2]*b[0]-a[0]*b[2]) c3 = (a[0]*b[1]-a[1]*b[0]) print("el producto vectorial de A y B es: (",c1,c2,c3,")")
72d11b218f1fbd4bc5de98277a79f7964bba91c5
matheusribeirog/cognitive
/aula03/01_revisaopython_numpy_pandas.py
2,023
3.8125
4
# pip install pandas, numpy, ipython, scikit-learn, matplotlib #Sobre Spyder # ctrl + P # F5 / F9 import pandas as pd import numpy as np from IPython.display import Image, display # Funcao # https://www.w3schools.com/python/python_functions.asp def soma_funcao(x, y): return x + y resultado_soma_funcao = soma_funcao(1, 2) print('resultado_soma_funcao: ', resultado_soma_funcao) # Lambda # https://www.w3schools.com/python/python_lambda.asp soma_lambda = lambda x, y: x + y resultado_soma_lambda = soma_lambda(3, 4) print('resultado_soma_lambda: ',resultado_soma_lambda) # Iteracao for item in [1, 2, 3]: print('iteracao: ', item) # Listas Python lista1 = [1, 2 ,3] resultado1 = [item+1 for item in lista1] print('resultado1: ', resultado1) resultado2 = list(map((lambda item: item + 1), lista1)) print('resultado2: ', resultado2) display(Image('numpy_array_pandas_dataframe.jpeg', width=600, height=600)) # Numpy # https://www.w3schools.com/python/numpy_intro.asp ndarray_v = np.array([4, 5, 6]) print('numpy adrray_v: ', ndarray_v) print(type(ndarray_v)) print(ndarray_v.__class__) ndarray_m = np.array([[4, 5, 6], [7, 8, 9]]) print('numpy adrray_m: ', ndarray_m) # https://www.w3schools.com/python/pandas/default.asp # https://www.w3schools.com/python/pandas/pandas_series.asp numeros = [10, 11, 12] serie_n = pd.Series(numeros, index = ["x", "y", "z"]) print('serie_n: ', serie_n) print('serie_n["x"]: ', serie_n["x"]) dic_numeros = {"x": 13, "y":14, "z":15} serie_d = pd.Series(dic_numeros) print('serie_d["x"]: ', serie_d["x"]) # Series entao resumidamente sao colunas dic_dados = {"a": [1, 2], "b": [3, 4], "c": [5, 6] } df_d = pd.DataFrame(dic_dados) print('df_d: ', df_d) # Dados coluna print('type(df_d["a"]): ', type(df_d["a"])) print('df_d["a"]: ', df_d["a"]) # Aplicando transformacao multiplica_2 = lambda x: x*2 df_d["nova_coluna_b"] = df_d["b"].apply(multiplica_2) print('df_d["nova_coluna_b"]: ', df_d["nova_coluna_b"]) # Leitura de arquivo dataset = pd.read_csv('Case_cobranca.csv')
13a703f47484d8b9d7008b097b599bac058dbd1b
sarthakturkar75/python_practicals
/string.py
1,744
3.828125
4
str = "i aM IrOnmAn" str0 = "i\taM\tIrOnmAn" str1 = "ṅśṅḍḥñṭḍ" str2 = "8696590494" str3 = "1.5 3.6" print(str.capitalize()) print(str.casefold()) print(str.center(20, "-")) print(str.count("n")) print(str.count("nm")) print(str1.encode("ascii", "ignore")) print(str1.encode("ascii", "xmlcharrefreplace")) print(str1.encode("ascii", "backslashreplace")) print(str.endswith("an")) print(str.endswith("An")) print(str0.expandtabs(tabsize=15)) print(str.find("nm")) print("{} and{}".format("Apple", " Banana")) print("{1} and{0}".format(" Apple", "Banana")) print("{lunch} and{dinner}".format(lunch="Peas", dinner=" Beans")) lunch = {"Food": "Pizza", "Drink": "Wine"} print("Lunch: {Food},{Drink}".format_map(lunch)) print(str.index("m")) print(str.isalnum()) print(str1.isalnum()) print(str2.isalnum()) print(str.isalpha()) print(str1.isalpha()) print(str2.isalpha()) print(str.isdecimal()) print(str1.isdecimal()) print(str2.isdecimal()) print(str.isdigit()) print(str1.isdigit()) print(str2.isdigit()) print(str3.isdigit()) print(str.isidentifier()) print(str1.isidentifier()) print(str2.isidentifier()) print(str3.isidentifier()) print(str.islower()) print(str.isupper()) print(str.isnumeric()) print(str1.isnumeric()) print(str2.isnumeric()) print(str3.isnumeric()) print(str.isprintable()) print(str0.isprintable()) print(str.isspace()) print(str0.isspace()) print(str.istitle()) a = "-" print(a.join("123")) print(str.ljust(16, "_")) print(str.lower()) print(str.upper()) print(str.lstrip(), "!") frm = "SecretCode" to = "8203670540" trans_table = str.maketrans(frm, to) sec_code = "SecretCode".translate(trans_table) print(sec_code) print(str.partition('-'))
b21569732e0458a10a883dfb33a4ebefdfb08547
anvandev/TMS_HW
/HW/task_1_5/task_4_5.py
1,125
3.859375
4
""" Закрепить знания по работе с циклами. Составить список чисел Фибоначчи содержащий 15 элементов. (Подсказка: Числа Фибоначчи - последовательность, в которой первые два числа равны либо 1 и 1, а каждое последующее число равно сумме двух предыдущих чисел. Пример: 1, 1, 2, 3, 5, 8, 13, 21, 34... ) """ # using for loop (new) f_list = [] for i in range(15): if i < 2: f_list.append(1) else: f_list.append(f_list[i-2] + f_list[i-1]) print(f_list) # using while loop l_fib = [] i = 0 while len(l_fib) < 15: while len(l_fib) < 2: l_fib.append(1) next_num = l_fib[i] + l_fib[i+1] l_fib.append(next_num) i += 1 print(l_fib) # using for loop (old) l_fib = [] i = 0 if len(l_fib) == 0: l_fib.append(1) l_fib.append(1) for n in l_fib: next_num = l_fib[i] + l_fib[i+1] l_fib.append(next_num) i += 1 if len(l_fib) == 15: break print(l_fib)
c78faf447251f861aae637cf1e98c7719e451eff
lil-mars/pythonProblems
/binaryVSsimple/search.py
519
3.859375
4
#Comparing binary search vs fast search # 9780333 # for number in range(0, 10000000000): # print(number) # if 10000000 == number: # break searched_number = 10000000 max_bound = 10000000000 minBound = 0 while max_bound: mid_number = (max_bound + minBound) // 2 print(mid_number) if (searched_number == mid_number): break else: if searched_number < mid_number: max_bound = mid_number - 1 else: minBound = mid_number + 1
c8fa461f4e9f904148d9a9669c70fe0a06b93338
liuxiaoliang/L
/common/util.py
531
3.5625
4
#! /usr/bin/env python # # Copyright (c) <2014> <leon.max.liew@gmail.com> # """common utilities """ __author__ = "xiaoliang liu" import sys import time class Timing(object): """computer used time by a process unit: milliseconds """ def __init__(self): self.cur_time = 0 def start(self): self.cur_time = int(time.time()*1000) def report(self): return int(time.time()*1000) - self.cur_time if __name__ == '__main__': t = Timing() t.start() time.sleep(2) print t.report()
f55640b5845ea7434d5c2a81585eabe0a275af45
feliperfdev/100daysofcode-1
/Introdução ao Python/week1/day5/listas_aninhadas.py
1,207
4.28125
4
''' Listas Aninhadas -> Linguagens como C/Java possuem uma estrutura de dados chamada array: - Unidimensionais (arrays/vetores) - Multidimensionais (matrizes) -> Em Python temos as listas ''' print('\n') # Exemplo: lista = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(type(lista)) print(lista) print('\n'); print(lista[0]) # Acessa a primeira lista print('\n'); print(lista[0][1]) # Acessa o elemento '2' da primeira lista print(lista[1][2]) print(lista[2][0]); print('\n') [[print(valor, end=' ') for valor in listas] for listas in lista]; print('\n') [[print(elemento*2, end=' ') for elemento in listas_] for listas_ in lista] #========================================================================================================== print('\n') matriz = [[num for num in range(1, 4)] for value in range(1, 4)] print(matriz) print('\n'); import numpy as np matriz_array = np.array(matriz) print(matriz_array) #========================================================================================================== print('\n') velha = [['x' if numero % 2 == 0 else 'O' for numero in range(1, 4)] for valor in range(1, 4)] jogo_da_velha = np.array(velha) print(jogo_da_velha)
551a0ed539a451f04c298ac69b34101978a873d0
rabin-nyaundi/micropilot-entry-challenge
/rabin-nyaundi/count_zeros.py
376
3.828125
4
def count_zero(arr): result_arr = [] for i in arr: if i == 0: result_arr.append(i) return result_arr result = count_zero([1,2,3,0,0,0,8]) assert len(result) == 3 print("Test 1 passed") result = count_zero([0,0,0,0,0,0,]) assert len(result) == 6 print("Test 2 passed") result = count_zero([]) assert len(result) == 0 print("Test 3 passed")
de4e52cd88e17dd2493d6f9d1b49227b2b1b1aa9
KodeBlog/Python-3
/11-while-loop/app.py
602
3.765625
4
i = 0 while i < 5: print(i) i += 1 import random condition = True while condition: n = random.randint(1,7) m = random.randint(1,10) if (n > m): print (f'The winning number is {n}, it was blessed by {m}') condition = False else: print(f'The losing number is {n}, it was jinxed by {m}') i = 0 while i < 15: i += 1 if (i % 2 == 0): continue print(i) while i < 15: i += 1 if (i == 5): break print(i) i = 0 while i < 5: i += 1 print(i) else: print('Loop execution has completed successfully')
79b7ffad85187d12d4819b1c7e54a02916abe49d
jaramosperez/Pythonizando
/Ejercicios Operadores y expresiones/Ejercicio 01.py
580
4.1875
4
# Realiza un programa que lea 2 números por teclado y determine los siguientes aspectos # (es suficiene con mostrar True o False): # # Si los dos números son iguales # Si los dos números son diferentes # Si el primero es mayor que el segundo # Si el segundo es mayor o igual que el primero a = float(input('Ingrese un número: ')) b = float(input('Ingrese otro número: ')) print('Los numeros son iguales: ', a == b) print('Los números son diferentes', a != b) print('El primero es mayor que el segundo', a > b) print('El segundo numero es mayor o igual al primero', b >= a)
648852ebb2e4442d003e3e796bb3133a71b2ec51
RyujiOdaJP/python_practice
/ryuji.oda19/week02/c30_int_list.py
243
3.578125
4
def int_list(L): if len(L) == 0: return False else: try: X = [isinstance(L[i],int) for i in range(len(L))] print(X) return all(X) except TypeError: return False
a3ca79690bf400fa772db768f0d5976326890ec5
ledzerck/devf
/operadoresDeAsignacion.py
334
3.984375
4
## Operadores de asignación # = asigna un valor # += suma el valor de la izquierda con el de la derecha # -= resta # *= multiplica x = y = z = 5 print(x) print(y) print(z) print("---------") a,b,c = 1,2,"Jose" print(a) print(b) print(c) print("---------") x = x + 10 print(x) x += 10 print(x) x -= 10 print(x) x *= 10 print(x)
660f64753d2f14317e04c41cf7e5a115b6e93820
Giantpizzahead/comp-programming
/Project Euler/p17.py
1,332
3.609375
4
digits = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] tens = ['N/A', 'N/A', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] def get_words(x, is_first = False): words = [] if x == 0 and not is_first: # Blank number pass elif x >= 10**6: words += get_words(x // (10**6)) words += ['million'] words += get_words(x % (10**6)) elif x >= 10**3: words += get_words(x // (10**3)) words += ['thousand'] words += get_words(x % (10**3)) elif x >= 10**2: words += [digits[x // (10**2)]] words += ['hundred'] if x % (10**2) != 0: words += ['and'] words += get_words(x % (10**2)) elif x >= 20: if x % 10 == 0: words += [tens[x // 10]] else: words += [tens[x // 10] + '-' + digits[x % 10]] else: words += [digits[x]] return words def get_word(x): return ' '.join(get_words(x, True)) cnt = 0 for i in range(1, 1001): word = get_word(i) curr_cnt = len(list(filter(lambda x: x not in ' -', word))) cnt += curr_cnt print(i, curr_cnt, word) print(cnt)
35b09e6edb632af056589186afd23ddaf1765e56
herbetyp/Exercicios_Python
/Mundo 1 - Fundamentos/ex025-procurando uma string dentro de outra.py
134
3.59375
4
nome = str(input("\nDigite seu nome completo: ")).strip() print('Seu nome tem a palavra "Silva" ? {} '.format('Silva' in nome))
b4cc403055f523ec8a7c68d4e9e98bead648aa7c
egar-garcia/AIND_Project3_Adversarial_Search
/opening_book.py
2,569
3.5625
4
import random import pickle from collections import defaultdict, Counter from isolation import Isolation NUM_ROUNDS = 1000000 #NUM_ROUNDS = 50000 # This is to get within the limits of the review tool DEPTH = 6 DATA_FILE = 'data.pickle' def build_table(num_rounds=NUM_ROUNDS): """ Creates the table of opening moves, returns a dictionary with the game state as the key and the best found move as value. """ # Creates a dictionary for counting purposes, # it has a game state as a key, and the values are other dictionaries. # This inner dictionaries have actions (taken in a particular state) as keys # and total reward (#won-matches - #lost-matches) as values book = defaultdict(Counter) for _ in range(num_rounds): state = Isolation() # Initial state (a blank board) build_tree(state, book) return {k: max(v, key=v.get) for k, v in book.items()} def build_tree(state, book, depth=DEPTH): """ Recursive function to explore the game states up to a given depth, and create the respective entries in the opening book. """ # If the depth is 0 (i.e. the maximum depth to explore has been reached) # then performing a simulation for the rest of the game if depth <= 0 or state.terminal_test(): return -simulate(state) # Taking a random action from the current state action = random.choice(state.actions()) # Recursively calling this function to explore actions in deeper levels # reward would be 1 if the next player wins or -1 if it loses (i.e. the current player wins) reward = build_tree(state.result(action), book, depth - 1) # Updating the total reward of the taken action, # the more wins the higher the total reward book[state][action] += reward # Returns the negative of the reward, # in order to adjust the result to the caller's perspective (i.e the other player's) return -reward def simulate(state): """ Performs a simulation of the rest of a game, by choosing random moves. """ # The current player player_id = state.player() # Performing random moves till the game ends while not state.terminal_test(): state = state.result(random.choice(state.actions())) # Returns 1 if the current player wins, or -1 if it loses return -1 if state.utility(player_id) < 0 else 1 # Creating the opening book (dictionary), # and storing it into the specified pickle file opening_book = build_table() with open(DATA_FILE, 'wb') as f: pickle.dump(opening_book, f)
59230f05474f2261674592377dc887ff89fdbb87
KunyiLiu/algorithm_problems
/kangli/leetcode/hash_table/find_common_characters.py
783
3.515625
4
class Solution: def commonChars(self, A): d, delete = {}, [] res = [] for c in A[0]: d[c] = 1 if c not in d else d[c]+1 for word in A[1:]: for k, v in d.items(): if k not in list(word): delete.append(k) continue elif word.count(k) < v: d[k] = word.count(k) for c in delete: if c in d: del d[c] for k, v in d.items(): while v > 0: res.append(k) v -= 1 return res ''' 83 / 83 test cases passed. Status: Accepted Runtime: 96 ms Memory Usage: 13.1 MB Related Topics: Array, Hash Table Similar Questions: Intersection of Two Arrays II '''
55cfcefef97312fa2cd309f8cdc071128ed4f478
yewei600/Python
/Crack the code interview/Minesweeper.py
846
4.21875
4
''' algorithm to place the bombs placing bombs: card shuffling algorithm? how to count number of boms neighboring a cell? when click on a blank cell, algorithm to expand other blank cells ''' import random class board: dim=7 numBombs=3 bombList=[None]*numBombs def __init__(self): print "let's play Minesweeper!" for i in range (0,self.dim): for j in range(0,self.dim): print "?", print #determine the location of bombs for i in range (0,self.numBombs): self.bombList[i]=random.randrange(0,self.dim*self.dim+1) print self.bombList[i] def is_bomb(self,num): # def makePlay(self,row,column): # if not isBomb()
ad132f338c5b967896b9ea97ece06501e73e2c7b
hyun98/Project_AlgoStudy
/study/2021.03-2021.04/team1/Week04/BOJ_11057_박시형.py
393
3.609375
4
N = int(input()) if N >= 3: arr = [i for i in range(10,0,-1)] for i in range(N-2): arr_temp = [] temp = [] for idx in range(len(arr)): arr_temp.append(arr[idx:]) for j in range(len(arr_temp)): temp.append(sum(arr_temp[j])) arr = temp[:] # print(arr) print(sum(arr)) elif N == 2: print(55) else: print(10)
eeea939622fa90b7f325f0d48101a90f1f26e639
anilhoon/penta_python_study
/lotto.py
696
3.90625
4
import random # Create lotto List lotto=[] # 1 ~ 45 number insert for number in range(1,46): lotto.append(number) print(lotto) # choice 6 numbers # for 문 보다는 while 문을....len(lotto2) = 6일 때 까지.. # Service number 때문에 7번 실 lotto2=[] print(len(lotto2)) #for num in range(6): # number for num in range(7): # service number choice=random.randint(1,45) print(choice) print("first : " ,lotto2) # 중복 제거 if choice in lotto2: print(choice) print("double") # 재수 없게 중복 되면? choice=random.randint(1,45) lotto2.append(choice) print(lotto2) print("==========================")
6d64467772d28087b6c0bb4d89b8b544f2c247f8
twumm/upcoming-movie-trailers
/entertainment_center.py
1,838
3.734375
4
'''This file makes a request to themoviedb.org's api and fetches the following movie details: title, storyline/overview, poster image url, youtube trailer url and the release date ''' import media import fresh_tomatoes import requests # access the api and convert it to a json file MOVIE_LIST = requests.get("https://api.themoviedb.org/3/movie/upcoming?" + "api_key=03531cf9267cbb1ee25c65670346beca&page=1") MOVIE_DATA = MOVIE_LIST.json() MOVIE_TRAILER_BASE_URL = "https://api.themoviedb.org/3/movie/" MOVIE_TRAILER_END_URL = "/videos?api_key=03531cf9267cbb1ee25c65670346beca" POSTER_BASE_URL = "https://image.tmdb.org/t/p/w500" YOUTUBE_TRAILER_BASE_URL = "https://www.youtube.com/watch?v=" MOVIES = [] for item in MOVIE_DATA["results"][:10]: # Loop through the response received from api.themoviedb.org and pick out # the title, overview and movie image movie_title = item["title"] movie_storyline = item["overview"][:200].encode('utf8') + "...read more" poster_image = POSTER_BASE_URL + item["poster_path"] release_date = item["release_date"] # Get the video feed for each movie item and assign the video URL to # trailer_youtube movie_id = str(item["id"]) movie_trailer_list = requests.get(MOVIE_TRAILER_BASE_URL + movie_id + MOVIE_TRAILER_END_URL) movie_trailer_data = movie_trailer_list.json() trailer_youtube = YOUTUBE_TRAILER_BASE_URL \ + movie_trailer_data["results"][0]["key"] # Create an instance of the Movie() class using the items movie_instance = media.Movie(movie_title, movie_storyline, poster_image, trailer_youtube, release_date) # Append the movies to the movies[] array MOVIES.append(movie_instance) # The open_movies_page displays the movies in the browser fresh_tomatoes.open_movies_page(MOVIES)
7edec0e891bd01a2d0223d6aaf70bc58b934efb7
Ting0718/Leetcode
/String/344_reverse_string.py
682
3.9375
4
'''use python in-built function''' class Solution: def reverseString(self, s: List[str]) -> None: s.reverse() '''iteratively swap left and right''' class Solution: def reverseString(self, s: List[str]) -> None: left, right = 0, len(s) - 1 while left < right: tmp = s[left] s[left] = s[right] s[right] = tmp left += 1 right -= 1 '''recursively swap left and right''' class Solution: def reverseString(self, s: List[str]) -> None: def helper(l, r): if l < r: s[l], s[r] = s[r], s[l] helper(l + 1, r - 1) helper(0, len(s)-1)
f163b27f07f5a4a4e34804a91b7222e5047a0eb8
patela29/OOD
/primenumbers.py
470
4.125
4
#Jeffrey Creighton #Updated by Anand Patel #Looks through each number within the range and prints it if prime. def primenumbers(i): for j in range(2, i+1): if checkPrime(j): #find out if j is prime print j #Checks to see if a number is prime. Returns false if any number less than sqrt+1 divides evenly, true otherwise. def checkPrime(k): for i in range(2, int(k**.5 + 1)): if i < k: if (k % i) == 0: return False return True primenumbers(input("Enter a number: "))
c4613f6ad8a571db354d428c78a9f5441cdc62a0
tyriem/PY
/Intro To Python/41 - GUI - Radio Button SelectGet - TMRM.py
1,047
4.25
4
### AUTHOR: TMRM ### PROJECT: INTRO TO PYTHON - GUI: Radio Buttons Select & Get ### VER: 1.0 ### DATE: 06-06-2020 ##################### ### GUIs ### ##################### ### OBJECTIVE ### #Code a basic GUI for user # ### OBJECTIVE ### ##Declare CALLs & DEFs from tkinter import* #First, we import the ttk library from tkinter.ttk import * ##Declare/Input VALs & STRINGs ##CALCs ##OUTPUTs window = Tk() window.title("PYTHON APP: GUI - RADIO BUTTONS SELECT & GET") #First, we issue the selected = IntVar() selected = IntVar() rad1 = Radiobutton(window,text='First', value=1, variable=selected) rad2 = Radiobutton(window,text='Second', value=2, variable=selected) rad3 = Radiobutton(window,text='Third', value=3, variable=selected) #Second, we define a function for clicked def clicked(): print(selected.get()) btn = Button(window, text="Click Me", command=clicked) rad1.grid(column=0, row=0) rad2.grid(column=1, row=0) rad3.grid(column=2, row=0) btn.grid(column=3, row=0) window.mainloop()
164fd89684bec7fd144308b525eeec393a6dd404
awedz/uni
/python/dp/singleton/sngtn.py
313
3.703125
4
class Singleton: __myList = [] def GetInstance(self): return self.__myList def Insert(self,data): if self.__myList is None: self.__myList = [] self.__myList.append(data) a1 = Singleton() a1.Insert( 1 ) a2 = Singleton() a2.Insert( 2 ) print( a1.GetInstance() )
478d287b8a64a188fec68fb70106fd8ecdc324f6
Auclown/algo-challenge-py
/010_alternating-sums/attempt.py
304
3.765625
4
def alternating_sums(people): team_one = 0 team_two = 0 for i in range(len(people)): if i % 2 == 0: team_one += people[i] else: team_two += people[i] return [team_one, team_two] # Test print(alternating_sums([50, 60, 60, 45, 70])) # [180, 105]
decf6342b0fc75bcf2fa73486341e8c0e8b7be5b
jasmin-guven/labile_HD_exchange
/pdb2DF.py
2,736
3.515625
4
import numpy as np import pandas as pd import csv import os.path def is_path(filepath): is_path = os.path.isdir(filepath) while is_path == False: filepath = input('Invalid directory %s. Please enter again: ' %(filepath)) is_path = os.path.isdir(filepath) return filepath def is_file(filepath, filename): is_file = os.path.isfile(str(filepath)+str(filename)) while is_file == False: filename = input('Invalid filename %s. Please enter again: ' %(filename)) is_file = os.path.isfile(str(filepath)+str(filename)) return filename def is_int(input_string, input_var): input_valid = False while input_valid == False: try: input_var = int(input_var) input_valid = True except ValueError: print('Did not understand the command. Try again.') input_var = input(input_string) return input_var def pdb2DF(): pdb_path = input('Please enter the full path to the folder containing the PDB file: ') pdb_path = is_path(pdb_path) file = input('Please enter the name of the PDB file: ') file = is_file(pdb_path,file) fullpath = str(pdb_path)+str(file) cutoff_string = 'MODEL' # Open file f = open(fullpath, 'r') # Read in all lines from file to a list lines = f.readlines() number_of_lines = 0 cutoff_line = 0 # Loop over lines in file to get location of cutoff for line in lines: # Get number of lines in file number_of_lines += 1 if cutoff_string in line: cutoff_line = number_of_lines # Create an array containing only x and y data rows = lines[cutoff_line:number_of_lines] split_rows = np.char.split(rows) output = str(pdb_path)+'LYS_data_clean.csv' is_anti = input('Is the file a protein or antibody? \n 1. Antibody \n 2. Protein \nPlease enter: ') is_anti = is_int('Is the file a protein or antibody? \n 1. Antibody \n 2. Protein \nPlease enter: ', is_anti) if is_anti == 1: columns = [['TYPE', 'ATOM_NR', 'ELEMENT', 'AA_NAME','CHAIN','AA_NR', 'X', 'Y', 'Z', 'ONE', 'ZERO', 'ATOM_NAME']] with open(output,"w+", newline='') as my_csv: csvWriter = csv.writer(my_csv, delimiter=',') csvWriter.writerows(columns) csvWriter.writerows(split_rows) elif is_anti == 2: columns = [['TYPE', 'ATOM_NR', 'ELEMENT', 'AA_NAME','AA_NR','X', 'Y', 'Z', 'ONE', 'ZERO', 'ATOM_NAME']] with open(output,"w+", newline='') as my_csv: csvWriter = csv.writer(my_csv, delimiter=',') csvWriter.writerows(columns) csvWriter.writerows(split_rows) return output, fullpath, is_anti
b7d6e97569e0b2e85b8c741e62ed0daee1651e27
Jojtek/allPythonLabsAndProject
/Zad4.py
559
4.125
4
def insertsort(arr): for i in range(1, len(arr)): temp = arr[i] j = i - 1 while j >= 0 and temp < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = temp import random arr=[] for i in range (20): arr.append(random.randrange(1, 101, 1)) sor = arr.copy() insertsort(sor) print("\n unsorted array is:") for i in range(len(arr)): print(str(arr[i]) + ", ", end = '') print("\n sorted array is:") for i in range(len(sor)): print(str(sor[i]) + ", ", end = '') #finished
b0dc54bc68d6b374c419e3edacbf5b7ebde7378d
luosch/leetcode
/python/Kth Smallest Element in a BST.py
896
3.71875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def dfs(self, root, answer): if root: self.dfs(root.left, answer) answer.append(root.val) self.dfs(root.right, answer) def kthSmallest_rec(self, root, k): answer = [] self.dfs(root, answer) return answer[k - 1] def kthSmallest(self, root, k): stack = [] node = root while stack or node: if node: stack.append(node) node = node.left else: node = stack.pop() if k > 1: k -= 1 else: return node.val node = node.right
6275d78014687aa63aa75e5b323f98cc9f98395b
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/mrnkud004/question4.py
488
4.0625
4
"""finding palindromic primes kennedy muranda 9/5/2014""" import sys sys.setrecursionlimit (30000) #define function to check if number is palindrome def palind(c): if len(c)<2: return True else: if c[0]==c[-1]: return palind(c[1:-1]) else: return False #check for prime numbers def is_prime(N): N = eval(input("Enter the starting point N:\n")) M = eval(input("Enter the ending point M:\n"))
41ef03cadff0fab488de1475d1b4b1a22012b30b
neequole/my-python-programming-exercises
/unsorted_solutions/question68.py
663
3.9375
4
""" Question 68: Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. Example: If the following n is given as input to the program: 100 Then, the output of the program should be: 0,35,70 Hints: Use yield to produce the next value in generator. In case of input data being supplied to the question, it should be assumed to be a console input. """ def foo(num): for x in range(0, num+1): if x % 5 == 0 and x % 7 == 0: yield x inp = int(input("Enter a number: ")) out = [str(i) for i in foo(inp)] print(", ".join(out))
01984a3f1be19145930da2615763d9859168f41e
ppak9/intern
/5주차/3.py
227
3.90625
4
# 2,3 은 하나에 # 2.py는 조건문에 대한 기본문을 작성하는 것 # 논리연산자 and or numbers =[1,2,3,4,5,6,7,8,9,10] for n in numbers: if n%2==0 or n%3==0: print(n) else: continue
09eafe3a8b6f5079f9495da3c819d55bcdb7234e
zhangda7/leetcode
/solution/_101_symmitric_tree.py
2,133
4.3125
4
# -*- coding:utf-8 -*- ''' Created on 2015/8/24 @author: dazhang Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following is not: 1 / \ 2 2 \ \ 3 3 Note: Bonus points if you could solve it both recursively and iteratively. ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root == None: return True nodes = [] nodes.append(root) while(len(nodes) > 0): newNodes = [] retVal = [] while(len(nodes) > 0): node = nodes.pop(0) if node == None: continue if node.left != None: newNodes.append(node.left) retVal.append(node.left.val) else: newNodes.append(None) retVal.append(None) if node.right != None: newNodes.append(node.right) retVal.append(node.right.val) else: newNodes.append(None) retVal.append(None) #detemine retVal whether is symmtric mid = len(retVal) / 2 print retVal for i in range(mid): if retVal[i] != retVal[-1 - i]: return False nodes = newNodes return True if __name__ == '__main__': root = TreeNode(0) l1 = TreeNode(1) l2 = TreeNode(1) l3 = TreeNode(2) l4 = TreeNode(2) l5 = TreeNode(5) l6 = TreeNode(6) root.left = l1 root.right = l2 l1.right = l3 l2.right = l4 #l2.right = None #l5.left = l6 s = Solution() print(s.isSymmetric(root)) pass
12f9519b6d6304712969380b708455915ff171f1
nikhil-nakhate/search-engine-udacity
/test.py
576
3.875
4
''' Created on 21 Apr 2013 @author: Nikhil ''' def find_element(p, t): i = 0 for e in p: if (e == t): print i return i i = i+1 return -1 find_element([1,2,3], 3) def find_element_in(p, t): if (t in p): print p.index(t) return p.index(t) else: print -1 return -1 find_element_in([1,2,3,4,5,5],0) def union(l1, l2): for b in l2: if (b not in l1): l1.append(b) return l1,l2; print(union([1,2,3], [2,4,6]))
737e967a5037124beae855b3f6ddcc44e39bfaa5
andreaumac/Python
/Classe.py
3,174
4
4
print(type(1)) print(type([])) print(type(())) print(type({})) #instancia da class list(objeto) l = [1,2,3] print('----------------------------') class Dog(object): #construtor def __init__(self, raca): self.raca = raca #public #self.__raca = raca #privado rex = Dog('vira-lata') print(rex.raca) print('----------------------------') class Dog(object): especie = 'mamifero' #construtor def __init__(self, raca): self.raca = raca #public #self.__raca = raca #privado rex = Dog('vira-lata') print(rex.raca) print(rex.especie) print('----------------------------') class Circulo(object): pi = 3.14 # se nao passar nenhum valor, vale 1 def __init__(self, raio=1): self._raio = raio def area(self): return self._raio * self._raio * Circulo.pi #caso os valores sejam privados def setraio(self, raio): self._raio = raio def getraio(self): return self._raio circulo = Circulo(raio=2) print(circulo.area()) circulo.setraio(8) print(circulo.getraio()) circulo2 = Circulo(6) print(circulo2.area()) print('----------------------------') #Herança #Classe PAI class Animal(object): def __init__(self): print('Animal Criado') def sou(self): print('Animal') def comer(self): print('comendo') #Classe FILHO class Dog(Animal): def __init__(self): #super().__init__() pode usar esse tbm Animal.__init__(self) #ou esse print('Cachorro criado') def sou(self): print('Dog') def latir(self): print('Au au') d = Dog() d.sou() d.comer() d.latir() print('----------------------------') #Metodos Especiais class Livro(object): def __init__(self, titulo, autor, paginas): print('Livro criado') self.titulo = titulo self.autor = autor self.paginas = paginas def __str__(self): return 'titulo: %s, autor: %s, paginas: %s' %(self.titulo, self.autor, self.paginas) def __len__(self): return self.paginas def __del__(self): print('livro destruido') livro = Livro('Python','Luciano', 799) print(livro) print(len(livro)) del livro print('----------------------------') #Atividade '''crie uma classe Retangulo com os parametros inteiro base e inteiro altura. E os metodos Perimetro e area''' class Retangulo(object): def __init__(self, base=0, altura=0): self._base = base self._altura = altura def setBase(self,base): self._base def setAltura(self,altura): self._altura def getBase(self): return self._base def getAltura(self): return self._altura def Perimetro(self): return 2*self._base + 2* self._altura def Area(self): return self._base*self._altura try: b = float(input('Base: ')) except ValueError: print('Valor Invalido') try: h = float(input('Altura: ')) except ValueError: print('Valor Invalido') retangulo = Retangulo(b,h) print('Perimetro: %.2f' %retangulo.Perimetro()) print('Area: %.2f' %retangulo.Area()) print('----------------------------') '''Trabalho usando heranças - alunos e materia'''
43784a9c4b2a701899a93f251919b608b53c6972
yhxddd/python
/lian.py
614
4.0625
4
''' print("--------------文字小游戏----------------") temp = input("猜猜我想的是数字几(3次机会哦!):") guss = int(temp) if guss == 8: print("对咯!") else: for content in range(0,3): content = 3 temp = input("猜错了 重新输入吧!") guss = int(temp) if guss == 8: print("对咯!") else: if guss > 8: print("大了!") else: print("小了!") content -= 1 print("游戏结束") ''' x = 6 y = 22 a = x if x > y else y print(a)
97730b7e22c7eb4b8dfd256d7a67325d225fe05e
Aasthaengg/IBMdataset
/Python_codes/p03815/s962131495.py
106
3.71875
4
x=int(input()) ans=(x//11)*2 if x%11==0: pass elif 0<x%11<=6: ans+=1 else: ans+=2 print(ans)
1d3753de01b4f7e96b64ee6faf91c4ace26ba78f
paik11012/Algorithm
/lecture/day02/day02_3.py
1,194
3.640625
4
# def bin(n,key): # l = 1 # r = n # cnt = 0 # while 1: # mid = int((l+r)/2) # cnt +=1 # if mid == key: # return cnt # break # elif import sys sys.stdin = open('sample_3.txt','r') def binary_search(a, key): # 400개가 든 리스트 a start, end = 0, len(a) # len(a) = 400 a_cnt = 0 # 몇 번 나누어지는지 세서 나눌 것 while start <= end: # start와 end가 같을 때까지 middle = (start + end) // 2 # 2로 나눈 몫을 반영 if middle == key: a_cnt += 1 return a_cnt elif a[middle] > key: # 키가 중간값보다 오른쪽에 위치하면 end = middle - 1 # end를 하나 전 값 가져오기 a_cnt += 1 else: start = middle + 1 # 키가 중간값보다 왼쪽에 위치하면 a_cnt += 1 total = int(input()) for tot in range(1, total+1): book, A, B = map(int, input().split()) a = [] # 1부터 A까지 리스트 for k in range(1, A+1): a.append(k) b = [] # 1부터 B까지 리스트 for k in range(1, B+1): b.append(k) print(binary_search(a, A))
d79ce832b1d924d57248270e04890e5a3137d56a
rafsie/scripts
/articles_counter.py
297
3.828125
4
from string import punctuation s = input('Wprowadź jakiś tekst: \n') for c in punctuation: s = s.replace(c, '') s = s.lower() L = s.split() words = ['a', 'an', 'the'] print() for item in words: article = L.count(item) print("Słowo '{}' występuje {} razy.".format(item, article))
b4ad7b1f331b92371c30be5b028b0c45dbcb9bf8
Devinlomax/Ch3-Programming-Assignment
/#6.py
1,032
4.09375
4
#6. A software company sells a package that retails for $99. Quantity discounts are given according to the following: 10 – 19 (10%), 20 - 49 (20%), 50 – 99 (30%), and 100 or more (40%). Write a program that asks the user to enter the number of packages purchased. The program should then display the amount of the discount (if any) and the total amount of the purchase after the discount retailprice = 99 quantity = int(input("Quantity purchased:")) if quantity <10: discount = 0 elif 10 <= quantity and quantity < 20: discount = 0.1 elif 20 <= quantity and quantity < 50: discount = 0.2 elif 50 <= quantity and quantity < 100: discount = 0.3 else:discount = 0.4 subtotal = retailprice * quantity totaldiscount = subtotal * discount total = subtotal - totaldiscount print(format("\nSubtotal:", "<10s") , "$", format(subtotal, ",.2f")) print(format("Discount:", "<10s") , "$", format(totaldiscount, ",.2f")) print(format("total:", "<10s") , "$", format(total, ",.2f"))
2ff7c89b6ca6e95208850dfa77fe7630ad31610c
avldokuchaev/testProject
/body_square.py
2,211
4.0625
4
# Рассчет площади поверхности тела def square_body_chemotherapy(weight_float, height_float): square_body = 0.0167 * weight_float ** 0.5 * height_float ** 0.5 square_body_result = round(square_body, 2) return square_body_result height = float(input("Введите рост в сантиметрах: ")) weight = float(input("Введите вес в килограммах: ")) schema_therapy = input("Введите название схемы (AC): ") reduction_doze = int(input("Если нужна редукция дозы, введите цифру процентов, иначе введите \"0\": ")) res = square_body_chemotherapy(height, weight) if schema_therapy.upper() == "AC" or schema_therapy.upper() == "АС" and reduction_doze == 0: doksorubicin = 60 ciklophosphamid = 600 doksorubicin_doza = doksorubicin * res ciklophosphamid_doza = ciklophosphamid * res print(f"Площадь поверхности тела = {str(res)} квадратных метров") print(f"Необходимая доза Доксорубицина = {str(round(doksorubicin_doza))} мг") print(f"Необходимая доза Циклофосфамида = {str(round(ciklophosphamid_doza))} мг") elif schema_therapy.upper() == "AC" or schema_therapy.upper() == "АС" and reduction_doze != 0: doksorubicin = 60 ciklophosphamid = 600 doksorubicin_doza = (doksorubicin * res) - ((doksorubicin * res) * (reduction_doze / 100)) ciklophosphamid_doza = (ciklophosphamid * res) - ((ciklophosphamid * res) * (reduction_doze / 100)) print(f"Площадь поверхности тела = {str(res)} квадратных метров") print( f"Необходимая доза Доксорубицина (редуцированная на {reduction_doze}%) = {str(round(doksorubicin_doza))} мг") print( f"Необходимая доза Циклофосфамида (редуцированная на {reduction_doze}%) = {str(round(ciklophosphamid_doza))}" f" мг") else: print("Вы ввели не ту схему!") k = input("Нажмите Enter для выхода! ")
3b15767988f1d958fc456f7966f425f93deb9017
juliehub/python-practice
/string/anagrams.py
591
4.0625
4
""" Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams. Any characters can be deleted from either of the strings. """ from collections import Counter import math import os import random import re import sys # Complete the makeAnagram function below. def makeAnagram(a, b): ct_a = Counter(a) ct_b = Counter(b) ct_a.subtract(ct_b) return sum(abs(i) for i in ct_a.values()) if __name__ == '__main__': a="cde" b="abc" res = makeAnagram(a, b) print(res)
75fdae0a570ddea8c84fad8f6f52d0bccd77729b
subodhss23/python_small_problems
/hard_problems/oddly_or_evenly_positioned.py
1,096
3.96875
4
'''Create a function that returns the characters from a list or string r on odd or even positions, depending on the specifier s. The specifier will be "odd" for items on odd positions(1,3,5,....) and "even" for items on even positions(2,4,6,...)''' def char_at_pos(r, s): if type(r) == list: new_lst = [] if s == 'even': for i in range(len(r)): if i % 2 != 0: new_lst.append(r[i]) elif s == 'odd': for i in range(len(r)): if i % 2 == 0: new_lst.append(r[i]) return new_lst elif type(r) == str: new_str = "" if s == 'even': for i in range(len(r)): if i % 2 != 0: new_str+=r[i] elif s == 'odd': for i in range(len(r)): if i % 2 == 0: new_str+=r[i] return new_str print(char_at_pos([2, 4, 6, 8, 10], "even")) print(char_at_pos("EDABIT", "odd")) print(char_at_pos(["A", "R", "B", "I", "T","R", "A", "R", "I", "L", "Y"], "odd"))
96ed932274c368a1bd7ba93afed1e8546575a38a
ekdeguzm/space_invaders
/space_invaders.py
10,280
4.0625
4
# Space Invaders # Python 3.9.5 on Mac import turtle import os import math import random import platform # Set up the screen screen = turtle.Screen() screen.bgcolor("black") screen.title("Space Invaders") screen.setup(width = 700, height = 700) screen.tracer(0) # shuts off all the screen updates # Register the shapes turtle.register_shape("alien2.gif") turtle.register_shape("small_ship.gif") # Draw outer border outer_pen = turtle.Turtle() outer_pen.color("blue") # Spell gray not grey? test outer_pen.pensize(55) # test outer_pen.speed(0) x = outer_pen.xcor = -325 y = outer_pen.ycor = -325 outer_pen.penup() outer_pen.goto(x,y) outer_pen.pendown() for s in range (2): # why 2? outer_pen.forward(650) # test this outer_pen.left(90) # test outer_pen.forward(650) # test outer_pen.left(90) # Draw title title = turtle.Turtle() title.speed(0) title.shape("square") title.color("white") title.penup() title.hideturtle() title.goto(0,310) title.write("Space Invaders", align="center", font=("courier", 30, "normal")) # Draw innder border border_pen = turtle.Turtle() border_pen.speed(0) border_pen.color("white") border_pen.penup() border_pen.setposition(-300,-300) border_pen.pendown() #border_pen.speed(6) border_pen.pensize(3) for side in range(4): border_pen.fd(600) border_pen.lt(90) border_pen.hideturtle() # Set the score to 0 score = 0 # Draw score score_pen = turtle.Turtle() score_pen.speed() score_pen.hideturtle() score_pen.speed(0) score_pen.color("white") score_pen.penup() score_pen.setposition(-290, 280) scorestring = "Score: {}".format(score) score_pen.write(scorestring, False, align="left", font=("Areial", 14, "normal")) score_pen.hideturtle() # Create the player turtle player = turtle.Turtle() player.setheading(90) player.color("light blue") player.shape("small_ship.gif") player.penup() player.speed(1) player.setposition(0, -265) player.setheading(90) player.speed = 0 # Create enemies # Choose a number of enemies number_of_enemies = 30 # Create an empty list of enemies enemies = [] # list b/c [] # Add enemies to list (actual turtle objects) for i in range(number_of_enemies): print(range(number_of_enemies)) # Create the enemy enemies.append(turtle.Turtle()) enemy_start_x = -225 enemy_start_y = 250 enemy_number = 0 for enemy in enemies: enemy.color("red") enemy.shape("alien2.gif") enemy.penup() enemy.speed(0) enemy.shapesize(50, 50) x = enemy_start_x + (50 * enemy_number) y = enemy_start_y enemy.setposition(x,y) # Update the enemy number enemy_number += 1 if enemy_number == 10: enemy_start_y -= 50 enemy_number = 0 enemyspeed = 0.15 # Create the player's bullet bullet = turtle.Turtle() bullet.color("yellow") bullet.shape("square") bullet.penup() bullet.speed(0) bullet.setheading(90) bullet.shapesize(0.18, .75) bullet.hideturtle() y = player.ycor() bullet.sety(y) # Create the player's bullet bullet2 = turtle.Turtle() bullet2.color("red") bullet2.shape("square") bullet2.penup() bullet2.speed(0) bullet2.setheading(90) bullet2.shapesize(0.18, .75) bullet2.hideturtle() y = player.ycor() bullet2.sety(y) bulletspeed = 5 # Define bullet state, which controls bullet behavior # ready - ready to fire # fire - bullet is firing bulletstate = "ready" bulletstate2 = "ready" spacestate = "1" # Create function for horizontal movement def move_left(): player.speed = -2 def move_right(): player.speed = 2 def move_player(): x = player.xcor() x += player.speed if x < -270: x = -270 if x > 270: x = 270 player.setx(x) def fire_bullet(): # Declare bulletstate as a global if it needs changed global bulletstate global bulletstate2 global spacestate if spacestate == "1" and bulletstate == "ready": play_sound("3_12.WAV") bulletstate = "fire" # Move the bullet to just above the player x = player.xcor() y = player.ycor()+5 bullet.setposition(x, y) bullet.showturtle() spacestate == "2" if bulletstate == "fire": bulletstate2 == "ready" else: play_sound("3_12.WAV") bulletstate2 = "fire" # Move the bullet to just above the player x = player.xcor() y = player.ycor()+5 bullet2.setposition(x, y) bullet2.showturtle() spacestate == "1" def isCollision(t1, t2): # Going to return True or False distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(), 2) + math.pow(t1.ycor()-t2.ycor(),2)) if distance < 20: return True else: return False def play_sound(sound_file, time = 0): # Time is in sec, how many seconds before time file repeats?, if no time, it doesn't repeat os.system("afplay {}&".format(sound_file)) # Repeat sound if time > 0: turtle.ontimer(lambda: play_sound(sound_file, time), t=int(time * 1000)) # Create keyboard bindings screen.listen() screen.onkeypress(move_left, "Left") screen.onkeypress(move_right, "Right") # make sure to capitaize the "R" screen.onkeypress(move_left, "a") screen.onkeypress(move_right, "d") screen.onkeypress(fire_bullet, "space") # lower case spelled # Play background music play_sound("bgm.mp3", 119) # Main game loop while True: # Game runs forever, keeps on running screen.update() # Updates each time through the loop move_player() # Enemy mechanics for enemy in enemies: # Moveing the enemy x = enemy.xcor() x += enemyspeed enemy.setx(x) # must put (x) inside parenthesis # Move the enemy back and down if enemy.xcor() > 280: for e in enemies: # loop within a loop = nested loop y = e.ycor() y -= 40 e.sety(y) # Change enemy direction enemyspeed *= -1 if enemy.xcor() < -280: for e in enemies: y = e.ycor() y -= 40 e.sety(y) # Change enemy direction enemyspeed *= -1 # Enemy collides with player if isCollision(player, enemy): enemyspeed = 0 player.speed = 0 x = player.xcor() player.setx(10000) # Sends the turtle out of range so the losing.mp3 does not constantly repeat play_sound("impact_crete.wav") play_sound("losing.mp3") player.hideturtle() enemy.hideturtle() # Draw Message lose = turtle.Turtle() lose.speed(0) lose.shape("square") lose.color("red") lose.penup() lose.hideturtle() lose.goto(0,0) lose.write("GAME OVER.", align="center", font=("Courier", 60, "normal")) break # Check for collision between bullet and enemy if isCollision(bullet, enemy): play_sound("impact_crete.wav") # Reset the bullet bullet.hideturtle() bulletstate = "ready" bullet.setposition(0, -400) # Reset the enemy enemy.setposition(0,10000) # Update the score score += 10 scorestring = "Score: {}".format(score) score_pen.clear() score_pen.write(scorestring, False, align="left", font=("Areial", 14, "normal")) # Increase enemy speed if enemyspeed > 0: enemyspeed += 0.025 else: enemyspeed -= 0.025 print(enemyspeed) # Check for collision between bullet2 and enemy if isCollision(bullet2, enemy): play_sound("impact_crete.wav") # Reset the bullet2 bullet2.hideturtle() bulletstate2 = "ready" bullet2.setposition(0, -400) # Reset the enemy enemy.setposition(0,10000) # Update the score score += 10 scorestring = "Score: {}".format(score) score_pen.clear() score_pen.write(scorestring, False, align="left", font=("Areial", 14, "normal")) # Increase enemy speed if enemyspeed > 0: enemyspeed += 0.05 else: enemyspeed -= 0.05 print(enemyspeed) # If enemy hits bottom border if enemy.ycor() < -285: enemyspeed = 0 player.speed = 0 player.sety(10000) # Sends the turtle out of range so the losing.mp3 does not constantly repeat play_sound("impact_crete.wav") play_sound("losing.mp3") player.hideturtle() enemy.hideturtle() # Draw Message lose = turtle.Turtle() lose.speed(0) lose.shape("square") lose.color("red") lose.penup() lose.hideturtle() lose.goto(0,0) lose.write("GAME OVER.", align="center", font=("Courier", 60, "normal")) break # Move the bullet if bulletstate == "fire": y = bullet.ycor() y = y + bulletspeed bullet.sety(y) # Move bullet2 if bulletstate2 == "fire": y = bullet2.ycor() y = y + bulletspeed bullet2.sety(y) screen.onkeypress(fire_bullet, "space") == False # Check to see if the bullet has gone to the top if bullet.ycor() > 290: bullet.hideturtle() bulletstate = "ready" # Check to see if the bullet2 has gone to the top if bullet2.ycor() > 290: bullet2.hideturtle() bulletstate2 = "ready" # Play winning song if won if score == 300: play_sound("winning.mp3") player.speed = 0 player.hideturtle() enemy.hideturtle() # Draw Message win = turtle.Turtle() win.speed(0) win.shape("square") win.color("yellow") win.penup() win.hideturtle() win.goto(0,0) win.write("YOU WIN!", align="center", font=("Courier", 60, "normal")) break #delay = raw_input("Press enter to finish.")
580be650f840ef13d4fd478d75f8dba4c5273f95
maiya-tracy/helloFlask
/hello.py
996
3.578125
4
from flask import Flask # Import Flask to allow us to create our app app = Flask(__name__) # Create a new instance of the Flask class called "app" @app.route('/') # The "@" decorator associates this route with the function immediately following def hello_world(): return 'Hello World!' # Return the string 'Hello World!' as a response @app.route('/dojo') def dojo(): return "Dojo!" @app.route('/say/<id>') def hello(id): if (type(id) is str): return "Hi " + id + "!" else: return "That's not a string!" @app.route('/repeat/<num>/<stringy>') def repeating(num, stringy): # num = int(num) # stringy = str(stringy) big_string = '' for i in range(int(num)): big_string = big_string + stringy + ' ' return big_string @app.errorhandler(404) def page_not_found(error): return "Sorry! No response. Try again." if __name__=="__main__": # Ensure this file is being run directly and not from a different module app.run(debug=True) # Run the app in debug mode.
9459cbf14133847e1e0558bab3b42d701f961ddf
VLD62/PythonFundamentals
/01.PYTHON_INTRO_FUNCTIONS_DEBUGGING/06.Math_Power.py
182
3.78125
4
def power_calculator(n,pow): return n ** abs(pow) if __name__ == '__main__': number = float(input()) power = int(input()) print(power_calculator(number,power))
d6198d84c1a376eb709049ab982db14e418698c9
kjnh10/pcw
/work/atcoder/abc/abc079/B/answers/782387_amukichi.py
306
3.59375
4
#!/usr/bin/env python3 import functools @functools.lru_cache(maxsize=None) def lucas(n): if n == 0: return 2 elif n == 1: return 1 else: return lucas(n - 1) + lucas(n - 2) def main(): n = int(input()) print(lucas(n)) if __name__ == '__main__': main()
d8da81942f3a41175ffeff7d65f2f7de4950328c
ekjellman/interview_practice
/ctci/17_3.py
825
3.953125
4
### # Problem ### # Write a method to randomly generate a set of m integers from a list of size # n. Each element must have an equal probability of being chosen. ### # Work ### # Questions: # Sizes of m and n? (assume fits in memory) # Invalid inputs? (Assume input is valid) # -- negative m, m > n, etc. import random def random_set(numbers, m): assert m >= 0 and m <= len(numbers) numbers_copy = numbers[:] random.shuffle(numbers_copy) return numbers_copy[:m] # or turn into a set, or whatever. # Alternate strategies: # -- Make copy, pick items one at a time. # -- Pick indices one at a time, using a set to ensure no duplicates, until you # have m # -- Shuffle the original list then return the slice the same way, if you can # modify numbers # Time: 5 minutes ### # Mistakes / Bugs / Misses ###
602c4f96aebb51ffa0ee20f861f45e1340e79f4b
FelipeLauton/Python
/Exercicios/ex007.py
171
3.796875
4
medida = float(input('Uma distância em metros: ')) cm = medida * 100 mm = medida * 1000 print('A distância de {}m em cm vale {}cm e em mm {}mm.'.format(medida, cm, mm))
7f4503b51c5c06b2c97242a6058450ac5ca17978
KumarSanskar/Python-Programs
/Getting_items_of _list.py
669
4.75
5
# Programs to access items/elements of the list: # (1) Using index:- This can be used to get a specific item: lst = ["Ram","Ali","Hardy","Joe"] print("List is: ",lst) print("Item at second is:",lst[2]) # (2) Using negative index:- this can be used to acces item from backwards, (-1) represents last element: lst = ["Ram","Ali","Hardy","Joe"] print("List is: ",lst) print("Item at last is: ",lst[-1]) print("Item at second last is :", lst[-2]) # (3) Using index range:- By mentioning the index range it can be accessed: lst = ["Ram","Ali","Hardy","Joe","Hariom","Rebeca"] print("List is: ",lst) print("Items in range [2:5] is: ",lst[2:5])
c59789e7ccc1f32b917c659347e9d00a4b497df6
mgermaine93/python-playground
/python-coding-bat/warmup-1/monkey_trouble/test_module.py
1,163
3.5625
4
import unittest from monkey_trouble import monkey_trouble class UnitTests(unittest.TestCase): def test_true_and_true_returns_true(self): actual = monkey_trouble(True, True) expected = True self.assertEqual( actual, expected, 'Expected calling "monkey_trouble() with "True" and "True" to return "True"') def test_false_and_false_returns_true(self): actual = monkey_trouble(False, False) expected = True self.assertEqual( actual, expected, 'Expected calling "monkey_trouble() with "False" and "False" to return "True"') def test_true_and_false_returns_false(self): actual = monkey_trouble(True, False) expected = False self.assertEqual( actual, expected, 'Expected calling "monkey_trouble() with "True" and "False" to return "False"') def test_false_and_true_returns_false(self): actual = monkey_trouble(False, True) expected = False self.assertEqual( actual, expected, 'Expected calling "monkey_trouble() with "False" and "True" to return "False"') if __name__ == "__main__": unittest.main()
4ac47b9c33a339eff8496612c2d841f492122157
Tiyasa41998/py_program
/temp.py
97
3.796875
4
c= float(input("enter the temparature")) f=(c*9/5)+32 print("the temparature is" ,float(f))
a3bb5d8bd60c5c5e6a23aa0dfd33eb7b038ad0c9
nat-g/algorithms
/BasicDataStructures/linked_lists/singly_linked_list.py
629
3.578125
4
#!/usr/bin/env python """ Pros: 1) Linked lists have constant insertion and deletion time at any position n comparison arrays will always require linear (meaning O(n)) to do the same thing 2) Linked lists can also expand without specifying their size ahead of time (amortization reference) Cons: 1) Lookup time is O(K) where K is the Kth element. In contrast, arrays have constant time operations to access elements in the array. """ class SinglyNode(object): def __init__(self, value): self.value = value self.nextnode = None a = SinglyNode(1) b = SinglyNode(2) c = SinglyNode(3) a.nextnode = b b.nextnode = c
29841f1c1c7fb2bb63b10d84df3cc73a349d7191
younes38/Daily-Coding-Problem
/uber_problems/problem_4.py
544
4.1875
4
"""This problem was asked by Uber. Implement a 2D iterator class. It will be initialized with an array of arrays, and should implement the following methods: next(): returns the next element in the array of arrays. If there are no more elements, raise an exception. has_next(): returns whether or not the iterator still has elements left. For example, given the input [[1, 2], [3], [], [4, 5, 6]], calling next() repeatedly should output 1, 2, 3, 4, 5, 6. Do not use flatten or otherwise clone the arrays. Some of the arrays can be empty."""
0fd8b7c6d2cf62cb26e520db90fd717231fb2dcc
icarogoggin/Exercitando_python
/Exercicios11_PintandoParede.py
302
3.9375
4
largura = float(input('Digite a largura da parede: ')) altura = float(input('Digite a Altura da parede: ')) area = largura*altura print(f'Sua parede tem a dimensão de {largura}x{altura} e sua área é de {area}m') tinta = area/2 print(f'Para pintar essa parede, você precisará de {tinta}l de tinta')
79691788a8cd9dca4857937a16a18af632a30be7
dingkillerwhale/Python
/My_Python/Manhattan_Distance.py
169
3.640625
4
# Manhattan Distance from numpy import * # import numpy libraries v1 = array([1,2,3]) v2 = array([4,5,6]) print(sum(abs(v1 - v2))) # print Manhattan Distance
799fccf6325d7f38069b9dd7b42ec459d77643af
qiang-yu-scd/Python_cursus
/pe5_1.py
251
3.703125
4
score = input ( 'Geef je score: ' ) if int(score) >= 15: print ( 'Gefeliciteerd!' ) print ( 'Met een score van' + ' ' + str(score) +' ' + 'ben je geslaagd!' ) else: print ( 'Met een score van' + ' ' + str(score) +' ' + 'ben je Gezakt!')
99f862a58831afe3072727be21fea0163f6c5b35
omdeshmukh20/Python-3-Programming
/string1.py
243
3.828125
4
#Discription: str input #Date: 10/07/21 #Author : Om Deshmukh print("Enter the element:") element=str(input()) for i in range(element): if element=str.upper(): print(element.lower()) else element=str.lower(): print(element.upper())
6b1deb02f50a897037c402e8f8736c30c772233b
mrfabroa/ICS3U
/Archives/2_ControlFlow/2_5_1_Practice/question_3_for_loop.py
899
4.28125
4
""" Write a trip calculator that allows the user to enter how many trips they’ve travelled (in km) and then the distance travelled for each trip. It should then output the total distance travelled. """ number_of_trips = input("How many trips did you travel?") total_distance = 0 for i in range(1, number_of_trips + 1): distance = input("Enter the distance in km travelled for trip " + str(i)) total_distance = total_distance + distance print "The total distance travelled on your trips is", total_distance, "km." # WHILE LOOP VERSION number_of_trips = input("How many trips did you travel?") total_distance = 0 count = 1 while count <= number_of_trips: distance = input("Enter the distance in km travelled for trip " + str(count) +": ") total_distance = total_distance + distance count += 1 print "The total distance travelled on your trips is", total_distance, "km."
0c30c0a6c467442df9f6136d7bb6841fc59bc36f
TanyaFox/3_bars
/bars.py
1,537
3.75
4
import json import math def load_data(filepath): with open(filepath, 'r') as json_file: data = json.load(json_file) return data def get_biggest_bar(data): biggest_bar = max(data, key = lambda i: i['SeatsCount']) return (biggest_bar['Name'], biggest_bar['SeatsCount']) def get_smallest_bar(data): biggest_bar = min(data, key = lambda i: i['SeatsCount']) return (biggest_bar['Name'], biggest_bar['SeatsCount']) def get_distance(x1, y1, x2, y2): distance = math.sqrt((float(x2)-x1)**2+(float(y2)-y1)**2) return distance def get_closest_bar(data, longitude, latitude): closest_bar = min([{"Name": bar['Name'], "Address": bar['Address'], "Distance" : get_distance(latitude, longitude, bar['Latitude_WGS84'], bar['Longitude_WGS84'])} for bar in data], key = lambda i: i["Distance"]) return closest_bar if __name__ == '__main__': filepath = input("Enter path to your json file: ") data = load_data(filepath) biggest_bar = get_biggest_bar(data) print("The biggest bar is %s and the number of seats there: %d" % biggest_bar) smallest_bar = get_smallest_bar(data) print("The smallest bar is %s and the number of seats there: %d" % smallest_bar) latitude = float(input("Enter latitude of your location, f.e. 45.56: ")) longitude = float(input("Enter longitude of your location, f.e. 47.67: ")) closest_bar = get_closest_bar(data, longitude, latitude) print("The closest bar is {} and its address {}".format(closest_bar["Name"],closest_bar["Address"]))
fcd05d370cf43d9fddefdeea050748ecef709ca4
jmruzafa/cd50-problem-set
/pset6/credit/credit.py
2,203
3.921875
4
#!/bin/python3 import cs50 import math def main(): # message result = "INVALID" while True: # ask for the change owed creditcard = cs50.get_int("Number: ") if creditcard >= 0: break # get the lenght of the CC number (easier in pyhton than C) # it could be done using this math calculation: # length = int(math.log10(creditcard))+1 # or simply getting the string (an array in fact) digits = str(creditcard) length = len(digits) # because we got the number as integer but in Python it is a string by default # control digit sum = int(digits[-1]) # parity to know which are the digits to multiply parity = length % 2 # now we can iterate through digits of the credit card but the last one (control) for i in range (length-1): #extract the digit digit = int(digits[i]) #check if it equals to parity if i % 2 == parity: digit = digit * 2 # if we go over 9 we need to get the sum of both ( x * 2 = y > 9 => x + y) if digit > 9: digit -= 9 sum += digit # this is another way to calcultate the control digit. # the check digit (x) is obtained by computing the sum of the # digits (third row) then subtracting the units digit from 10 if sum % 10 == 0: first_digit = int(digits[0]) second_digit = int(digits[1]) if (length == 15 and first_digit == 3 and (second_digit == 4 or second_digit == 7)): result = "AMEX" elif (length == 16 and first_digit == 5 and (second_digit == 1 or second_digit == 2 or second_digit == 3 or second_digit == 4 or second_digit == 5)): result = "MASTERCARD" elif ((length == 13 or length == 16) and first_digit == 4): result = "VISA" print(f"{result}") def getDigitsArray(digits, number): factor = 1 temp = number while temp != 0: temp = temp / 10 factor = factor * 10 i = 0 while factor > 1: factor = factor / 10 digits[i] = number // factor number = number % factor i += 1 main()
e006ef63dad027281a421c972f761913c5fdb4d2
Lusarom/progAvanzada
/ejercicio93.py
790
3.984375
4
def nextPrime(n): while True: if n < 0: print("www") print("El número no es un entero positivo") n = float(input("Ingrese un número entero positivo: ")) elif n != int(n): print("El número no es un entero positivo") n = float(input("Ingrese un número entero positivo: ")) else: break n = int(n) n = n+1 while True: for i in range(2,n): if n%i == 0: n = n+1 break else: print("El primero primo más grande que el número ingresado es: ", n) break def main(): number = float(input("Ingrese un número entero positivo: ")) nextPrime(number) main()
d6c644c054f05051263f7ba3a98050450910f495
hellohaoyu/codeEveryDay
/constructStringFromBinaryTree.py
1,492
3.78125
4
# Leetcode: https://leetcode.com/problems/construct-string-from-binary-tree/description/ # Input: Binary tree: [1,2,3,4] # 1 # / \ # 2 3 # / # 4 # Output: "1(2(4))(3)" # Explanation: Originallay it needs to be "1(2(4)())(3()())", # but you need to omit all the unnecessary empty parenthesis pairs. # And it will be "1(2(4))(3)". # Input: Binary tree: [1,2,3,null,4] # 1 # / \ # 2 3 # \ # 4 # Output: "1(2()(4))(3)" # Explanation: Almost the same as the first example, # except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Be careful about the rules => root(Left)(Right) when both left and right exists. class Solution(object): def tree2str(self, t): """ :type t: TreeNode :rtype: str """ if not t: return "" rs = str(t.val) if t.left and t.right: return rs + "(" + self.tree2str(t.left) + ")(" + self.tree2str(t.right) + ")" elif t.left: return rs + "(" + self.tree2str(t.left) + ")" elif t.right: return rs + "()(" + self.tree2str(t.right) + ")" # Remember to check the needs!!! rootVal(Left)(Right) else: return rs
92b2b4abee66646bdbf171da3081a6a08a9ff0c6
snlab/utilities
/mininet/ysn_linuxrouter.py
3,830
3.671875
4
#!/usr/bin/python """ linuxrouter.py: Example network with Linux IP router This example converts a Node into a router using IP forwarding already built into Linux. The topology contains MX-router (r1) with two IP subnets: - 130.132.11.0/24 (interface r1-eth1 IP: 130.132.11.1) - 192.31.2.0/24 (interface r1-eth2 IP: 192.31.2.1) - h1 (IP: 130.132.11.100) connected to r1-eth1 - r2 (IP: 192.32.2.8) connected to r1-eth2 KBT (r2) with two IP subnets: - 192.31.2.0/24 (interface r2-eth1 IP: 192.31.2.8) Assuming KBT has a port on vlan200 and vlan200 is 172.28.28.0/24 - 172.28.28.0/8 (interface r2-eth2 IP: 172.28.28.10) - r1 (IP: 192.31.2.1) connected to r2-eth1 - s1 (IP: 172.28.28.1) connected to r2-eth2 300G-Router (s1): Acting as a legacy L2 switch on vlan 172.28.28.0/24 - r2 (IP: 172.28.28.10) connected to s1-eth1 - h3 (IP: 172.28.28.101) connected to s1-eth2 - s2 connected to s1-eth3 WC-Switch (s2): Acting as a Legacy L2 switch on vlan 172.28.28.0/24 - s1 connected to s2-eth1 - h4 connected to s2-eth2 Routing entries can be added to the routing tables of the hosts or router using the "ip route add" or "route add" command. See the man pages for more details. """ from mininet.topo import Topo from mininet.net import Mininet from mininet.node import Node, Controller, RemoteController, OVSKernelSwitch from mininet.log import setLogLevel, info from mininet.cli import CLI class LinuxRouter( Node ): "A Node with IP forwarding enabled." def config( self, **params ): super( LinuxRouter, self).config( **params ) # Enable forwarding on the router self.cmd( 'sysctl net.ipv4.ip_forward=1' ) def terminate( self ): self.cmd( 'sysctl net.ipv4.ip_forward=0' ) super( LinuxRouter, self ).terminate() class NetworkTopo( Topo ): "A simple topology of a router with three subnets (one host in each)." def build( self, **_opts ): router = self.addNode( 'r1', cls=LinuxRouter, ip='130.132.11.9/24') h1 = self.addHost( 'h1', ip='130.132.11.100/24', defaultRoute='via 130.132.11.9' ) self.addLink( h1, router, intfName2='r1-eth1', params2={ 'ip' : '130.132.11.9/24' } ) router2 = self.addNode( 'r2', cls=LinuxRouter, ip='192.32.2.8/24' ) #h2 = self.addHost( 'h2', ip='172.28.28.100/24', # defaultRoute='via 172.28.28.10' ) self.addLink( router, router2, intfName1='r1-eth2', intfName2='r2-eth1', params1={'ip' : '192.31.2.1/24'}, params2={'ip' : '192.32.2.8/24'}) #self.addLink( h2, router2, intfName2='r2-eth2', # params2={ 'ip' : '172.28.28.10/24' } ) switch1 = self.addSwitch('s1') switch2 = self.addSwitch('s2') h3 = self.addHost('h3', ip='172.28.28.101/24', defaultRoute='via 172.28.28.10') h4 = self.addHost('h4', ip='172.28.28.102/24', defaultRoute='via 172.28.28.10') self.addLink(router2, switch1, intfName1='r2-eth2', params1={'ip': '172.28.28.10/24'}) self.addLink(switch1, h3) self.addLink(switch1, switch2) self.addLink(switch2, h4) def run(): "Test linux router" topo = NetworkTopo() c0 = RemoteController('c0') net = Mininet( topo=topo, controller=c0) # no controller needed net.start() print net['r1'].cmd('ip route add 192.32.2.0/24 dev r1-eth2') print net['r2'].cmd('ip route add 192.31.2.0/24 dev r2-eth1') print net['r1'].cmd('ip route add 172.28.28.0/24 via 192.32.2.8') print net['r2'].cmd('ip route add 130.132.11.0/24 via 192.31.2.1') info( '*** Routing Table on MX-104\n' ) print net[ 'r1' ].cmd( 'route' ) info( '*** Routing Table on KBT\n' ) print net[ 'r2' ].cmd( 'route' ) CLI( net ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) run()
ff849e53eee5fe198eb33eaaa4aa9f4a3e1c7096
sdfgx123/Python_lecture
/section_8_Dynamic_programming/4.py
595
3.59375
4
# 도전과제 돌다리 건너기 bottom up # 쉽게 생각해서, top down은 DFS, bottom up은 dynamic programming 생각 import sys sys.stdin=open("C:\Python-lecture\Python_lecture\section_8_Dynamic_programming\input.txt", "rt") # def DFS(x): # if dy[x]>0: # return dy[x] # if x==1 or x==2: # return x # else: # dy[x]=DFS(x-1)+DFS(x-2) # return dy[x] # if __name__=="__main__": # n=int(input()) # dy=[0]*(n+1) # print(DFS(n)) n=int(input()) dy=[0]*(n+1) dy[1]=1 dy[2]=2 for i in range(3, n+1): dy[i]=dy[i-1]+dy[i-2] print(dy[n])
3c3100353ea38b11bffd0b6558e40c4060266e93
research-fork/SMTsolver
/smt_solver/solver/solver.py
826
3.921875
4
from abc import ABC, abstractmethod class Solver(ABC): @abstractmethod def __init__(self): """ Initializes the solver. """ pass def create_new_decision_level(self): """ Creates a new decision level. """ pass def backtrack(self, level: int): """ Backtracks to the specified level. """ pass def propagate(self): """ Propagates constraints. """ pass @abstractmethod def get_assignment(self) -> dict: """ :return: a {literal: int -> value: bool} dictionary containing the current assignment. """ pass @abstractmethod def solve(self) -> bool: """ :return: True if SAT, False otherwise. """ pass
20eebbe85ae1b1f2d50297cd9a036c77d63aeb00
lixiang2017/leetcode
/leetcode-cn/1436.0_Destination_City.py
877
3.703125
4
''' Hash Table 执行用时:36 ms, 在所有 Python3 提交中击败了50.15% 的用户 内存消耗:15 MB, 在所有 Python3 提交中击败了69.66% 的用户 通过测试用例:103 / 103 ''' class Solution: def destCity(self, paths: List[List[str]]) -> str: a2b = {} for a, b in paths: a2b[a] = b city = paths[0][1] while city in a2b: city = a2b[city] return city ''' Hash Set s 执行用时:32 ms, 在所有 Python3 提交中击败了77.40% 的用户 内存消耗:15.1 MB, 在所有 Python3 提交中击败了13.93% 的用户 通过测试用例:103 / 103 ''' class Solution: def destCity(self, paths: List[List[str]]) -> str: starts = set() for s, _ in paths: starts.add(s) for _, e in paths: if e not in starts: return e
7f61e27afa407ba726e261040cae124cf05e8828
juliendurand/geoapi
/src/trigram.py
1,526
3.765625
4
""" Copyright (C) 2016 Julien Durand Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class Trigram(): def __init__(self, s): # Construction of the list of trigrams of the string s. # First and last letter and couple of letters are included trigram_list = [s[max(0, i):min(len(s), i + 3)] for i in range(-2, len(s))] # Object fields instantiation self.s = s self.trigrams = set(trigram_list) def score(self, s): """ Computes the socre of similqrity between self.s and s Keyword arguments: s -- the string to compare """ # Construction of the list of trigrams of the string s. # First and last letter and couple of letters are included. trigram_list = [s[max(0, i):min(len(s), i + 3)] for i in range(-2, len(s))] intersection = set(trigram_list) & self.trigrams # Computation of the final score. return 2 * len(intersection) / (len(s) + len(self.s) + 4)
f71c00f69d927ea007db0d44ffbe832a598b0ca4
jxlxt/leetcode
/Python/92.reverse_linked_listII.py
756
3.6875
4
class Solution: def reverseBetween(self, head, start, end): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ dummy_head = sublist_head = ListNode(0) sublist_head.next = head for _ in range(1, start): sublist_head = sublist_head.next # reverses sublist sublist_iter = sublist_head.next for _ in range(end - start): temp = sublist_iter.next sublist_iter.next, temp.next, sublist_head.next = (temp.next, sublist_head.next, temp) return dummy_head.next
2d46b5ee5c79dc997df806e1df1dc37ef0cd5f94
bakunobu/exercise
/python_programming /Chapter_1.1_and_1.2/order_check.py
773
4.21875
4
""" Составьте программу, получающую в аргументах ко­мандной строки три значения, х, у и z типа float, а выводящую True, если значения расположены в порядке возрастания или убывания (х < у < z или х >у> z), и False в противном случае. """ def in_a_raw(x:float, y:float, z:float) -> bool: """ An order checker Args: ===== x: float the first element of a series y: float the second element of a series z: float the third element of a series Return: ======= result: bool True if a < b < c or a > b > c """ return((x < y < z) or (x > y > z))
414054aed84fa777b5c21b3409b6c5e1a628f791
flora-pura/pog
/listAppV1DeBerry.py
4,614
4.21875
4
""" Program Goals: 1. Get input from the user (at multiple points) 2. We need to convert some of this input to INTs from StRs 3. We need to provide choices to the user a. Add more values to the list b. Return a value a speciftic index """ import random myList = [] uniqueList = [] def mainProgram(): #build a while loop here! while True: try: print("Hello, there! Lets work with lists!") print("Choose from the following options. Type a number below!") choice = input("""1. Add to list , 2. Add a bunch of numbers, 3. Return the value at an index, 4. Random Search, 5. Linear Search, 6. Recursive Binary Search, 7. Iterative Binary Search 8. Sort list, 9. Print contents of list 10. Exit program. """) #add a way to catch bad user responses if choice == "1": addToList() elif choice == "2": addABunch() elif choice == "3": indexValues elif choice == "4": randomSearch() elif choice == "5": linearSearch() elif choice == "6": searchItem = input("What are you looking for? ") recursiveBinarySearch(uniqueList, 0, len(uniqueList)-1, int(searchItem)) elif choice == "7": searchItem = input("What are you looking for? ") result = iterativeBinarySearch(uniqueList, int(searchItem)) if result != -1: print("Your number is at index {}".format(result)) else: print("Your number isn't in this list!") elif choice == "8": sortList(myList) elif choice == "9": printList() else: break except: print("You made a whoopsie!") #TO ADD: 1. a way to loop the action, 2. a way to quit, 3. think of repetition def addToList(): print("Adding to list! Great choice!") newItem = input("Type an integer here! ") myList.append(int(newItem)) def addABunch(): print("We're gonna add a bunch of integers here!") numToAdd = input("How many new integers would you like to add?") numRange = input("And how high would you like these numbers to go? ") for x in range(0, int(numToAdd)): myList.append(random.randint(0, int(numRange))) print("Your list is now complete.") def indexValues(): print("Ohhh! I heard you a particular piece of data!") indexPos = input("What index position are you curious about? ") print(myList[int(indexPos)]) def sortList(myList): print("A little birdy told me you needed some data") for x in myList: if x not in uniqueList: uniqueList.append uniqueList.sort() showMe = input("Wanna see your new list? Y/N") if showMe.lower() == "y": print(uniqueList) def randomSearch(): print("RaNDoM SeaRCH!") print(myList [random.randint(0, len (myList)-1)]) def linearSearch(): print("We're gonna check out each item one at a time in your list! this sucks.") searchItem = input("What you lookin for pardner? ") for x in range(len(myList)): print("Your item is at index posistion {}".format(x)) def recursiveBinarySearch(uniqueList, low, high, x): if high >= low: mid = (high + low) // 2 if uniqueList[mid] == x: print("You ding dang found it at index position {}".format(mid)) return mid elif uniqueList[mid] > x: return recursiveBinarySearch(uniqueList, low, mid -1, x) else: recursiveBinarySearch(uniqueList, mid + 1, high, x) else: print("Your number isn't here!") def iterativeBinarySearch(uniqueList, x): low = 0 high = len(uniqueList)-1 mid = 0 while low <= high: mid = (high + low) // 2 if uniqueList[mid] < x: low = mid + 1 elif uniqueList[mid] > x: high = mid - 1 else: return mid return -1 def printList(): if len(uniqueList) == 0: print(myList) else: which0ne = input("Which list? sorted or unsorted? ") if Which0ne.lower() == "sorted": print(uniqueList) else: print(myList) #dunder main -> Double Underscore---dunder if __name__ == "__main__": mainProgram()
b4e90b4be5e93f441ff131ba49dd04c36428ea9e
AHowardC/python101
/excerise.py
1,781
4.0625
4
name = raw_input("What is your name") #day 4 algorithim 1 # if we list all natural numbers below 10 that are mulitiples of 3 or 5, we get 3,5,6, and 9. # the sum of these nultiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. empty_list = [] for i in range (0, 1000, 3): empty_list.append(i) for j in range (0, 1000, 5): empty_list.append(j) total = sum(empty_list) print total # day 4 algorithim 2 # Each new term in the fibonacci sequence is generated by adding the previous two terms. #by starting with 1 and 2, the first 10 terms will be: # 1,2,3,5,8,13,21,34,55,89,... #By considering the terms in the Fibonacci sequence whose values do not exceed four million, #find the sum of the even_valued terms. fib_first = [1, 2] even_fib = [] i = 1 max_fib = 4000000 curr_sum = fib_first[1] while curr_sum <= max_fib: if (curr_sum % 2 == 0): even_fib.append(curr_sum) curr_sum = fib_first[i] + fib_first[i-1] if (curr_sum > max_fib): break fib_first.append(curr_sum) i += 1 # print fib_first # print even_fib[-1] print sum(even_fib) #Algorithim 3 #The prime factors of 13195 are 5,7,13 and 29. #What is the largest prime factor of the number 600851475143? def is_prime(n, prime_list): for i in prime_list: if (n % i == 0): return False return True num = 600 factor = [] prime_factor = [2] for i in range (2, num): if (num % i == 0): # factor if is_prime(i, prime_factor): prime_factor.append(i) # factor.append(i) # for j in factor: # if is_prime(j): # prime_factor.append(j) # print factor print prime_factor if (len(prime_factor) > 0): print max(prime_factor) else: print "Your number %d is prime!" % num
9142898d5d79f70e9cd31c6704d07da464fbb38b
Sandraopone1/python_fundamentals
/findCharacters.py
548
3.796875
4
# def findCharacters(listed,singlechar): # newArr = [] # for x in range(0,len(listed)): # if listed[x].find(singlechar) != -1: # newArr.append(listed[x]) # return newArr # print findCharacters(['hello', 'the'], 'l') word_list = [] def FindCharacters(list, character ): for word in list: for char in word: if char == character : word_list.append(word) break else: pass print word_list FindCharacters(['hello','world','my','name','is','Anna'], "o" )
dafc642f39bbc5dbdebdb91ef85c83e064727063
sifo/hackerrank
/python/built_ins/athlete_sort.py
307
3.671875
4
# https://www.hackerrank.com/challenges/python-sort-sort/problem if __name__ == '__main__': N, _ = map(int, input().split()) l = [] for i in range(N): l.append(list(map(int, input().split()))) K = int(input()) l = sorted(l, key=lambda x: x[K]) for i in l: print(*i)
8f0afa4f5a2f06d884db53e6b99096e74c03cb0b
maurus56/exercism
/python/word-count/word_count.py
192
3.6875
4
def word_count(phrase): import re phrase = re.compile(r"[a-z]+'?[a-z]|[0-9]").findall(phrase.lower()) d = {} for key in phrase: d[key] = d.get(key, 0) + 1 return d
136918e0c0b7c1d655fabeab683cc091da981f65
Jean-Martins22/Exercicios-Python
/Projeto_03.py
4,428
3.828125
4
# Importanto a biblioteca randint para escolher aleatóriamente from random import randint # Importanto a biblioteca sleep para fazer pausas durante um print e outro from time import sleep # Mostrando a apresentação do campeonato e as Regras print('-=-' * 32) print(' Sejam bem vindos ao campeonato de dados 🎲 RocketZada ') sleep(1) print('Queijão 🧀: Sou o apresentador Queijão e hoje iremos ter uma disputa de dados entre os jogadores: ') print('-=-' * 32) print() print('=' * 10, 'Jogadores', '=' * 10) sleep(1) print('Jean 😃') sleep(1) print('Antonio 😄') sleep(1) print('Jonas 😁') sleep(1) print('Ricardo 😆') print('=' * 31) print() print('-=-' * 12) print('Queijão 🧀: Vamos explicar as regras') print('-=-' * 12) print() print('=' * 37, 'Regras', '=' * 37) print('A cada rodada os jogadores deverão rodar o dado 1 vez') sleep(1) print('Quem tirar o maior número será o vencedor') sleep(1) print('Caso der empate durante uma rodada o jogo será desconsiderado') sleep(1) print('Em RocketZada poderá haver mais de um campeão') sleep(1) print('E se jogarem mais de 1 rodada, as vitórias serão somadas e mostradas no final.') print('=' * 82) print() print('-=-' * 36) print('Queijão 🧀: Que tal você nosso caro espectador escolher quantas rodadas nossos queridos jogadores irão fazer ?') print('-=-' * 36) print() dicionario = dict() # Dicionário crido para guardar os valores de cada rodada jean = antonio = jonas = ricardo = empate = 0 # Variáveis criadas para guardas as vitórias de cada jogador for i in range(int(input('Digite quantos jogos iremos fazer hoje: '))): # Pergunta ao usuário quantos jogos vai querer fazer dicionario['Jean'] = randint(1, 6) # Escolhe um número aleatório para os jogadores (Linha 53 até 56) dicionario['Antonio'] = randint(1, 6) dicionario['Jonas'] = randint(1, 6) dicionario['Ricardo'] = randint(1, 6) print() # Formatação print('Rodando os dados... 🕗') print() sleep(3) print('=' * 10, 'Resultados desta Rodada', '=' * 10) # Mostra os resultados de cada partida (Linha 61 até 69) print(f"Jean 😃: {dicionario['Jean']}") sleep(1) print(f"Antonio 😄: {dicionario['Antonio']}") sleep(1) print(f"Jonas 😁: {dicionario['Jonas']}") sleep(1) print(f"Ricardo 😆: {dicionario['Ricardo']}") print('=' * 45) # Calcula os possíveis resultados dos jogos (Linha 73 até 104) if dicionario['Jean'] > dicionario['Antonio'] and dicionario['Jean'] > dicionario['Jonas'] and dicionario['Jean'] > dicionario['Ricardo']: jean += 1 # Adiciona mais 1 as vitórias do jogador print('O vencedor desta rodada foi...') # Formatação sleep(2) print('Jean 😃') elif dicionario['Antonio'] > dicionario['Jean'] and dicionario['Antonio'] > dicionario['Jonas'] and dicionario['Antonio'] > dicionario['Ricardo']: antonio += 1 print('O vencedor desta rodada foi...') sleep(2) print('Antonio 😄') elif dicionario['Jonas'] > dicionario['Jean'] and dicionario['Jonas'] > dicionario['Antonio'] and dicionario['Jonas'] > dicionario['Ricardo']: jonas += 1 print('O vencedor desta rodada foi...') sleep(2) print('Jonas 😁') elif dicionario['Ricardo'] > dicionario['Jean'] and dicionario['Ricardo'] > dicionario['Antonio'] and dicionario['Ricardo'] > dicionario['Jonas']: ricardo += 1 print('O vencedor desta rodada foi...') sleep(2) print('Ricardo 😆') else: print() ('-=-' * 14) sleep(1) print('Queijão 🧀: Parece que deu empate ⛔, essa rodada será desconsiderada!. Pois só pode haver 1 vencedor por rodada') sleep(1) ('-=-' * 14) empate += 1 # Mostra os resultados finais print() print('-=-' * 12) print('Queijão 🧀: Os resultados finais são:') print('-=-' * 12) print() print('=' * 10, 'Resultados', '=' * 10) print(f'Jean 😃 ganhou: {jean} vezes') sleep(1) print(f'Atonio 😄 ganhou: {antonio} vezes') sleep(1) print(f'Jonas 😁 ganhou: {jonas} vezes') sleep(1) print(f'Ricardo 😆 ganhou: {ricardo} vezes') sleep(1) print(f'Foram desconsiderados: {empate} empates ⛔') print('=' * 32)