blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
15fba47f232916f6bc1df9a720e5484cbe12c659
pegurnee/2016-01-667
/homework/2_hw/src/5.py
789
3.53125
4
records = [ (3, 2 , 10, 2), (2, 1 , 2 , 1), (5, 18, 9 , 2), (2, 5 , 4 , 1), (4, 3 , 2 , 1), (4, 17, 12, 2) ] def distances(rec1, records, dis): _ds = [] for r in records: _ds.append(dis(rec1, r)) return _ds def euclid(rec1, rec2): _dist = 0 for u,v in zip(rec1, rec2): _dist += (u - v) ** 2 return _dist ** 0.5 def taxi(rec1, rec2): _dist = 0 for u,v in zip(rec1, rec2): _diff = u - v _dist += -_diff if _diff < 0 else _diff return _dist if __name__ == '__main__': a = (6,7,10) ads = distances(a, records, euclid) print(ads) print('2: {}'.format(1 / ads[0])) _1 = 1 / ads[3] _2 = 1 / ads[4] print('1: {} = {} + {}'.format(_1 + _2, _1, _2)) b = (4, 9, 5) print(distances(b, records, taxi))
90a9511580892809267c7f30a50ed11ab1d09509
momentum-morehouse/house-hunting-with-python-SunriseTechie
/house_hunting.py
467
4.1875
4
# Write your code here # Exercise 1 total_cost = input("What is the cost of your dream home? ") portion_down_payment = total_cost / 4 print(portion_down_payment) current_savings = input("How much have you saved? ") r = 0.04 / 12 each_month_savings = current_savings * r annual_salary = input("What is your annual salary? ") portion_saved = input("What percentage of your salary (as a decimal) will you save? ") # x = input('Enter your name:') # print('Hello, ' + x)
496e840d48a684894493bd801a8999e81f0553dd
Gadhy/trabajo
/boleta 7.py
1,212
3.8125
4
#INPUT cliente=input("cliente:") cajero=input("cajero:") kg_de_manzanas=int(input("ingresar los kg de manzana=")) precio_por_cada_kg_de_manzana=float(input("ingresar el precio por cada kg de manzana =")) #PROCESSING pago_total=(kg_de_manzanas*precio_por_cada_kg_de_manzana) #OUTPUT print("#############################################################################################") print("################# BOLETA DE COMPRA ##########################################################") print("########### cliente:" , cliente , "##########################################################") print("########### cajero:" , cajero , "############################################################") print("########### kd de manzanas", kg_de_manzanas , "##############################################") print("########### precio por cada kg de manzana: s/.", precio_por_cada_kg_de_manzana, "############") print("#############################################################################################") print("###### pago total:", pago_total , "##########################################################") print("#############################################################################################")
dedba6d17bedfd43c086419a03afd24a0c47312b
wolfstriker134/RockPaperScissors
/rockpaperscissors.py
1,886
4.25
4
print("Credit for code and program: https://www.youtube.com/channel/UCYfSGNQSzCKp-QLL4pFKqvA") print() import random while True: print('Game Starting..') choices = ['Rock', 'Paper', 'Scissors'] # bot choices bot = random.choice(choices) player = input('Rock, Paper or Scissors:') player = player.lower() player = player.strip() if (player == 'rock') or (player == 'paper') or (player == 'scissors'): """ it is better to have a block filled with at least some code instead of leaving it as just 'pass' """ print() else: bad_input = True while bad_input: player = input('Rock, Paper or Scissors:') # you input player = player.lower() player = player.strip() if (player == 'rock') or (player == 'paper') or (player == 'scissors'): print() bad_input = False break else: continue """ upper case your choice just for the looks """ player = player.title() print(f'You chose {player}') print(f'Opponent chose {bot}\n') bot_win = 'Opponent wins.\n\n\n\n' player_win = 'You win!\n\n\n\n' # Check for winner player = player.lower() bot = bot.lower() if bot == 'rock' and player == 'scissors': print(bot_win) elif bot == 'paper' and player == 'rock': print(bot_win) elif bot == 'scissors' and player == 'paper': print(bot_win) elif player == 'rock' and bot == 'scissors': print(player_win) elif player == 'paper' and bot == 'rock': print(player_win) elif player == 'scissors' and bot == 'paper': print(player_win) else: print('Tie!\n\n\n\n') continue
8f9f73532ddbf6387174e0b8e637467e35c66179
codingstudy-pushup/python
/top/Sort_Searching/MeetingRoom.py
638
3.5
4
from typing import List class Solution: def solve_1(self, intervals: List[List[int]]) -> bool: intervals.sort() for i in range(len(intervals) - 1): if intervals[i][1] > intervals[i + 1][0]: return False return True def solve_2(self, intervals: List[List[int]]) -> bool: intervals.sort(key=lambda x: x[0]) for i in range(len(intervals) - 1): if intervals[i][1] > intervals[i + 1][0]: return False return True print(Solution().solve_1([[0, 30], [5, 10], [16, 20]])) print(Solution().solve_2([[0, 30], [5, 10], [16, 20]]))
c2d83fbd0eb7eb8edf44dd5301883fb3553dc4a1
imranali18/RPA4
/source/class_code/lec13_parse_legos.py
553
3.90625
4
""" Building the list of legos from a file. Each line of this file contains the name of a lego and the number of copies of that lego, separated by a comma. For example, 2x1, 3 2x2, 2 """ lego_name = input('Enter the name of the legos file: ').strip() lego_list = [] for line in open(lego_name): line = line.split(',') lego = line[0].strip() # get rid of extra space count = int(line[1]) # Either of the following two lines work... # lego_list.extend([lego] * count) lego_list = lego_list + [lego] * count print(lego_list)
f0b226626c86a66be2f9723cc200bd56f8fbc0ee
lc-rodrigues/Intro-Python-2019.1
/exercicios/aula6/exercicio6.py
2,248
4.25
4
import turtle # nos permite usar as tartarugas (turtles) cor_fundo = input("Que cor gostaria que que fosse sua janela? ") cor_linha = input("Que cor gostaria que fossem suas linhaa? ") largura = input("Considerando 1 o mais fino possível, quão largas gostaria que fossem suas linhas? ") jn = turtle.Screen() # Abre uma janela onde as tartarugas vão caminhar jn.bgcolor(cor_fundo) # Associa a resposta gravada na variável cor_fundo à cor de fundo da janela joana = turtle.Turtle() # Cria uma tartaruga, atribui a joana joana.color(cor_linha) # Associa a resposta gravada na variável cor_linha à cor da linha joana.pensize(largura) # Associa a resposta gravada na variável largura à largura da linha joana.shape("turtle") # Define a forma do cursor como turtle joana.speed(10) # Define a velocidade com que o cursor desenha as linhas joana.color(cor_fundo) # Instruções para posicionar o cursor, sem desenhar na tela joana.backward(200) joana.left(90) joana.forward(200) joana.right(90) joana.color(cor_linha) joana.speed(2) for i in range(5): # Loop para desenhar a primeira estrela joana.forward(100) joana.right(144) joana.forward(103) # Instruções para afastar o cursor, sem desenhar na tela joana.color(cor_fundo) joana.forward(200) joana.color(cor_linha) for i in range(5): # Loop para desenhar a segunda estrela joana.forward(100) joana.right(144) joana.backward(3) joana.color(cor_fundo) joana.right(90) joana.forward(300) joana.left(90) joana.color(cor_linha) for i in range(5): # Loop para desenhar a terceira estrela joana.forward(100) joana.right(144) joana.backward(3) joana.color(cor_fundo) # Instruções para afastar o cursor, sem desenhar na tela joana.backward(300) joana.color(cor_linha) for i in range(5): # Loop para desenhar a quarta estrela joana.forward(100) joana.right(144) joana.backward(3) joana.color(cor_fundo) # Instruções para afastar o cursor, sem desenhar na tela joana.left(90) joana.forward(140) joana.right(90) joana.forward(210) joana.left(90) joana.color(cor_linha) jn.mainloop() # Espera o usuário fechar a janela
3477f677f591fda9efc7fccfec641b0c5afe9a77
ryandavis3/leetcode
/frog_jump/frog_jump2.py
1,064
3.65625
4
import sys from functools import lru_cache from typing import List sys.setrecursionlimit(2500) def canCross(stones: List[int]) -> bool: # Cannot make first jump if stones[1] - stones[0] != 1: return False # Set of stones stones_set = set(stones) L = len(stones) # Dynamic programming with memoization @lru_cache(None) def dp(val: int, k: int) -> bool: # k = 0 -> same spot; return False if k == 0: return False # Reached end! if val == stones[L - 1]: return True # Stone not in set if val not in stones_set: return False # Try different jumps return dp(val+k-1, k-1) or dp(val+k, k) or dp(val+k+1, k+1) return dp(stones[1], 1) class Solution: def canCross(self, stones: List[int]) -> bool: return canCross(stones) if __name__ == "__main__": stones = [0,1,3,5,6,8,12,17] result = canCross(stones) print(result) stones = [0,1,2,3,4,8,9,11] result = canCross(stones) print(result)
e5e75a1c2cb0c7f4ce2975a6dfbb5c95c838618d
ahmadraad97/py
/numpy4.py
2,654
3.796875
4
from numpy import * # ممكن حساب الارقام التي ليست صفر a=random.randint(0,10,(3,3)) b=count_nonzero(a) print(a) # [[2 4 2] # [6 3 7] # [3 2 2]] print(b) # 9 # او تحديد عدد الارقام اكبر او اصغر من كذا a=random.randint(0,10,(3,3)) b=count_nonzero(a>5) c=count_nonzero(a<5) print(a) # [[0 4 1] # [4 9 4] # [5 0 9]] print(b) # 2 print(c) # 6 # وممكن حساب الارقام يكون بالصف اوالعمود كله a=random.randint(0,10,(3,3)) b=count_nonzero(a>5,axis=0) c=count_nonzero(a<5,axis=1) print(a) # [[4 9 7] # [0 0 4] # [1 8 9]] print(b) # [0 2 2] print(c) # [1 3 1] # لمعرفة هل فيه رقم اكبر او اصغر a=random.randint(0,10,(3,3)) b=any(a>7) print(a) # [[8 6 4] # [5 8 9] # [6 6 6]] print(b) # True # ويمكن عملها في كل عمود a=random.randint(0,10,(3,3)) b=any(a>7,axis=0) print(a) # [[3 2 5] # [9 9 0] # [4 0 5]] print(b) # [ True True False] # او صف a=random.randint(0,10,(3,3)) b=any(a>7,axis=1) print(a) # [[7 2 9] # [3 4 2] # [6 6 9]] print(b) # [ True False True] # ويمكن معرفة هل كل العناصر شرط معين a=random.randint(0,10,(3,3)) b=all(a>7,axis=1) print(a) # [[0 3 4] # [9 0 4] # [3 7 5]] print(b) # [False False False] # ويمكن معرفة هل العناصر اكبر من او اصغر من رقم معين a=random.randint(0,10,size=6).reshape(2,3) b=a>5 c=a<5 print(a) # [[4 5 0] # [8 8 1]] print(b) # [[False False False] # [ True True False]] print(c) # [[ True False True] # [False False True]] a=arange(6).reshape(2,3) b=arange(6).reshape(2,3) c=a**2 d=isclose(a,b,rtol=0.2) e=isclose(a,c,rtol=0.2) print(a) # [[0 1 2] # [3 4 5]] print('------------------') print(b) # [[0 1 2] # [3 4 5]] print('------------------') print(c) # [[ 0 1 4] # [ 9 16 25]] print('------------------') print(d) # [[ True True True] # [ True True True]] print('------------------') print(e) # [[ True True False] # [False False False]] # يمكن ضرب قيم المصفوفة في بعضها a=arange(3) print(a) # [0 1 2] print(multiply(a,10)) # [ 0 10 20] # لرفع كل العناصر للأس الرابع a=arange(3) print(a) # [0 1 2] print(power(a,4)) # [ 0 1 16]
6b0d985ac417982931eda6955c6e1081bd5b600d
BizShuk/code_sandbox
/python/test_sort.py
365
3.75
4
from functools import cmp_to_key def s(c,d): print(c,d) print(c['a'],d['a']) if c['a'] > d['a'] or (c['a'] == d['a'] and c['b'] < d['b']): return 1 if c['a'] < d['a'] or (c['a']==d['a'] and c['b']>d['b']): return -1 return 1 a= [{'a':3,'b':4},{'a':4,'b':3},{'a':3,'b':5}] a= sorted(a,key=cmp_to_key(s)) print(a)
adac6fb79f124e14675f9f1ffec1544180614193
AndersonBatalha/Programacao1
/Estrutura de Decisão/decisão-02.py
290
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 2. Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. while True: numero = float(raw_input("Número: ")) if numero > 0: print "Positivo." elif numero < 0: print "Negativo." else: print "Zero."
58223e30daa64dbf4af72dd63fc6e0fc5fdca275
anastasiabya/python-tasks
/hometask4.py
3,821
3.921875
4
########################################## # TODO задание 1 ########################################## """Переделать приведенный for""" print("Результат задания 1 - списки должны совпасть!") l = [] for i in range(3, 23, 2): l.append(i) new_l=[] new_l = [i for i in range(3, 23, 2)] print(new_l) print(l) print(new_l == l) ########################################## # конец задания ########################################## ########################################## # TODO задание 2 ########################################## """Переделать приведенный for""" print("Результат задания 2 - списки должны совпасть!") l = [] for i in range(12): l.append(2**i + 1) new_l=[] new_l = [2**i+1 for i in range(12)] print(new_l) print(l) print(new_l == l) ########################################## # конец задания ########################################## ########################################## # TODO задание 3 ########################################## """Переделать приведенный for""" print("Результат задания 3 - списки должны совпасть!") old_l = [1, 3, 1, 3, 5, 2, 5, 6] l = [] for i in old_l: l.append(i-16) new_l = [] new_l=[i-16 for i in old_l] print(new_l) print(l) print(new_l == l) ########################################## # конец задания ########################################## ########################################## # TODO задание 4 ########################################## """Переделать приведенный for""" print("Результат задания 4 - списки должны совпасть!") old_l = [1, 3, 1, 3, 5, 2, 5, 6] l = [] for i in old_l: l.append(13) new_l = [] new_l = [13 for _ in old_l] print(new_l) print(l) print(new_l == l) ########################################## # конец задания ########################################## """ Переделывать в генератор списков из существующего for проще, чем писать свои генераторы с нуля, но и это тоже возможно, потренируемся """ ########################################## # TODO задание 5 ########################################## """Напишите генератор, создающий список, состоящих из 2оек""" print("Результат задания 5.1") # здесь ваш код l = [2 for _ in range(10)] print(l) ########################################## # конец задания ########################################## ########################################## # TODO задание 5 ########################################## """Напишите генератор, создающий список, состоящих из чисел кратных 5 [5,10,15,20,25,30]""" print("Результат задания 5.2") # здесь ваш код l = [i for i in range(5, 36, 5)] print(l) ########################################## # конец задания ########################################## ########################################## # TODO задание 6 ########################################## """СОздайте список состоящий из степенй двойки""" print("Результат задания 6") # здесь ваш код l = [2**i for i in range(10)] print(l) ########################################## # конец задания ##########################################
dfa4ab7e69d0d408c0f0edd821a340aebf34e474
jia3857/doubledrops
/MC/py/minecraft-cubes-and-towers.py
2,679
4.03125
4
""" Make cubes and towers in Minecraft, with Python. Really fun way to introduce a kid to Python (or yourself to Minecraft, as I've learned). Setup instructions for Minecraft + macOS + Python: https://gist.github.com/noahcoad/fc9d3984a5d4d61648269c0a9477c622 Additional setup: - Activate correct Java version: `export JAVA_HOME=`/usr/libexec/java_home -v 11.0.5`` - Activate spigot `cd spigot; java -jar spigot.jar` - Open Minecraft, make installation of v13.0.1, go into Multiplayer, join server `localhost`, and then run this script API doc here for more functionality: https://www.stuffaboutcode.com/p/minecraft-api-reference.html """ import mcpi.minecraft as minecraft import mcpi.block as block import mcpi.entity as entity # get game mc = minecraft.Minecraft.create() # get your current position and use to place objects entityIds = mc.getPlayerEntityIds() me = mc.entity.getPos(entityIds[0]) origin = (me.x, me.y, me.z) # Make a solid cube of material def cube(cubeSize, blockType, offsetXZ=5, offsetY=-5): if cubeSize <= 250: for x in range(0,cubeSize): for z in range(0,cubeSize): for y in range(0,cubeSize): mc.setBlock(origin[0]+x+offsetXZ, origin[1]+y+offsetY, origin[2]+z+offsetXZ, blockType) else: print("Sorry, that's too much! Making a lil' water cube instead.") cube(5, block.WATER.id) # make cube() function create a big block of Lava. Also try: AIR, WATER, LAVA, and more! # give offsetXZ of 15 so it's nearby but not on you. Try to offset to negative values so it's around you (be careful to not die)! cube(10, block.LAVA.id,15) ## uncomment the line below to knock out (almost) everything around you and be in a big pit: # cube(20, block.AIR.id,-10, -5) # Make a hollow tower around your character (can be much bigger than cube without crashing performance) def makeTower(squareSize, height, blockType, aboveGround=0): half = squareSize/2 for y in range(0, height): for x in range(0,squareSize): for z in range(0,squareSize): print "\n" xPos, yPos, zPos = origin[0]+x-half, origin[1]+y+aboveGround, origin[2]+z-half if x == 0 or x == (squareSize-1): # print("make x block", origin[0]+x, origin[1]+y, origin[2]+z) # if you need to debug # print("x,z: ", x, z) # if you need to debug mc.setBlock(xPos, yPos, zPos, blockType) elif z == 0 or z == (squareSize-1): # print("make z block", origin[0]+x, origin[1]+y, origin[2]+z) # if you need to debug # print("x,z: ", x, z) # if you need to debug mc.setBlock(xPos, yPos, zPos, blockType) # Make big tower of diamond around yourself. Make 4 units above you. makeTower(10, 50, block.DIAMOND_BLOCK.id, 4)
bbabc35363cda5d3dc0753bd1c175c6b8e6fd009
Pfeffer-Hu/numpytest
/np_clip.py
237
3.53125
4
""" Ҳ˵clipеԪa_min, a_max֮䣬a_maxľʹ a_maxСa_min,ľʹa_min """ import numpy as np x=np.array([1,2,3,5,6,7,8,9]) np.clip(x,3,8)
578ed6c95e2075f834eaa84053f064f8afaf42c1
ramkishorem/pythonic
/session4_while_dict/04.py
1,187
4.46875
4
""" Know the language enough to write my own dictionary. So far, we saw to 'iterable(loopable)' data structures, lists and tuples. They have one key thing in common. They have integer indices. eg: [2], [-1], [1:7]... Let us see the limitation of that in some use cases. """ # Say, we want to store info about players in lists messi = ['Lionel Messi', 30, 'Argentina', 'Barcelona', 'Attacker'] ramos = ['Sergio Ramos', 33, 'Spain', 'Real Madrid', 'Defender'] # get Messi's country print(messi[2]) # get Ramos's club print(ramos[3]) """ This is not very desirable. We have to remember which index corresponds to which information. It is prone to errors when we add new players. Would you rather it be print(messi['country']) print(ramos['club']) ? isn't this more readable and make more sense? we can use dictionaries to do that. """ messi = { 'name': 'Lionel Messi', 'age': 30, 'country': 'Argentina', 'club': 'Barcelona', 'position': 'Attacker', } ramos = { 'name': 'Sergio Ramos', 'age': 33, 'country': 'Spain', 'club': 'Real Madrid', 'position': 'Defender', } print(messi['country']) # Output: Argentina print(ramos['club']) # Output: Real Madrid
ebe23c916d70d8411bb9e1b0855e4b4fe21da66d
YashwanthCS/individual-string-count
/Count.py
399
3.9375
4
import operator def most_frequent(string): res={} for letter in string.lower(): if not letter.isalpha(): continue elif letter in res: res[letter]+=1 else: res[letter]=1 return res string=str(input("Enter your string here : ")) op=most_frequent(string) a=sorted(op.items(), key=operator.itemgetter(1), reverse=True) print(a)
aa616db476041a19ffb08b1e76545de35fe63967
basilije/CIS104
/main2.py
375
3.765625
4
from calc import calculator first_text = "" operations = ["+", "-", "*", "/", "^"] while True: calculation_text = first_text + input("Enter your calculation: " + first_text) for o in operations: if len(calculation_text.split(o)) == 2: first_text = str(calculator(float(calculation_text.split(o)[0]), float(calculation_text.split(o)[1]), o))
c32748105950f61cf2b0d571eeafa1ea0654da9a
sqq0216/testLearn
/pythonLearn/python/test/hignfunc.py
232
3.5
4
# 返回函数 def count(): fs = [] for i in range(1, 4): def f(): return i * i fs.append(f) return fs if __name__ == "__main__": f1, f2, f3 = count() print(f1(),f2(),f3())
304ebebb813fd74d378828b007601f99971c82bd
Psingh12354/Python-practice
/MergeDict.py
145
3.859375
4
def merge(dict1,dict2): return(dict2.update(dict1)) dict1={1:'Pk',2:'FK'} dict2={3:'ds',4:'fr'} print(merge(dict1,dict2)) print(dict2)
5ba484b433727b7a8964ee20b0081d682aeca5c6
Devraj789/python-files
/a/Basic/server.py
1,875
3.859375
4
''' Definition: A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the server. steps for connection: 1. server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request. 2. The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system. 3. If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client. 4. On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. ''' import socket s = socket.socket() host = socket.gethostname() port = 12345 s.bind((host,port)) s.listen(5) # wait for client connection while True: c,addr = s.accept() print ('Got conection from: ',addr) c.send(b'Thanks for conecting') c.close()
06765359e7c0fe14baa07e4869e3d324bbfe6c84
HarrisonMc555/adventofcode
/2020/day04a.py
828
3.921875
4
#!/usr/bin/env python3 INPUT_FILE = 'input04.txt' REQUIRED_KEYS = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] def main(): with open(INPUT_FILE) as f: text = f.read() passports = parse_passports(text) print(count_valid_passports(REQUIRED_KEYS, passports)) def parse_passports(text): passports_text = text.split('\n\n') return [parse_passport(pt) for pt in passports_text] def parse_passport(passport_text): pairs = passport_text.split() return dict(pair.split(':') for pair in pairs) def count_valid_passports(required_keys, passports): valids = [is_valid_passport(required_keys, p) for p in passports] return valids.count(True) def is_valid_passport(required_keys, passport): return all(key in passport for key in required_keys) if __name__ == '__main__': main()
dbe9514390279ed2e9eeb54b702913b1ac2b1c34
diego-vicente/machine-learning
/3/dogs.py
915
3.828125
4
import numpy as np import matplotlib.pyplot as plt import random # Create a population of 500 greyhounds and 500 labradours greyhounds = 500 labs = 500 # Greyhounds will be 4 inches taller in average, and the population will have # 4 inches of deviation. grey_height = 28 + 4 * np.random.randn(greyhounds) lab_height = 24 + 4 * np.random.randn(labs) # We can visualize the population in a histogram. Greyhounds will be red, and # labradours will be blue. You can check out the png in the file saved plt.figure(0) plt.hist([grey_height, lab_height], stacked=True, color=['r', 'b']) plt.savefig("good-attribute.png") # To simulate the eye-color property, we can use coin-flipping grey_eyes = [random.randint(0, 1) for x in range(greyhounds)] labs_eyes = [random.randint(0, 1) for x in range(labs)] plt.figure(1) plt.hist([grey_eyes, labs_eyes], stacked=True, color=['r', 'b']) plt.savefig("bad-attribute.png")
bd8e0e2d4c89efd85052f34a8d3c1c846d69d3a6
seoyoungsoo/CodingTest-Python
/Programmers/Lv1/lv1_문자열내림차순으로배치하기.py
277
3.546875
4
# 문자열 내림차순으로 배치하기 def solution(s): str = "" s_s = sorted(s, reverse=True) for i in s_s: str += i return str # 다른 풀이 def sol(s): return ''.join(sorted(s, reverse=True)) # testcase 1 s = "Zbcdefg" print(sol(s))
24be7127abedf027c838125400e0147e0b99f480
herojelly/Functional-Programming
/Chapter 3/3.8.py
253
3.8125
4
def main(): import math print("This program finds the Gregorian epact.") year = eval(input("Enter the year: ")) C = year//100 epact = (8 + (C//4) - C + ((8 * C + 13)//25) + 11 * (year%19))%30 print("The epact is", epact) main()
a2e76490be937473c4419655eb21aefe26ec0ff9
lopz82/exercism-python
/anagram/anagram.py
306
3.78125
4
from collections import Counter from typing import List def find_anagrams(word: str, candidates: List[str]) -> List[str]: return [ candidate for candidate in candidates if Counter(candidate.lower()) == Counter(word.lower()) and candidate.lower() != word.lower() ]
e128b8028afd6212799ada48f547a51f23629a05
RenatoDeAquino/DSlayer
/char.py
462
3.765625
4
from os import stat import random name = input("Digite o nome do seu personagem\n>") status = { 'força': random.randint(1, 10), 'agilidade': random.randint(1, 10), 'destreza': random.randint(1, 10), 'respiração': 0, "vitalidade": random.randint(1, 10) } inventario = { "armas": [], "utilitarios": [], "moedas": 10 } print(f'seja bem vindo {name} seus status são') for x in status: print(x, status[x])
dc1c5128f605d96b1824fa5f5f1cdf156d8de41a
Yobretaw/AlgorithmProblems
/EPI/Python/Searching/12_5_search_sorted_array_of_unknown_length.py
1,881
3.703125
4
import sys import os import math import imp import random """ Design an algorithm that takes a sorted array whose length is not known, and a key, and returns an index of an array element which is equal to the key. Assume that an out-of-bounds access throws an exception. """ class MyList(list): def at(self, idx): if idx >= len(self): raise Exception('Invalid Index') return self[idx] def search_sorted_array_of_unknown_length(arr, k): p = 0 while True: try: idx = (1 << p) - 1 if arr.at(idx) == k: return idx elif arr.at(idx) > k: break except Exception: break p += 1 # binary search between indices 2^(p - 1) and 2^p - 2 l, r = 1 << (p - 1), (1 << p) - 1 while l <= r: mid = l + (r - l) / 2 try: if arr.at(mid) == k: return k elif arr.at(mid) > k: r = mid else: l = mid + 1 except Exception: r = mid return -1 #def search_sorted_array_of_unknown_length(l, k): # i = 1 # while True: # try: # v = l.at(i) # if v == k: # return i # elif v < k: # i *= 2 # else: # return binary_search(l, k) # except Exception: # i -= 1 # return -1 #def binary_search(arr, k): # n = len(arr) # if not n: # return -1 # l, r = 0, n # while l < r: # mid = l + (r - l) / 2 # if arr.at(mid) == k: # return mid # elif arr.at(mid) > k: # r = mid # else: # l = mid + 1 # return -1 l = MyList([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for i in range(len(l)): print search_sorted_array_of_unknown_length(l, i)
56467dd6088cf59718abab7dd0a092f79c72737d
RodrigoMSCruz/CursoEmVideo.com-Python
/Aulas/ex004.py
471
3.859375
4
algumtexto = input('Digite algo: ') print('{} é alfabético: {}.'.format(algumtexto, algumtexto.isalpha())) print('{} é numérico: {}.'.format(algumtexto, algumtexto.isnumeric())) print('{} é caixa alta: {}.'.format(algumtexto, algumtexto.isupper())) print('{} é caixa baixa: {}'.format(algumtexto, algumtexto.islower())) print('{} está capitalizada: {}'.format(algumtexto, algumtexto.istitle())) print('{} tem espaço: {}'.format(algumtexto, algumtexto.isspace()))
d82ce7ed1d5d48b21a1a37400437b1c1add14db5
alvarogomezmu/dam
/SistemasGestion/Python/2ev/Actividad1/Ejercicio01.py
692
3.640625
4
#_*_coding:utf-8_*_ ''' Escribir los numeros pares comprendidos entre el 1 y el 100 en un fichero y luego lo muestras ''' import os def comprobarFichero(f) : if (f, os.W_OK) : print 'Fichero OK, Escritura OK' elif (f, os.R_OK) : print 'Fichero OK, Lectura OK' else : print 'Fichero no OK' def escribirPares(f) : for i in range(100) : if i % 2 == 0 : f.write(str(i) + " ") # main # Escribimos en el fichero escribir = open('numeros.txt','w') comprobarFichero(escribir) escribirPares(escribir) escribir.close() comprobarFichero(escribir) # Leemos del fichero leer = open ('numeros.txt','r') comprobarFichero(leer) print leer.read() leer.close() comprobarFichero(leer)
1ea73710202fc343b4494e0075bd7a5271c86dff
Sanfengzhu/Leetcode-Python
/2/addTwoNumbers.py
1,364
3.765625
4
#You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. # Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) # Output: 7 -> 0 -> 8 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1: return l2 if not l2: return l1 def length(l): cur, count = l, 0 while cur: cur=cur.next count=count+1 return count c1, c2 = length(l1), length(l2) if c1 < l2: l1, l2 = l2, l1 x=0 head=pre=l1 while l2: temp=l1.val+l2.val+x l1.val=temp%10 x=temp/10 pre=l1 l1=l1.next l2=l2.next while l1 and x: temp = l1.val+x l1.val=temp%10 x=temp/10 pre=l1 l1=l1.next if not l1 and x: pre.next=ListNode(x) return head
89830af8b279894342095a341c9fbb6a93108e77
CodecoolGlobal/lightweight-erp-python-cumpanasi
/store/store.py
5,354
3.5
4
""" Store module Data table structure: * id (string): Unique and random generated identifier at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters) * title (string): Title of the game * manufacturer (string) * price (number): Price in dollars * in_stock (number) """ # everything you'll need is imported: # User interface module import ui # data manager module import data_manager # common module import common title_list = ["id", "title", "manufacturer", "price", "in_stock"] file_game = 'store/games.csv' def start_module(): """ Starts this module and displays its menu. * User can access default special features from here. * User can go back to main menu from here. Returns: None """ options_list = ["Show table", "Add", "Remove", "Update", "Get counts by manufacturers", "Get avarage by manufacturers"] while True: table = data_manager.get_table_from_file(file_game) ui.print_menu("Store manager menu", options_list, "Back to Main Menu") inputs = ui.get_inputs(["Please enter a number: "], "") option = inputs[0] if option == "1": ui.print_table(table, title_list) elif option == "2": add(data_manager.get_table_from_file(file_game)) elif option == "3": ID = ui.get_inputs(["ID"], "give me the ID: ") remove(data_manager.get_table_from_file(file_game ),ID[0]) elif option =="4": ID = ui.get_inputs(["ID"], "give me the ID: ") update(data_manager.get_table_from_file(file_game ),ID[0]) elif option =="5": result = get_counts_by_manufacturers(data_manager.get_table_from_file(file_game )) ui.print_result(result,"The manufacturers are") elif option == "6": manufacturer = ui.get_inputs(["manufacturer"], "Give me the manufacturer") result = get_average_by_manufacturer(data_manager.get_table_from_file(file_game),manufacturer[0]) ui.print_result(result,"The average amount of games in stock is") elif option == "0": break else: raise KeyError("There is no such option.") # your code def show_table(table): """ Display a table Args: table (list): list of lists to be displayed. Returns: None """ # your code def add(table): """ Asks user for input and adds it into the table. Args: table (list): table to add new record to Returns: list: Table with a new record """ # your code new_record = ui.get_inputs(["title", "manufacturer", "price", "in_stock"], "") new_record.insert(0, common.generate_random(table)) table.append(new_record) data_manager.write_table_to_file(file_game, table) modiefied_games = data_manager.get_table_from_file(file_game) return modiefied_games def remove(table, id_): """ Remove a record with a given id from the table. Args: table (list): table to remove a record from id_ (str): id of a record to be removed Returns: list: Table without specified record. """ # your code for game in table: if game[0] == id_: table.remove(game) data_manager.write_table_to_file(file_game, table) modiefied_games = data_manager.get_table_from_file(file_game) return modiefied_games def update(table, id_): """ Updates specified record in the table. Ask users for new data. Args: table: list in which record should be updated id_ (str): id of a record to update Returns: list: table with updated record """ # your code new_data = ui.get_inputs(["title", "manufacturer", "price", "in_stock"],"please give me the details") new_data.insert(0, id_) for game in range(len(table)): if table[game][0] == id_: table[game] = new_data data_manager.write_table_to_file(file_game, table) modified_games = data_manager.get_table_from_file(file_game) return modified_games # special functions: # ------------------ def get_counts_by_manufacturers(table): """ Question: How many different kinds of game are available of each manufacturer? Args: table (list): data table to work on Returns: dict: A dictionary with this structure: { [manufacturer] : [count] } """ manufacturers = {} for game in table: manufacturers[game[2]] = manufacturers.get(game[2],0)+1 return manufacturers # your code def get_average_by_manufacturer(table, manufacturer): """ Question: What is the average amount of games in stock of a given manufacturer? Args: table (list): data table to work on manufacturer (str): Name of manufacturer Returns: number """ average = [] sum_sales = 0 one_manufacture_occurance = 0 for game in table: if game[2].lower() == manufacturer.lower(): one_manufacture_occurance += 1 sum_sales += int(game[4]) average.append(sum_sales / one_manufacture_occurance) return average # your code
04ffbb6a85d0f39e7a43926fd5a9c6621688257c
gddickinson/python_code
/geoPython_tutorial/geoPython_tutorial_2 2.py
4,100
3.78125
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 29 13:20:20 2020 @author: g_dic https://automating-gis-processes.github.io/2016/Lesson2-geopandas-basics.html """ # Import necessary modules import geopandas as gpd # Set filepath (fix path relative to yours) fp = r"C:\Users\g_dic\Documents\geoPython_tutorial\Data\DAMSELFISH_distributions.shp" # Read shapefile using gpd.read_file() data = gpd.read_file(fp) print(type(data)) #table head data.head() #simple plotting data.plot(); #coordinate reference system data.crs #write a new shapefile # Create a output path for the data out = r"C:\Users\g_dic\Documents\geoPython_tutorial\Data\DAMSELFISH_distributions_SELECTION.shp" # Select first 50 rows selection = data[0:50] # Write those rows into a new Shapefile (the default output file format is Shapefile) selection.to_file(out) #plot selection.plot(); # It is possible to use only specific columns by specifying the column name within square brackets [] data['geometry'].head() # Make a selection that contains only the first five rows selection = data[0:5] #We can iterate over the selected rows using a specific .iterrows() -function in (geo)pandas for index, row in selection.iterrows(): poly_area = row['geometry'].area print("Polygon area at index {0} is: {1:.3f}".format(index, poly_area)) # Empty column for area data['area'] = None # Iterate rows one at the time for index, row in data.iterrows(): # Update the value in 'area' column with area information at index data.loc[index, 'area'] = row['geometry'].area data['area'].head(2) # Maximum area max_area = data['area'].max() # Minimum area min_area = data['area'].mean() print("Max area: %s\nMean area: %s" % (round(max_area, 2), round(min_area, 2))) #Creating geometries into a GeoDataFrame # Import necessary modules first import pandas as pd import geopandas as gpd from shapely.geometry import Point, Polygon import fiona # Create an empty geopandas GeoDataFrame newdata = gpd.GeoDataFrame() newdata # Create a new column called 'geometry' to the GeoDataFrame newdata['geometry'] = None # Coordinates of the Helsinki Senate square in Decimal Degrees coordinates = [(24.950899, 60.169158), (24.953492, 60.169158), (24.953510, 60.170104), (24.950958, 60.169990)] # Create a Shapely polygon from the coordinate-tuple list poly = Polygon(coordinates) # Let's see what we have poly # Insert the polygon into 'geometry' -column at index 0 newdata.loc[0, 'geometry'] = poly # Let's see what we have now newdata # Add a new column and insert data newdata.loc[0, 'Location'] = 'Senaatintori' # Let's check the data newdata # Import specific function 'from_epsg' from fiona module to add CRS from fiona.crs import from_epsg # Set the GeoDataFrame's coordinate system to WGS84 (epsg code: 4326) newdata.crs = from_epsg(4326) # Let's see how the crs definition looks like newdata.crs # Determine the output path for the Shapefile outfp = r"C:\Users\g_dic\Documents\geoPython_tutorial\Data\Senaatintori.shp" # Write the data into that Shapefile newdata.to_file(out) #Grouping data data = gpd.read_file(fp) #list columns #for col in data.columns: # print(col) # Group the data by column 'binomial' grouped = data.groupby('BINOMIAL') # Let's see what we got grouped # Iterate over the group object for key, values in grouped: individual_fish = values individual_fish type(individual_fish) print(key) # Determine outputpath outFolder = r"C:\Users\g_dic\Documents\geoPython_tutorial\Data" # Create a new folder called 'Results' (if does not exist) to that folder using os.makedirs() function import os resultFolder = os.path.join(outFolder, 'Results') if not os.path.exists(resultFolder): os.makedirs(resultFolder) # Iterate over the for key, values in grouped: # Format the filename (replace spaces with underscores) outName = "%s.shp" % key.replace(" ", "_") # Print some information for the user print("Processing: %s" % key) # Create an output path outpath = os.path.join(resultFolder, outName) # Export the data values.to_file(outpath)
348f881a06e1606fee4864c2822f4854b6a7c350
ramya42043/RAMYA_VT_WORK
/Knowledge/VTpython/PRacPy/1_A4.py
408
3.84375
4
#!/usr/bin/python mylist=[] num=input("Please enter the numbers or 0 to exit : ") while(num!=0): mylist.append(num) num=input("Please enter the numbers or 0 to exit : ") print mylist len1=len(mylist) index=0 num=0 print len1 while(num<len1): if(mylist[index]<0): ele=mylist.pop(index) print ele mylist.append(ele) print "\n",mylist index -=1 num +=1 index +=1 print "Given list is : ",mylist
1cbd798a0dd4aaf9b928edaa691f6735c3886498
lxyshuai/leetcode
/559. Maximum Depth of N-ary Tree.py
1,766
4.25
4
""" Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. For example, given a 3-ary tree: We should return its max depth, which is 3. Note: The depth of the tree is at most 1000. The total number of nodes is at most 5000. """ # Definition for a Node. class Node(object): def __init__(self, val, children=[]): self.val = val self.children = children # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def maxDepth(self, root): """ :type root: Node :rtype: int """ if root is None: return 0 if root.children == []: return 1 max_depth = -float('inf') for child in root.children: max_depth = max(max_depth, self.maxDepth(child)) return max_depth + 1 class Solution(object): def maxDepth(self, root): """ :type root: Node :rtype: int """ if root is None: return 0 stack = [] stack.append((1, root)) max_depth = 1 while stack: depth, current_node = stack.pop() max_depth = max(max_depth, depth) for children in current_node.children: stack.append((depth + 1, children)) return max_depth if __name__ == '__main__': node1 = Node(1) node2 = Node(3) node3 = Node(2) node4 = Node(4) node5 = Node(5) node6 = Node(6) node1.children = [node2, node3, node4] node2.children = [node5, node6] print Solution().maxDepth(node1)
ea9df7d7b6e29216bea2c1f7124196332795be4d
SandhyaKamisetty/CSPP-1
/cspp1-practice/m3/iterate_even_reverse.py
207
4.59375
5
''' @author : SandhyaKamisetty The program prints even reverse using while loop ''' print('Hello!') i = 10 while i >= 2: print(i) i = i-2 print('Hello!') for A in range(10, 0, -2): print(A)
270c813029cfeb9f1f70a76a4d4ecae3ce3ecfac
woodsleaf/matrixpifagora
/matrix.py
11,874
3.53125
4
# -*- coding: utf-8 -*- import sys import os from tkinter import * import tkinter as tk import tkinter.ttk as ttk import tkinter.messagebox as messagebox from tkinter import Menu import re from functools import reduce import argparse parser = argparse.ArgumentParser(description='Enter birthday') parser.add_argument( '-d', '--birthday', default='01-01-1978', #'17-11-1991' help='provide an birthday -d=ddmmyyyy (default: 17-11-1991 )' ) parser.add_argument( '-n', '--fullname', default='LastnameNamePatronymic', help='provide an fullname -n=ФамилияИмяОтчество (default: LastnameNamePatronymic )' ) my_namespace = parser.parse_args() #print(my_namespace) fullname = my_namespace.fullname indata = my_namespace.birthday ''' 17-11-1991 30 3 28 10 171119913032810 [111111][][7] [2][][8] [33][][99] ''' def findto(mychar, mystr): mychar= '[' + str(mychar) + ']' res = re.findall(mychar, mystr) return ''.join(res) #test: print(findto(1,'34241414')) def strsum(num): #print(num) num = list(str(num)) # str(num) #print(num) num = reduce((lambda sum, item: int(sum) + int(item)), num) #print(num) return num #test: strsum(25) def truegod(num): num = int(num) return (num >=10 and num <= 12) #return True if (num >=10 and num <= 12) else False #test: print(truegod(5)) def fwn(indata): return strsum(re.sub(r'[/.,;-]', '', indata)) #test: print(fwn(indata)) #from input to text def clickedBtn(): indata = lbl_birthday_value.get() main(indata) print(indata) return True def nd(fwnarr): res = fwnarr while (len(str(res)) != 1): res = strsum(res) print('NumDesteny = ', res) return res #Begin================================================== def main(indata): fwnarr = re.sub(r'[/.,;-]', '', indata) # строка ddmmyyyy numdesteny = nd(fwnarr) dmyarr = re.split(r'[/,.;-]', indata) # массив [dd, mm, yyyy] #check: print(fwnarr, ' ', dmyarr) day = str(int(dmyarr[0])) #Убираем из строки начальный ноль, чтобы в dayfirst был не ноль а число. dayfirst = int(list(day)[0]) #Формируется массив из чисел дня, если их больше одного, берется нулевой элемент check: print('first Number of day = ', dayfirst) year = dmyarr[2] #test: print("dmyarr: ", ''.join(dmyarr)) firstworknumber = fwn(indata) #test: print('WN1: ', firstworknumber) secondworknumber = 0 if (truegod(firstworknumber)): secondworknumber = firstworknumber else: secondworknumber = strsum(str(firstworknumber)) #test: print('WN2: ', secondworknumber) threeworknumber = 0 if (int(year) >= 2000): #после 2000 включительно threeworknumber = str(int(firstworknumber) + 19) else: threeworknumber = str(int(firstworknumber) - int(dayfirst)*2) #test: print('WN3: ', threeworknumber) fourworknumber = 0 if (truegod(threeworknumber)): fourworknumber = threeworknumber else: fourworknumber = strsum(str(threeworknumber)) #test: print('WN4: ', fourworknumber) print(fullname) print(indata) all = '' if (int(year) >= 2000): #после 2000 включительно print(firstworknumber, secondworknumber, '19', threeworknumber, fourworknumber) dopnum = firstworknumber, secondworknumber, '19', threeworknumber, fourworknumber all = ''.join(dmyarr) + str(firstworknumber) + str(secondworknumber) + '19' + str(threeworknumber) + str(fourworknumber) else: print(firstworknumber, secondworknumber, threeworknumber, fourworknumber) dopnum = firstworknumber, secondworknumber, threeworknumber, fourworknumber all = ''.join(dmyarr) + str(firstworknumber) + str(secondworknumber) + str(threeworknumber) + str(fourworknumber) print(all) print('[{}][{}][{}]'.format(findto(1, all),findto(4, all),findto(7, all)) ) print('[{}][{}][{}]'.format(findto(2, all),findto(5, all),findto(8, all)) ) print('[{}][{}][{}]'.format(findto(3, all),findto(6, all),findto(9, all)) ) print('Target =', len(findto(147, all))) print('Famile =', len(findto(258, all))) print('Stable. =', len(findto(369, all))) print('Samoocenka =', len(findto(123, all))) print('Money =', len(findto(456, all))) print('Talant =', len(findto(789, all))) print('Duhovnost =', len(findto(159, all))) print('Temperament =', len(findto(357, all))) lbl_dopnumbers_value['text'] = dopnum lbl_temperament_value['text'] = len(findto(357, all)) lbl_desteny_value['text'] = numdesteny lbl_character_value['text'] = findto(1, all) lbl_zdorovie_value['text'] = findto(4, all) lbl_udacha_value['text'] = findto(7, all) lbl_target_value['text'] = len(findto(147, all)) lbl_energy_value['text'] = findto(2, all) lbl_logika_value['text'] = findto(5, all) lbl_dolg_value['text'] = findto(8, all) lbl_family_value['text'] = len(findto(258, all)) lbl_interes_value['text'] = findto(3, all) lbl_trud_value['text'] = findto(6, all) lbl_memory_value['text'] = findto(9, all) lbl_privichki_value['text'] = len(findto(369, all)) lbl_samoocenka_value['text'] = len(findto(123, all)) lbl_money_value['text'] = len(findto(456, all)) lbl_talant_value['text'] = len(findto(789, all)) lbl_duhovnost_value['text'] = len(findto(159, all)) return True #Рисуем GUI (4 колонки/11строк) #1#Дата рождения /Значение /Темперамент(357) #2#Доп. числа /Значение /Значение #3#Число судьбы /Значение #4#Характер(1) /Здоровье(4) /Удача(7) /Цель(147) #5#значение /значение /значение /значение #6#Энергия(2) /Логика-интуиция(5) /Долг(8) /Семья(258) #7#значение /значение /значение /значение #8#Интерес(3) /Труд(6) /Память-Ум(9) /Привычки(369) #9#значение /значение /значение /значение #10#Самоценка(123) /Деньги(456) /Талант(789) /Духовность(159) #11#значение /значение /значение /значение window = Tk() #Заголовок окна window.title("Добро пожаловать в приложение matrix") #window.geometry('683x768') #Меню menu = Menu(window) new_item = Menu(menu) #, tearoff=0 new_item.add_command(label='Новый') new_item.add_separator() new_item.add_command(label='Открыть') new_item.add_separator() new_item.add_command(label='Изменить') menu.add_cascade(label='Файл', menu=new_item) window.config(menu=menu) #zero lbl_birthday = Label(window, text="Дата рождения", font=("Arial Bold", 18)) lbl_birthday.grid(column=0, row=0) lbl_birthday_value = Entry(window, width=10, font=("Arial", 14)) lbl_birthday_value.insert(INSERT, indata) lbl_birthday_value.focus() lbl_birthday_value.grid(column=1, row=0) btn = Button(window, command=clickedBtn, text="Вычислить", bg="white", fg="black") btn.grid(column=2, row=0) lbl_temperament = Label(window, text="Темперамент(357)", font=("Arial", 18)) lbl_temperament.grid(column=3, row=0) #one lbl_dopnumbers = Label(window, text="Доп числа", font=("Arial Bold", 18)) lbl_dopnumbers.grid(column=0, row=1) lbl_dopnumbers_value = Label(window, text="1st, 2st, 3st, 4st", font=("Arial", 14)) lbl_dopnumbers_value.grid(column=1, row=1) lbl_temperament_value = Label(window, text="value", font=("Arial", 14)) lbl_temperament_value.grid(column=3, row=1) #two lbl_desteny = Label(window, text="Число судьбы", font=("Arial Bold", 18)) lbl_desteny.grid(column=0, row=2) lbl_desteny_value = Label(window, text="value", font=("Arial", 14)) lbl_desteny_value.grid(column=1, row=2) #three lbl_character = Label(window, text="Характер(1)", font=("Arial Bold", 18)) lbl_character.grid(column=0, row=3) lbl_zdorovie = Label(window, text="Здоровье(4)", font=("Arial Bold", 18)) lbl_zdorovie.grid(column=1, row=3) lbl_udacha = Label(window, text="Удача(7)", font=("Arial Bold", 18)) lbl_udacha.grid(column=2, row=3) lbl_target = Label(window, text="Цель(147)", font=("Arial Bold", 18)) lbl_target.grid(column=3, row=3) lbl_character_value = Label(window, text="value", font=("Arial", 14)) lbl_character_value.grid(column=0, row=4) lbl_zdorovie_value = Label(window, text="value", font=("Arial", 14)) lbl_zdorovie_value.grid(column=1, row=4) lbl_udacha_value = Label(window, text="value", font=("Arial", 14)) lbl_udacha_value.grid(column=2, row=4) lbl_target_value = Label(window, text="value", font=("Arial", 14)) lbl_target_value.grid(column=3, row=4) #five lbl_energy = Label(window, text="Энергия(2)", font=("Arial Bold", 18)) lbl_energy.grid(column=0, row=5) lbl_logika = Label(window, text="Логика(5)", font=("Arial Bold", 18)) lbl_logika.grid(column=1, row=5) lbl_dolg = Label(window, text="Долг(8)", font=("Arial Bold", 18)) lbl_dolg.grid(column=2, row=5) lbl_family = Label(window, text="Семья(258)", font=("Arial Bold", 18)) lbl_family.grid(column=3, row=5) lbl_energy_value = Label(window, text="value", font=("Arial", 14)) lbl_energy_value.grid(column=0, row=6) lbl_logika_value = Label(window, text="value", font=("Arial", 14)) lbl_logika_value.grid(column=1, row=6) lbl_dolg_value = Label(window, text="value", font=("Arial", 14)) lbl_dolg_value.grid(column=2, row=6) lbl_family_value = Label(window, text="value", font=("Arial", 14)) lbl_family_value.grid(column=3, row=6) #seven lbl_interes = Label(window, text="Интерес(3)", font=("Arial Bold", 18)) lbl_interes.grid(column=0, row=7) lbl_trud = Label(window, text="Труд(6)", font=("Arial Bold", 18)) lbl_trud.grid(column=1, row=7) lbl_memory = Label(window, text="Память(9)", font=("Arial Bold", 18)) lbl_memory.grid(column=2, row=7) lbl_privichki = Label(window, text="Привычки(369)", font=("Arial Bold", 18)) lbl_privichki.grid(column=3, row=7) lbl_interes_value = Label(window, text="value", font=("Arial", 14)) lbl_interes_value.grid(column=0, row=8) lbl_trud_value = Label(window, text="value", font=("Arial", 14)) lbl_trud_value.grid(column=1, row=8) lbl_memory_value = Label(window, text="value", font=("Arial", 14)) lbl_memory_value.grid(column=2, row=8) lbl_privichki_value = Label(window, text="value", font=("Arial", 14)) lbl_privichki_value.grid(column=3, row=8) #nine lbl_samoocenka = Label(window, text="Самооценка(123)", font=("Arial Bold", 18)) lbl_samoocenka.grid(column=0, row=9) lbl_money = Label(window, text="Деньги(456)", font=("Arial Bold", 18)) lbl_money.grid(column=1, row=9) lbl_talant = Label(window, text="Талант(789)", font=("Arial Bold", 18)) lbl_talant.grid(column=2, row=9) lbl_duhovnost = Label(window, text="Духовность(159)", font=("Arial Bold", 18)) lbl_duhovnost.grid(column=3, row=9) lbl_samoocenka_value = Label(window, text="value", font=("Arial", 14)) lbl_samoocenka_value.grid(column=0, row=10) lbl_money_value = Label(window, text="value", font=("Arial", 14)) lbl_money_value.grid(column=1, row=10) lbl_talant_value = Label(window, text="value", font=("Arial", 14)) lbl_talant_value.grid(column=2, row=10) lbl_duhovnost_value = Label(window, text="value", font=("Arial", 14)) lbl_duhovnost_value.grid(column=3, row=10) main(indata) # must be end window.mainloop()
87d334dd48f6801396d8e9c5b4e249173585b35e
c2huc2hu/Isometric-Game
/map.py
1,346
3.796875
4
from tile import Tile class Map(): def __init__(self, map_width, map_height): self.tiles = [[Tile(x, y, Tile.PLAIN) for y in range (map_height)] for x in range (map_width)] self.width = map_width self.height = map_height #Overloading get, set, iter and next to allow its use as a 2d iterable. def __getitem__ (self, key): """Get the tile at given coordinates. Key is a x,y pair.""" return self.tiles [key[0]] [key[1]] def __setitem__ (self, key, value): """Set the tile at the given coordinates. Key is an x,y pair""" self.tiles [key[0]] [key[1]] = value def all_cells(self): """Generator returning all cells""" for row in self.tiles: for tile in row: yield tile def __str__ (self): res = "" for x in range (self.width): for y in range (self.height): res += self.tiles [x][y].to_tile() + ' ' res += '\n' return res if __name__ == '__main__': print ("==TESTING MAP CLASS==") m = Map(5, 10) m[4, 2].terrain_type = Tile.WATER #accessing cell assert m[4,2] == Tile.WATER a = 0 for i in m.all_cells(): #iterate through every cell print (i.x, i.y) a += 1 assert a == 50 print (m)
6123de7078ed83df9616cee9923474e74fca327c
LinuxKernelDevelopment/algs_py
/ch4/DepthFirstPath/DepthFirstPaths.py
1,508
3.59375
4
#!/home/hmsjwzb/python/bin/python3.5 import sys from In import In from Graph import Graph class DepthFirstSearch: def __init__(self, G, s): self.s = s self.edgeTo = [None] * G.Vertex() self.marked = [None] * G.Vertex() self.count = 0 self.dfs(G, s) def dfs(self, G, v): self.count += 1 self.marked[v] = True for w in G.adj[v]: if not self.marked[w]: self.edgeTo[w] = v self.dfs(G, w) def markedf(self, v): self.validateVertex(v) return self.marked[v] def countf(self): return self.count def hasPathTo(self, v): return self.marked[v] def pathTo(self, v): self.validateVertex(v) if not self.hasPahTo(v): return None path = [] for x in self.edgeTo[x]: path.push(x) path.push(self.s) return path def validateVertex(self, v): V = len(self.marked) if v < 0 or v >= V: raise Exception("vertex " + v + " is not between 0 and " + (V-1)) if __name__ == '__main__': myin = In(sys.argv[1], None) G = Graph(myin) s = int(sys.argv[2]) output = "" search = DepthFirstSearch(G, s) for v in range(0, G.Vertex()): if search.markedf(v): output += str(v) output += " " print(output) if search.countf() != G.Vertex(): print("Not connected\n") else: print("connected\n")
2c4bcc1f985b7eb61d2b4d996a7840bdb522922b
ghldbssla/Python
/프로그램 만들어보기/Quiz.py
554
3.875
4
#Quiz.py choice=0 while True: print("다음 중 프로그래밍 언어가 아닌것은?(종료하려면 0)") print("1.파이썬") print("2.Java") print("3.망둥어") print("4.C언어") choice=int(input("정답 입력 : ")) if(choice==3): result="정답입니다." elif(choice==1 or choice==2 or choice==4): result ="다시 한번 생각해보세요." elif(choice==0): #무한반복 탈출 break else: result= "잘못 입력하셨습니다." print(result)
14c037c311f6b8344010579b06d71a99a3526b36
zeebraa00/python_practice
/실습_8_4_국가별_무역수지_정렬.py
901
3.9375
4
# 파이썬 8일차 db = [] def enter() : a=input("국가명(종료:0) : ") if a=="0" : return else : b=int(input("수입 : ")) c=int(input("수출 : ")) db.append([a,[b,c,c-b]]) enter() def func1() : db.sort(key=lambda x:x[0]) # print(db) print("%s %s %s"%("국가명","수입액","수출액")) print("-----------------------") for i in range(len(db)) : print("%s %7d %7d"%(db[i][0],db[i][1][0],db[i][1][1])) print("") def func2() : db.sort(key=lambda x:x[1][2], reverse=True) # print(db) print("%s %s"%("국가명", "순이익")) print("-----------------------") for i in range(len(db)) : print("%s %7d"%(db[i][0],db[i][1][2])) print("") def oper() : a=int(input("1:국가순 정렬, 2:순이익순 정렬, 이외 : 종료 ")) if a==1 : func1() oper() elif a==2 : func2() oper() else : return enter() oper()
b05ee3f21cb0e4ce229e70208e3c5f1f8c3120a1
srengifo79/Tesis
/preguntas.py
8,314
3.625
4
# -*- coding: utf-8 -*- from random import randint import sys reload(sys) sys.setdefaultencoding('utf8') #Numero Antes def numeroAntes(minn, maxn): numero = randint(minn,maxn) pregunta = '¿Qué número está antes del ' + str(numero) + '?' respuesta = numero - 1 return [pregunta, respuesta, None] #Numero Despues def numeroDespues(minn, maxn): numero = randint(minn,maxn) pregunta = '¿Qué número esta después del número ' + str(numero) + '?' respuesta = numero + 1 return [pregunta, respuesta, None] #Numero Entre def numeroEntre(minn, maxn): numero1 = randint(minn,maxn) numero2 = numero1 + 2 pregunta = '¿Qué número está entre el número ' + str(numero1) + ' y el ' + str(numero2) + '?' respuesta = numero1 + 1 return [pregunta, respuesta, None] #Preguntas valor posicional def valorPosicional(persona, objeto, minn, maxn): numero = randint(minn,maxn) tamanoNumero = len(str(numero)) unidad = randint(1, tamanoNumero) if unidad < 2: valorPosicional, respuesta = 'Unidades' , int(str(numero)[tamanoNumero - 1]) elif unidad < 3: valorPosicional, respuesta = 'Decenas', int(str(numero)[tamanoNumero - 2])# + '0') elif unidad < 4: valorPosicional, respuesta = 'Centenas', int(str(numero)[tamanoNumero - 3])# + '00') else : valorPosicional, respuesta = 'Millares', int(str(numero)[tamanoNumero - 4])# + '000') if valorPosicional == 'Millares': cuanto = 'cuantos' else: cuanto = 'cuantas' if numero != 1: objeto = objeto + 's' listaModelosPreguntas = [ 'Si ' + persona + ' tiene ' + str(numero) + ' ' + objeto + ', ' + cuanto + ' ' + valorPosicional + ' de ' + objeto + ' tiene?', 'Si compro ' + str(numero) + ' ' + objeto + ', ' + cuanto + ' ' + valorPosicional + ' de ' + objeto + ' compre?', 'Si regalo ' + str(numero) + ' ' + objeto + ', ' + cuanto + ' ' + valorPosicional + ' de ' + objeto + ' regale?' ] indiceModeloPregunta = randint(0,len(listaModelosPreguntas) - 1) pregunta = listaModelosPreguntas[indiceModeloPregunta] imagen = "/static/svgs/" + objeto + ".svg" return [pregunta, respuesta, imagen] # Preguntas Restas def resta(persona, comida, minn, maxn): # Si <persona> tiene <numero> <comida> y se come <numero>, cuanta(s) <comida> le queda(n)? numero1 = randint(minn,maxn) numero2 = randint(1,numero1) respuesta = numero1-numero2 imagen = "/static/svgs/" + comida + ".svg" if comida[len(comida)-1] == 'a': cuanto = 'cuantas' else: cuanto = 'cuantos' if numero1 != 1: plural = 's' else: plural = '' listaModelosPreguntas = [ 'Si '+persona+' tiene '+str(numero1)+' '+comida+plural + ' y se come '+str(numero2)+', '+cuanto+' '+comida+'s'+' le quedan?', 'Si '+persona+' compra '+str(numero1)+' '+comida+plural + ' y luego vende '+str(numero2)+', '+cuanto+' '+comida+'s'+' le quedan?', 'Tengo '+str(numero1)+' '+comida+plural + ' y le regalo '+str(numero2)+' a '+persona+ ', ' +cuanto+' '+comida+'s'+' me quedan?' ] indiceModeloPregunta = randint(0,len(listaModelosPreguntas) - 1) pregunta = listaModelosPreguntas[indiceModeloPregunta] return [pregunta,respuesta,imagen] #Preguntas Sumas def suma(persona1, persona2, accion, accionPasado, minn, maxn): # <persona> <accion> <numero> veces, <persona2> <accion> <numero> veces mas que <persona>, cuantas veces <accionpasado> <persona2>? imagen = "/static/svgs/" + accion + ".svg" numero1 = randint(minn,maxn) if (numero1 + maxn) > 1000: maxn = 1000 - numero1 numero2 = randint(1,maxn) respuesta = numero1 + numero2 pregunta = 'Si ' + persona1 + ' ' + accion + ' ' + str(numero1) + ' metros y ' + persona2 + ' ' + str(numero2) + ' cuantos metros ' + accionPasado + ' entre los dos?' return [pregunta,respuesta,imagen] #Preguntas Multiplicaciones def multiplicacion(persona, objeto, minn, maxn): imagen = "/static/svgs/" + objeto + ".svg" numero1 = randint(1,maxn) if (numero1 * maxn) > 1000: maxn = int(1000 / numero1) numero2 = randint(1, maxn) if numero1 > 1: plural1 = 's' else: plural1 = '' if numero2 > 1: plural2 = 's' else: plural2 = '' respuesta = numero1 * numero2 listaModelosPreguntas = [ persona + ' tiene ' + str(numero1) + ' bolsos cada uno con ' + str(numero2) + ' ' + objeto + plural2 + ' dentro, cuantas ' + objeto + plural2 + ' compró ' + persona + '?', 'Si en una camioneta llevo ' + str(numero1) + ' cajas con ' + str(numero2) + ' ' + objeto + plural2 + ' cada una, ' + ' qué número de ' + objeto + plural2 + ' llevo?', persona + ' recoge ' + str(numero1) + ' ' + objeto + plural1 + ' cada dia, cúal es el número de ' + objeto + plural1 + ' que tendrá ' + persona + ' después de ' + str(numero2) + ' dias?' ] indiceModeloPregunta = randint(0,len(listaModelosPreguntas) - 1) pregunta = listaModelosPreguntas[indiceModeloPregunta] return [pregunta,respuesta,imagen] #Preguntas posicion numerica # def posicionNumericaA(persona, maxn): # numero1 = randint(1,maxn) # if randint(1, 2) == 1: antesDespues, respuesta = 'antes', numero1 - 1 # else: antesDespues, respuesta = 'despues ', numero1 + 1 # pregunta = persona + ' tiene el turno ' + str(numero1) + ' para jugar con el balon, que turno tiene la persona ' + antesDespues + ' que ' + persona + '?' # return [pregunta, respuesta] # def posicionNumericaB(persona1, persona2, persona3): # numero = 0 # if randint(1, 2) == 1: # numero = randint(1,10) # antesDespues, respuesta = numero + 2, numero + 1 # else: # numero = randint(3,12) # antesDespues, respuesta = numero - 2, numero - 1 # pregunta = 'Un tren que sale a cada hora, el cual ' + persona1 + ' lo toma a las ' + str(numero) + ' y ' + persona2 + ' toma el tren a las ' + str(antesDespues) + ' a que hora tomo el tren ' + persona3 + ' si salio entre ' + persona1 + ' y ' + persona2 +'?' # return [pregunta, respuesta] #Preguntas conjuntos def conjuntosIguales(animal1, animal2): totalConjuntoA = randint(1, 5) totalConjuntoB = randint(1, 5) pregunta = 'Hay dos manadas de animales, escúchalos y escribe si el número de animales en cada manada es diferente o es igual.' if totalConjuntoA != totalConjuntoB: respuesta = 'diferente' else: respuesta = 'igual' imagen = "/static/svgs/" + animal1 + ".svg" return [pregunta, respuesta, imagen , animal1, animal2, totalConjuntoA, totalConjuntoB] def conjuntoMayor(animal1, animal2): totalConjuntoA = randint(1, 5) totalConjuntoB = randint(1, 5) while totalConjuntoA == totalConjuntoB: totalConjuntoB = randint(1, 5) pregunta = 'Hay dos manadas de animales, escúchalos y escribe cual es el nombre del animal con mayor número' if totalConjuntoA > totalConjuntoB: respuesta = str(animal1) else: respuesta = str(animal2) imagen = "/static/svgs/" + animal1 + ".svg" return [pregunta, respuesta, imagen , animal1, animal2, totalConjuntoA, totalConjuntoB] def conjuntoMenor(animal1, animal2): totalConjuntoA = randint(1, 5) totalConjuntoB = randint(1, 5) while totalConjuntoA == totalConjuntoB: totalConjuntoB = randint(1, 5) pregunta = 'Hay dos manadas de animales, escúchalos y escribe cual es el nombre del animal con menor número' if totalConjuntoA < totalConjuntoB: respuesta = str(animal1) else: respuesta = str(animal2) imagen = "/static/svgs/" + animal1 + ".svg" return [pregunta, respuesta, imagen , animal1, animal2, totalConjuntoA, totalConjuntoB] def contarSonidos(animal1, animal2): totalConjuntoA = randint(1, 5) totalConjuntoB = randint(1, 5) pregunta = 'Dos animales cantan sin parar, cuenta cuantas veces cantan en total?' respuesta = totalConjuntoA + totalConjuntoB imagen = "/static/svgs/" + animal1 + ".svg" return [pregunta, respuesta, imagen , animal1, animal2, totalConjuntoA, totalConjuntoB]
9e14d696b6e35463f99b204cfe27235df7c145d6
ericasu33/LHL-Fundamentals-to-Python
/Bill splitter.py
508
4.03125
4
subtotal = float(input("Bill Total: ")) tipPercentage = int(input("Tip Percentage: ")) contributors = int(input("Number of People: ")) tax_rate = 0.14 tax = round(subtotal*tax_rate,2) total = round(subtotal + tax,2) tips = total*tipPercentage/100 overall_total = round(total+tips,2) total_per_person = round(overall_total/contributors,2) print ("The total before tips is:$", total) print ("The final total including tips is:$", overall_total) print("The bill per person comes to:$", total_per_person)
2291a6767aa40757727ef9a9067b3b723b3c6917
vuongvx96/Linux
/BT_TrenLop_24-4/Mang.py
944
3.5
4
# Mang trong Python #-- Ham nhap mang def Nhapmang(arr,n): for i in range(n): arr.append(int(raw_input("Nhap vao phan tu thu %d = " %(i+1)))) #-- In mang vua nhap def Xuatmang(arr): for item in arr: print item, #-- Ham xuat cac phan tu chan def Inchan(arr): for item in arr: if (int(item) % 2 == 0): print item, #-- Ham sap xep mang tang dan def Sapxep(arr,n): for i in range(0,n-1): for j in range(i+1,n): if (a[i] > a[j]): tam = a[i] a[i] = a[j] a[j] = tam #-- Ghi ra file def Ghifile(arr): file = open('Mang.txt','w+') for item in arr: file.write(str(item) + " ") file.close() #----------- CHUONG TRINH CHINH ------------- # Khai bao mang a a = [] n = input("Nhap vao so luong phan tu: ") Nhapmang(a,n) print("\nMang vua nhap:") Xuatmang(a) print("\nCac phan tu co gia tri chan:") Inchan(a) print("\nMang sau khi sap xep tang dan:") Sapxep(a,n) Xuatmang(a) print("\nGhi ra file ...") Ghifile(a)
ba7c3ca5d6f0c53362e6eb79a790ab59b72d7f8f
jsw0402/python-practice
/py4-Q3.py
181
3.609375
4
input1=int(input("첫번째 숫자를 입력하세요:")) input2=int(input("두번째 숫자를 입력하세요:")) total=input1+input2 print("두수의 합은 %d입니다."%total)
c694f25bf9a2c693871f70c06967f8c5e2e82bc5
sagitta1969/lesson_6
/zadanie_2.py
647
3.90625
4
class Road: def __init__(self, _lenght, _width): self._lenght = _lenght self._width = _width def calc(self): print(f"масса асфальта дороги: {self._lenght * self._width * 5 * 0.025} тн") def main(): while True: try: new_road = Road(int(input("введите ширину дороги в метрах: ")),\ int(input("введите длину дороги в метрах: "))) new_road.calc() break except ValueError: print("вводить только цифры") main()
6c2aed7b1f1e11d1112f44dfaa786f79156a151f
raykstar/1st
/hello.py
48
3.640625
4
s= input("Your name: ") print("Hello "+s+" !")
a53c348e955cd46be9cad01fbd39c696ef63f34e
Oxtin/Python_homework
/3107.py
1,105
3.65625
4
class student: a = 0 def __init__ (self, Name, Gender): self.name = Name self.gender = Gender self.grades = [] self.avg = 0 self.FailNumber = 0 def add (self, Grade): self.grades.append(Grade) def compute(self): sum = 0 n = 0 for i in self.grades: if i < 60: n = n + 1 sum = sum + i self.avg = (sum) / len(self.grades) self.FailNumber = n def show_info(self): print("Name: %s\nGender: %s\nGrades: %r\nAvg: %.1f\nFail Number: %d\n"%(self.name, self.gender, self.grades, self.avg, self.FailNumber)) def Find (data): Max = 0 for i in data: if i.avg > Max: Max = i.avg p = i return (p) s1 = student("Tom","M") s2 = student("Jane","F") s3 = student("John","M") s4 = student("Ann","F") s5 = student("Peter","M") s1.add(80) s1.add(90) s1.add(55) s1.add(77) s1.add(40) s2.add(58) s2.add(87) s3.add(100) s3.add(80) s4.add(40) s4.add(55) s5.add(60) s5.add(60) s1.compute() s2.compute() s3.compute() s4.compute() s5.compute() s1.show_info() s2.show_info() s3.show_info() s4.show_info() s5.show_info() print("Top Student:") Find((s1, s2, s3, s4, s5)).show_info()
5b19110d7ad4811ed14d7d7c557ae7fef5caee04
kinqston34/python_program
/PycharmProjects/python_basic_language/e.py
133
3.671875
4
#f : f-string {} #r : 原樣(raw) #u :unicode w = {'a':1 ,'b':2} print(f"{w['a']} : {w['b']}") x = 1 print(f'{x+1}') print(f'{x+1=}')
3d8e00c6b5257d73b45a378030dba9f813183477
venanciomitidieri/Exercicios_Python
/053 - Detector de Palíndromo.py
610
4.09375
4
# Exercício Python 053 - Detector de Palíndromo # Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. frase = str(input('Digite um frase: ')).strip().upper() palavras = frase.split() junto = ''.join(palavras) inverso = '' for letra in range(len(junto) - 1, -1, -1): # Ele usa o len -1 para pegar a ultima letra da string, usa o -1 novamente pra pegar até o primeiro numero que seria zero inverso += junto[letra] print(junto, inverso) if inverso == junto: print('É um palindromo!') else: print('Não é um palindromo!')
5753c0dcf089e8d831a75c897662155d88a3dc33
Babken/python-hometask
/homework.shahane_2.extra1.py
335
3.953125
4
while True: password = input ("Password Validator: ") cl = False cu = False for i in password: if i.isdigit(): cl = True elif i.isupper(): cu = True if cl == True and cu == True: break if cl == True and cu == True: print(password) break
c6daf21ed8d918977acea09990a85b60fa6c6ba7
ZerafCode/python21
/string/006.py
655
4.0625
4
message = 'welcome to python' name = 'lina' print(name, message) print(name + message) new_message = ", ".join((name, message)) print(new_message) print('%s %s' % (name, message)) print('%s, %s! ' % (name, message)) print('<< %s, %s! >>' % (name, message)) print("%s %s %s %s " % ("welcome", "to", "python", "Hub")) number = 3 print('<< ' + name + ',😍 ' + (message) + str(3) + ' 👌') print(f'{name}, {message} 3') print('{} {}.'.format(name, message)) print(name + " " + message) name += ', ' + message print(name) list_message = ['welcome', 'to', 'python3'] empty_string = ' ' for lists in list_message: empty_string += lists print(empty_string)
756a4aa89a249bebf39f702902b2579c65c6ed68
idealhang/Python
/class18-1.py
259
3.84375
4
def sxh(number): temp = (number % 10) ** 3 + (number // 10 % 10) ** 3 \ + (number // 100) ** 3 if temp == number: return True for number in range(100,1000): if sxh(number): print(number)
a97f074c559e5a091ac66053e99a1d7207cbe638
arkimede/pysynfig
/objects/tags/Vector.py
794
3.703125
4
class Vector: def __init__(self, x,y): self.x = x self.y = y self.node = None def __init__(self,x,y,node=None): #self.x = x #self.y = y self.node = node self.setX(x) self.setY(y) def setNode(self, node): self.node = node def getNode(self): return self.node def getX(self): return self.x def getY(self): return self.y def setX(self,x): self.x = x if self.node is not None: self.node.find('x').text = self.x def setY(self,y): self.y = y if self.node is not None: self.node.find('y').text = self.y def printXML(self): xml = """\n""" + "<vector>" + """\n\t""" + "<x>" + self.x + "</x>" + """\n\t""" + "<y>" + self.y + "</y>\n" + "</vector>" + """\n""" return xml
c3082cd199a96057ace4d8a80578d45db7e0447d
ucarkadir/learning-python-from-zero-to-hero
/36_manage_private_variables_test.py
427
3.59375
4
class Person: def __init__ (self, first_name, email): self.first_name = first_name self._email = email def update_email(self, new_email): self._email = new_email def email(self): return self._email tk = Person('Tk', 'tk@mail.com') print(tk.email()) # => tk@mail.com tk._email = 'new_tk@mail.com' print(tk.email()) # => new_tk@mail.com tk.update_email('new_tk@mail.com') print(tk.email()) # => new_tk@mail.com
d34c36c134e00365db671444b782bf6d77a51e9f
nickayresdemasi/adventofcode
/code/2017/day3.py
2,078
4.03125
4
''' @author: Nick DeMasi Code to complete Part 2 of Day 3 of 2017 Advent of Code using Python 3 ''' import sys class SpiralGraph(object): def __init__(self): self.grid = {} def build_graph(self, num): '''Constructs a sprial graph in counterclockwise direction. INPUT: - num (int): number at which to stop graph building ''' self.grid[(0, 0)] = 1 x, y = 1, 0 self.grid[(x, y)] = 1 while True: while x != y: y += 1 self.grid[(x, y)] = self.__calculate_value(x, y) if self.grid[(x, y)] > num: print(self.grid[x, y]) sys.exit() while -x != y: x -= 1 self.grid[(x, y)] = self.__calculate_value(x, y) if self.grid[(x, y)] > num: print(self.grid[x, y]) sys.exit() while x != y: y -= 1 self.grid[(x, y)] = self.__calculate_value(x, y) if self.grid[(x, y)] > num: print(self.grid[x, y]) sys.exit() while -x != y: x += 1 self.grid[(x, y)] = self.__calculate_value(x, y) if self.grid[(x, y)] > num: print(self.grid[x, y]) sys.exit() x += 1 self.grid[(x, y)] = self.__calculate_value(x, y) if self.grid[(x, y)] > num: print(self.grid[x, y]) sys.exit() def __calculate_value(self, x, y): '''Calculates next value in Spiral Graph by adding up adding up all adjacent existing values''' num = 0 for i in range(-1, 2): for j in range(-1, 2): coordinates = (x - i, y - j) if coordinates in self.grid.keys(): num += self.grid[coordinates] return num if __name__ == '__main__': sg = SpiralGraph() sg.build_graph(361527)
224d431cba64ce85b938bd08fe0242df31998276
greenfox-velox/danielliptak
/week3/day4/demo2v2.py
388
4.03125
4
def search_palindromes(in_put): palindrome_list = [] length = 3 end = i + length temporary = in_put[i:end] while length < len(in_put)-1: for i in range(len(in_put)-length+1): if temporary == temporary[::-1]: palindrome_list.append(temporary) length += 1 return palindrome_list output = search_palindromes('dog goat dad duck doodle never') print(output)
fa601633904ab15137009c984347e13fbb69326a
timothyblack/qishialgo
/GoldmanSachesOA/medium/lint1611_smallestLength.py
2,568
3.703125
4
""" https://www.lintcode.com/problem/shortest-subarray/description Time O(N^2) brute force """ class Solution: """ @param nums: @param k: @return: return the length of shortest subarray """ def smallestLength(self, nums, k): start, presum = 0, 0 minlen = sys.maxsize for i in range(len(nums)): presum += nums[i] while presum >= k: print(i, start, i - start + 1) minlen = min(minlen, i - start + 1) presum -= nums[start] start += 1 return -1 if minlen == sys.maxsize else minlen """ # https://www.cnblogs.com/grandyang/p/4501934.html 这道题给定了我们一个数字,让我们求子数组之和大于等于给定值的最小长度,注意这里是大于等于,不是等于。跟之前那道 Maximum Subarray 有些类似,并且题目中要求我们实现 O(n) 和 O(nlgn) 两种解法,那么我们先来看 O(n) 的解法,我们需要定义两个指针 left 和 right,分别记录子数组的左右的边界位置,然后我们让 right 向右移,直到子数组和大于等于给定值或者 right 达到数组末尾,此时我们更新最短距离,并且将 left 像右移一位,然后再 sum 中减去移去的值,然后重复上面的步骤,直到 right 到达末尾,且 left 到达临界位置,即要么到达边界,要么再往右移动,和就会小于给定值。代码如下: """ class Solution: """ @param nums: @param k: @return: return the length of shortest subarray """ def smallestLength(self, nums, k): left, right = 0, 0 presum = 0 n = len(nums) minlen = n + 1 while right < n: while presum < k and right < n: presum += nums[right] right += 1 while presum >= k: minlen = min(minlen, right - left) presum -= nums[left] left += 1 return -1 if minlen == n + 1 else minlen """ start, presum = 0, 0 minlen = sys.maxsize for i in range(len(nums)): presum += nums[i] while presum >= k: print(i, start, i - start + 1) minlen = min(minlen, i - start + 1) presum -= nums[start] start += 1 return -1 if minlen == sys.maxsize else minlen """
c0eb0a88d364d9b69c9d04a9c7634d404d637c1d
hongwenshen/Python_Study
/Python 100例/Python 练习实例33.py
267
3.5
4
#!/usr/bin/env python # coding=UTF-8 ''' @Description: About practicing python exercises @Author: Shenhongwen @LastEditors: Shenhongwen @Date: 2019-03-04 19:58:49 @LastEditTime: 2019-03-04 20:06:29 ''' L = [1, 2, 3, 4, 5] s1 = ','.join(str(n) for n in L) print(s1)
d595491513c1347e14477c2097c32ba3a0bf2897
andres-root/hackerrank.com
/Algorithms/MaximizingXOR/NonOptimalSolution.py
244
3.640625
4
#!/usr/bin/python3 if __name__ == '__main__': l = int(input()) r = int(input()) m = -1 for i in range(l, r + 1): for j in range(l, r + 1): c = i ^ j if m < c: m = c print(m)
0c026a5e80b4071bdd00609228bb4702b9309fa8
anzhihe/learning
/python/source_code/source_code_of_lp3thw/ex6old.py
1,481
4.34375
4
# 将“字符串”赋值给"变量x",该字符串中有个位置是用“%d”(包含格式)来代替的。%d这个符号看起来有两个作用:第一个作用是“占位符”——正名这个位置将来会有个东西放在这里;第二个作用是“这个东西的格式”,既然其使用了%d,我认为其应该是digital——数字的。 x= "There are %d types of people." %10 # 建立了给新的变量binary,将字符串“binary”赋值给了它。一般来说,变量会用简单的写法,竟然也可以直接使用单词。 binary="binary" do_not="don't" y="Those who know %s and those who %s."%(binary,do_not) print (x)# print() 是个函数,必须有() print (y) print ("I said: %r."% x) print ("I also said:'%s'."%y)#Print后面每次都要加满括号。 hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" print (joke_evaluation% hilarious) w="This is the left side of..." e= "a string with a right side." print (w+e) # 只要将格式化的变量放到字符串中,再紧跟着一个百分号%,再紧跟着变量名即可。唯一要注意的地方,是如果你想要在字符串中通过格式化字符放入多个变量的时候,[你需要将变量放到()圆括号里,变量之间采用逗号,隔开。] #试着使用更多的格式化字符,例如%s、%d、%r。例如 %r%r就是是非常有用的一个,它的含义是“不管什 么都打印出来”。
1143c5cd1155191a5c71396c82628326e15252f7
Jonathas-coder/Python
/ex 69.py
731
3.859375
4
women20=0 homem=0 maior=0 while True: print('-'*25) print('CADASTRE UMA PESSOA') print('-'*25) idade=int(input('Qual a idade: ')) if idade > 18: maior+=1 sexo=str(input('Qual o sexo [M/F]: ')).upper() if sexo == 'M': homem+=1 else: print('DIGITE UM SEXO VÁLIDO POR FAVOR.') sexo = str(input('Qual o sexo [M/F]: ')).upper() if idade <20 and sexo == 'F': women20+=1 print('-'*15) continuar=str(input('Deseja continuar [S/N]: ')).upper() if continuar == 'N': print(f'Total de pessoas maiores de 18 anos:{maior}\nAo todo temos {homem} homens cadastrados' f'\nTotal de mulheres com menos de 20 anos: {women20}') break
e2ad1caa304b1c42b08d2d6291f043f8d52be71d
Raeebikash/python_class1
/python_class/while_loop24.py
119
3.6875
4
#loops #while loop, for loop #print('ellow world')# 10 times i = 1 while i <= 10: print("hellow world") i +=1
49fcf2420137fdf4d0cc6f64bc257264cedf0b72
EmmanuellaAlbuquerque/Curso-Em-Video
/Python Mundo3 - Estruturas Compostas/desafio - 95.py
3,458
3.75
4
# APROVEITAMENTO DE UM JOGADOR DE FUTEBOL time = list() jogador = dict() partidas = list() # ENTRADA DE DADOS while True: jogador.clear() jogador['nome'] = str(input('Nome do jogador: ')) tot = int(input(f'Quantas partidas {jogador["nome"]} jogou? ')) partidas.clear() for c in range(0, tot): partidas.append(int(input(f' Quantos gols na partida {c+1}? '))) jogador['gols'] = partidas[:] jogador['total'] = sum(partidas) time.append(jogador.copy()) while True: resp = str(input('Quer continuar? [S/N] ')).upper()[0] if resp in 'SN': break print('ERRO! Responda apenas S ou N.') if resp == 'N': break print('-='*30) # CABEÇALHO print('cod ', end='') for i in jogador.keys(): print(f'{i:<15}', end='') print() # TABELA COM TODOS AS ENTRADAS/KEYS E VALORES print('-'*40) for k, v in enumerate(time): print(f'{k:>3} ', end='') # k - (i)iterador for dado in v.values(): print(f'{str(dado):<15}', end='') print() print('-'*40) # EXIBE DADOS ESPECÍFICOS while True: busca = int(input('Mostrar dados de qual jogador? (999 para parar) ')) if busca == 999: break if busca >= len(time): print(f'ERRO! Não existe jogador com código {busca}!') else: print(f' -- LEVANTAMENTO DO JOGADOR {time[busca]["nome"]}:') for i , gols in enumerate(time[busca]['gols']): print(f' No jogo {i+1} fez {gols} gols.') print('-'*40) print('<< VOLTE SEMPRE >>') ''' jogador = dict() jogadores = list() aproveitamento = list() qQuatJogadores = 0 while True: nomeJogador = str(input('Nome do Jogador: ')) qPartidas = int(input('Quantidade de partidas: ')) jogador['Nome'] = nomeJogador somaGols = 0 for i in range(0, qPartidas): qGols = int(input(f'Quantidade de Gols na {i}° partida: ')) aproveitamento.append(qGols) somaGols += qGols jogador['Gols'] = aproveitamento[:] jogador['Total de Gols'] = somaGols print('-='*30) jogadores.append(jogador.copy()) qQuatJogadores += 1 aproveitamento.clear() desejaContinuar = str(input('S para continuar e N para sair do programa!')).strip().upper() while desejaContinuar not in 'SN': desejaContinuar = str(input('S para continuar e N para sair do programa!')).strip().upper() if desejaContinuar == 'N': print('{:-^51}'.format(' PROGRAMA ENCERRADO COM SUCESSO! ')) break print('-='*30) print(f'{"Cod.":<5}{"Nome.":<10}{"Gols.":<10}{"Total."::<10}') # alinha a esquerda e dá 10 espaços i = 0 for item in jogadores: print(f'{i} {item["Nome"]:<6} {item["Gols"]} {item["Total de Gols"]:}') i += 1 while True: escolha = int(input('>>> Mostrar dados de qual jogador? [999 p/ sair] ')) if escolha == 999: break while escolha > (qQuatJogadores-1) or escolha < 0: print('Escolha inválida!') escolha = int(input('>>> Mostrar dados de qual jogador? ')) if escolha == 999: break print(f'---- Levantamento do jogador {jogadores[escolha]["Nome"]}: ') for item in jogadores: if item['Nome'] == jogadores[escolha]["Nome"]: for i in range(0, len(item['Gols'])): print(f'No jogo {i} fez {item["Gols"][i]} gols.') print('PROGRAMA ENCERRADO') '''
98ea61d9ec010b05df2a0c0abf3791b04b8b54e9
rippedpant/bioinformatics
/rosalind/mortal_fibonacci_rabbits.py
716
3.96875
4
""" Calculate the total number of pairs of rabits that will remain after n-th month if all rabits live for m month. """ def calc_mortal_rabbits(n, m): """ n (int): number of months to endure m (int): number of months after which rabbits die Return (int): total number of rabbits pairs """ pairs = [1, 1] cur_month = 2 while cur_month < n: if cur_month < m: pairs.append(pairs[-2] + pairs[-1]) elif cur_month == m: pairs.append(pairs[-2] + pairs[-1] - 1) else: pairs.append(pairs[-2] + pairs[-1] - pairs[-m-1]) cur_month += 1 return pairs[-1] if __name__ == "__main__": print(calc_mortal_rabbits(94, 18))
b678d5c16777c3a3770c8105c455c8a2f52d1056
chom125/Algorithms-UCSanDiego
/1_course/5_week/2_primitive_calculator/python/main.py
2,139
3.8125
4
# python3 ## # # Python3 implementation to find the minimum amount of operations on a primitive calculator to obtain N # The primitive calculator has 3 operations: multiply by 2, multiply by 3, and add by 1 # # (c) Copyright 2019 Clayton J. Wong ( http://www.claytonjwong.com ) # ## from typing import List, Dict Type = int INF = 1000001 Memo = Dict[ Type,Type ] Collection = List[ Type ] def reconstruct( N: Type, memo: Memo={}, A: Collection=[] ) -> Collection: while 0 < N: A.insert( 0, N ) prev3 = memo[ N // 3 ] if N % 3 == 0 and N // 3 in memo else INF prev2 = memo[ N // 2 ] if N % 2 == 0 and N // 2 in memo else INF prev1 = memo[ N - 1 ] if N - 1 >= 0 and N - 1 in memo else INF prev = min( prev3, prev2, prev1 ) if prev == prev3: N //= 3 elif prev == prev2: N //= 2 elif prev == prev1: N -= 1 return A class RECSolution: def minOps( self, N: Type, memo: Memo={} ) -> Type: self.go( N, memo ) return reconstruct( N, memo ) def go( self, N: Type, memo: Memo, ans: Type=INF ) -> Type: if N < 2: memo[ N ] = 0 if N in memo: return memo[ N ] if N % 2 == 0: ans = min( ans, 1 + self.go( N // 2, memo )) if N % 3 == 0: ans = min( ans, 1 + self.go( N // 3, memo )) memo[ N ] = min( ans, 1 + self.go( N - 1, memo )) return memo[ N ] class DPSolution: def minOps( self, N: Type, memo: Memo={1:0} ) -> Type: dp = [ INF ] * ( N+1 ) dp[ 1 ] = 0 for i in range( 2, N+1 ): if i % 2 == 0: dp[ i ] = min( dp[ i ], 1 + dp[ i // 2 ] ) if i % 3 == 0: dp[ i ] = min( dp[ i ], 1 + dp[ i // 3 ] ) memo[ i ] = dp[ i ] = min( dp[ i ], 1 + dp[ i - 1 ] ) return reconstruct( N, memo ) if __name__ == '__main__': dp_solution = DPSolution() N = int( input() ) A = dp_solution.minOps( N ) print( len(A) - 1 ) print( A ) rec_solution = RECSolution() A1 = rec_solution.minOps( N ) assert( A1 == A )
cf4dfb4e4b16e0949cd917317dd8f5d1549e408d
psalc/ds4a
/encryption-decryption-scripts/decryption.py
1,189
3.828125
4
#!/usr/bin/env python # coding: utf-8 # In[7]: import random import math import ast # Setting up replacement dictionary constant letters = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ") values = list(range(1, 54)) replacement_dict = {} for letter, value in zip(letters, values): replacement_dict[letter] = value # Setting values for constants p = 101 q = 139 n = p * q phi = (p - 1) * (q - 1) e = 7 d = int((2 * phi + 1) / e) # In[8]: def decrypt(encrypted_chars): """ Takes encrypted_chars input as a list and decrypts, returning the original unencrypted message. Arguments: encrypted_chars, list Output: decrypted_string, string """ detranslated_chars = [(char ** d) % n for char in encrypted_chars] decrypted_chars = [] for each in detranslated_chars: for key, value in replacement_dict.items(): if each == value: decrypted_chars.append(key) decrypted_string = ''.join(decrypted_chars) return decrypted_string # In[9]: cipher = ast.literal_eval(input('Please paste your encrypted message exactly.\n')) # In[13]: print(decrypt(cipher))
a0a8fd3e17f7f0a04a99cb8840720ab7592520a0
rodolfopardo/codigos
/Temperaturas.py
1,531
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 28 15:36:19 2019 @author: rodolfopardo """ # import import matplotlib.pyplot as plt %matplotlib inline # axis x, axis y y = [33,66,65,0,59,60,62,64,70,76,80,81,80,83,90,79,61,53,50,49,53,48,45,39] x = list(range(len(y))) # plot plt.plot(x, y) plt.axhline(y=70, linewidth=1, color='r') plt.xlabel('hours') plt.ylabel('Temperature ºC') plt.title('Temperatures of our server throughout the day') # assign a variable to the list of temperatures # 1. Calculate the minimum of the list and print the value using print() print("El valor mínimo fue de:", min(y)) # 2. Calculate the maximum of the list and print the value using print() print("El valor máximo fue de:", max(y)) # 3. Items in the list that are greater than 70ºC and print the result for valores in y: if valores > 70: print(valores) else: print("Valor por debajo de 70º") # 4. Calculate the mean temperature throughout the day and print the result promedio = sum(y) / len(y) print("El promedio de temperaturas fue de:",promedio) # 5.1 Solve the fault in the sensor by estimating a value variable03 = y[2]+y[3]/2 y[3] = int(variable03) # 5.2 Update of the estimated value at 03:00 on the list print(y) # Bonus: convert the list of ºC to ºFarenheit Formula: F = 1.8 * C + 32 yFar = [] variable1 = 0 for valores in y: variable1 = 1.8 * valores + 32 yFar.append(variable1) print("Estas son las temperaturas en F para Estados Unidos:", yFar)
c54e976a32093a93011aa766912f2383260dbb9a
Kutukas/python-project-lvl1
/brain_games/games/gcd.py
699
3.625
4
import random from brain_games.engine import run_game def gcd(a, b): ''' find the greatest common divisor of integers a and b with the euclidean algorithm ''' rem = max(a, b) # rem is remainder next_rem = min(a, b) rest = rem % next_rem while rest != 0: rem, next_rem = next_rem, rest rest = rem % next_rem else: return next_rem def play(): RULE = "Find the greatest common divisor of given numbers." run_game(RULE, generate_data) def generate_data(): x = random.randrange(100) y = random.randrange(100) expression = '{} {}'.format(x, y) correct_answer = gcd(x, y) return expression, str(correct_answer)
f97d5922e954d32563a603ed7464cadeba001e5b
MarkHofstetter/python-kurs
/kurs-20170410/zahlen_unterteilen.py
556
3.8125
4
""" + die zahlen von 1-10 sollen unterteilt werden + in gerade und ungerade + und nur wenn ungerade soll auch angezeigt werden, dass die Zahl groesser als 5 ist """ for i in range(1,11): u = i/2 larger_than_5 = '' if u == int(u): odd_or_even = 'gerade' else: odd_or_even = 'ungerade' if i > 5 and u != int(u): larger_than_5 = 'groesser als 5' print("%02d %s %s" % (i, odd_or_even, larger_than_5))
ca36d5e48aa46594bf790fafe8ab579a98861775
ZacharyWatanabe/SudokuSolver
/Example.py
1,114
4.0625
4
from SudokuConstraintSolver import SudokuConstraintSolver from SudokuBacktrackingSolver import SudokuBacktrackingSolver """ Example.py Zachary Watanabe-Gastel Iterate through the list of sudoku puzzles and print the solutions """ def sub_routine1(solver): #written for constraint solver success = solver.ac3(False) #AC3 is passed false to return if a unique solution was found if success: solver.sudokus.write_puzzle('output_constraint_solver.txt') def sub_routine2(solver): #written for backtracking solver success = solver.backtracking() #Backtracking() returns if a unique solution was found if success: solver.sudokus.write_puzzle('output_backtracking_solver.txt') # Example usage of sudoku solvers #Constraint Solver Iterates through puzzle list and prints the puzzles it solves s1 = SudokuConstraintSolver() sub_routine1(s1) while s1.sudokus.next_puzzle(): sub_routine1(s1) #Backtracking Solver iterates through puzzle list and prints the puzzles it solves s2 = SudokuBacktrackingSolver() sub_routine2(s2) while s2.sudokus.next_puzzle(): sub_routine2(s2)
0272a04ca5d54d92e047363d9f65f827767e1d81
JhordanRojas/Trabajo-05
/boletas/prog13.py
971
4.1875
4
#INPUT cantidad_de_productos=input("Ingrese la cantidad de productos:") precio_del_producto1=int(input("Ingrese el precio del producto1:")) precio_del_producto2=int(input("Ingrese el precio del producto2:")) precio_del_producto3=int(input("Ingrese el precio del producto3:")) #PROCESSING Total=(precio_del_producto1 + precio_del_producto2 + precio_del_producto3) #verificador gasto_alto=(Total>150000) #OUTPUT print("##################################") print("# FERRETERIA - OLANO ") print("##################################") print("#") print("#cantidad de productos s/ :", cantidad_de_productos) print("#precio del producto1 s/ :", precio_del_producto1) print("#precio del producto2 s/ :", precio_del_producto2) print("#precio del producto3 s/ :", precio_del_producto3) print("#Total s/ :", Total) print("###################################") print("Nos a gustado su compra:",gasto_alto)
839b8cef14e0161dc98ef25f15316685dcffd1d9
iptoninho/learnings
/python/EstruturaSequencial/ex10-convTempCelcToFar.py
134
3.65625
4
c = input("Entre com a temperatura em graus Celsius: ") f = (c * 1.8) + 32 print "%.2f graus Celsius sao %.2f Farenheit." % (c,f)
fd57f1dd8b1e714b0c60cca5cfb3b27521dd0a43
BoxBy/Python
/20200117/Practice10.py
1,701
3.734375
4
# https://github.com/BoxBy/Cpp/tree/master/20191128 : Cpp to Python class Wordlist : def __init__(self) : self.__dictonary = [] self.__wordlist = [] inFile = open("dict.txt", 'r') lines = inFile.readlines() for line in lines : self.__dictonary.append(line) inFile.close() def CheckDictionary(self, string) : if string in self.__dictonary : return raise str("Not exist word in dictionary") def CheckDuplication(self, string) : if string in self.__wordlist : raise str("It's Duplication") def CheckConfirm(self, string) : if len(self.__wordlist) == 0 : return if self.__wordlist[-1][-1] != string[0] : raise str("Not same as the previous word alphabet") def add(self, string) : outFile = open("result.txt", 'w') try : self.CheckDictionary(string) self.CheckDuplication(string) self.CheckConfirm(string) except Exception as reason: print("You Lose. ", end = '') outFile.close() raise reason self.__wordlist.append(string) print(self.__wordlist) outFile.write(string, " ") def startGame(self) : print("Game Start") try : while True : word = input("Input Word : ") try : word.upper() except : raise str("It is not English") self.add(word) except Exception as reason : print(reason) wl = Wordlist() wl.startGame()
f81c058af9187eb2d7962e889aef51ccd9e0e1ce
keyPan-GitHub/MyPythonCode
/day3/深浅拷贝.py
398
3.984375
4
n1 = 123 n2 = n1 print(id(n1)) print(id(n2)) import copy n1 = 123 n2 = copy.copy(n1) print(id(n1)) print(id(n2)) n2 = copy.deepcopy(n1) print(id(n1)) print(id(n2)) n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]} n2 = copy.copy(n1) # 浅拷贝第一层不一样, print(id(n1),id(n2)) # 浅拷贝第二层内存地址相同 print(id(n1["k1"]),id(n2["k1"])) print(id(n1["k3"]),id(n2["k3"]))
501237f342c572001f7dd695894ddb21b4833271
ariji1/Competitive_Programming
/Day_6/queue_two_stacks.py
2,215
3.953125
4
import unittest # class QueueTwoStacks(object): # # Implement the enqueue and dequeue methods # def enqueue(self, item): # pass # def dequeue(self): # pass class Stack(): def __init__(self): self.stk = [] def pop(self): """raises IndexError if you pop when it's empty""" return self.stk.pop() def push(self, elt): self.stk.append(elt) def is_empty(self): return len(self.stk) == 0 def peek(self): if not self.stk.is_empty(): return self.stk[-1] class Queue(): def __init__(self): self.q = Stack() # the primary queue self.b = Stack() # the reverse, opposite q (a joke: q vs b) self.front = None def is_empty(self): return self.q.is_empty() def peek(self): if self.q.is_empty(): return None else: return self.front def enqueue(self, elt): self.front = elt self.q.push(elt) def dequeue(self): """raises IndexError if you dequeue from an empty queue""" while not self.q.is_empty() > 0: elt = self.q.pop() self.b.push(elt) val = self.b.pop() elt = None while not self.b.is_empty() > 0: elt = self.b.pop() self.q.push(elt) self.front = elt return val # Tests class Test(unittest.TestCase): def test_queue_usage(self): queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) actual = queue.dequeue() expected = 1 self.assertEqual(actual, expected) actual = queue.dequeue() expected = 2 self.assertEqual(actual, expected) queue.enqueue(4) actual = queue.dequeue() expected = 3 self.assertEqual(actual, expected) actual = queue.dequeue() expected = 4 self.assertEqual(actual, expected) with self.assertRaises(Exception): queue.dequeue() unittest.main(verbosity=2)
5e4645e0956833f49738d4740f0cdad8d4f5830c
fuzzyslippers/my-test-projects
/hangman.py
791
3.578125
4
#!/usr/bin/env python import random import urllib animals = urllib.urlopen('http://davidbau.com/data/animals').read().split() print 'time to play hangman' secret = random.choice(animals) guesses = 'aeiou' turns = 5 while turns > 0: missed = 0 for letter in secret: if letter in guesses: print letter, else: print '_', missed += 1 print if missed == 0: print 'You win!' break guess = raw_input('guess a letter: ') guesses += guess print 'You guessed ' +guesses if guess not in secret: turns -= 1 print 'Nope.' print turns, 'more turns' if turns < 5: print ' O ' if turns < 4: print ' \_|_/ ' if turns < 3: print ' | ' if turns < 2: print ' / \ ' if turns < 1: print ' d b ' if turns == 0: print 'The answer is', secret exit()
eb1498cab2257304b70a23a80dd55d0ae14747f4
pritam1997/python-test-4
/q6.py
164
4.09375
4
for r in range(6): if r == 0 or r==3: for c in range(5): print("*",end="") print() else: for a in range(2): print("*",end=" ") print()
2677bf06bd507748a12bb10ff3884f046c0b785f
hrushigade/learnpython
/divisiblebygivennumber.py
194
3.875
4
lower=int(input("enter lower range limit")) upper=int(input("enter upper range limit")) n=int(input("enter the no to be divided")) for i in range(lower,upper+1): if(i%n==0): print(i)
6ecf0df7f715abb298aa5fa11f1f2c07a27d2171
Hamza122000/Python-projects
/hw10/hw10.py
3,767
3.84375
4
class Complex: def __init__(self,real,imag): self.real=real self.imag=imag def get_real(self): return self.real def get_imag(self): return self.imag def set_real(self,new_real): self.real=new_real def set_imag(self,new_imag): self.imag=new_imag def __str__(self): return str(self.real)+ ' '+ '+'+ ' '+ str(self.imag)+'i' def __add__(self,other): a=self.real+other.real b=self.imag+other.imag return Complex(a,b) def __mul__(self,other): c=self.real*other.real-self.imag*other.imag d=self.imag*other.real+self.real*other.imag return Complex(c,d) def __eq__(self,other): if self.real==other.real and self.imag==other.imag: return True else: return False class Employee: #========================================== # Purpose: To initialize the instance variables of the class # Input Parameter(s):self which is a pointer, and line which is a string that represents the information of the employee # Return Value(s): none #========================================== def __init__(self,line): line=line.strip('\n') line=line.split(',') self.name=line[0] self.position=line[1] self.salary=float(line[2]) self.seniority=float(line[3]) self.value=float(line[4]) def __str__(self): return self.name + ','+ ' ' +(self.position) def net_value(self): return self.value-self.salary #========================================== # Purpose: to take two different employess and compare their net_Values # Input Parameter(s): self and other which represent the two different employees # Return Value(s): Returns True is the net_value of the first employee is less, false otherwise #========================================== def __lt__(self,other): a=self.net_value() b=other.net_value() if a<b: return True else: return False class Branch: #========================================== # Purpose: To intialize the instance variables of the class # Input Parameter(s): self which is the pointer and fname which is the name of the file # Return Value(s): none #========================================== def __init__(self,fname): fp=open(fname) line=fp.readlines() self.location=(line[0].split(',')[1]) self.upkeep=float((line[1].split(',')[1])) self.team=[] for i in range(3,len(line)): self.team.append(Employee(line[i])) def __str__(self): s='' for i in self.team: s+=str(i)+'\n' return self.location+'\n'+s def profit(self): s=0 for i in self.team: s+=i.net_value() return s-self.upkeep def __lt__(self,other): if self.profit()<other.profit(): return True else: return False def cut(self,num): self.team.sort() for i in range(0,num): self.team.pop(0) class Company: def __init__(self,name,branches): self.name=name self.branches=branches def __str__(self): line='' for i in self.branches: line=line+str(i)+'\n' return self.name + '\n'+'\n' + line def synergize(self): self.branches.sort() self.branches[0].cut(len(self.branches[0].team)//2)
fde1cef5e0f3283966c77d7075776443e6207b7a
hungphat/hackerrank-30days
/day_13/Abstract_Classes.py
1,110
3.859375
4
def run(input, output): from abc import ABCMeta, abstractmethod class Book(object, metaclass=ABCMeta): def __init__(self, title, author): self.title = title self.author = author @abstractmethod def display(): pass #Write MyBook class class my_book(Book): # TODO the exercise told you that creating Clase MyBook(), I dont understand why you create a 'my_book' # The Class name should be uppercase def __init__(self, title, author, price): Book.__init__(self, title, author) self.price = price def display(self): print('Title: '+self.title) print('Autthor' +self.author) print('Price: ' + self.price) f = open(input, 'r') wr = open(output, 'w') title = f.readline().rstrip('\n') author =f.readline().rstrip('\n') price =f.readline().rstrip('\n') new_novel=my_book(title, author, price) new_novel.display() if __name__ == '__main__': run('input.txt','output.txt')
425f98f0cc8d814e7e7d76f7a45e827ef3630716
KoliosterNikolayIliev/Softuni_education
/Python advanced 2020/Exercise Comprehensions/2.Words Lengths.py
159
3.8125
4
strings = [x for x in input().split(", ")] dictionary = {name: len(name) for name in strings} print(', '.join([f"{k} -> {v}" for k, v in dictionary.items()]))
41ec27066d64ad15298bb06512935d3c99da7ce7
aulee888/LeetCode
/Climbing Stairs.py
739
3.65625
4
class Solution: def rec_climbStairs(self, n: int) -> int: """Recursive Solution""" if n <= 2: return n else: step1 = self.rec_climbStairs(n - 1) step2 = self.rec_climbStairs(n - 2) return step1 + step2 def dp_climbStairs(self, n: int) -> int: """Dynamic Programming Solution w/ Recursion""" def helper(steps: int, known: dict) -> int: if steps in known: return known[steps] if steps <= 2: return steps ways = (helper(steps - 1, known) + helper(steps - 2, known)) known[steps] = ways return ways return helper(n, {})
ea20c8e998240825c39354ad7856744e5976a6fa
Vixus/LeetCode
/PythonCode/Monthly_Coding_Challenge/Aug2020/Find_All_Duplicates_in_an_Array.py
1,129
3.953125
4
from typing import List class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: """ Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example: Input: [4,3,2,7,8,2,3,1] Output: [2,3] Args: nums (List[int]): [description] Returns: List[int]: [description] """ i = 0 while i < len(nums): if nums[i] == i+1 or nums[i] == nums[nums[i]-1]: i += 1 else: nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] # nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] # THIS IS NO GOOD. ORDER MATTERS return [nums[x] for x in range(len(nums)) if nums[x] != x+1] def main(): s = Solution() nums = [4, 3, 2, 7, 8, 2, 3, 1, 4] ans = s.findDuplicates(nums) print(ans) if __name__ == '__main__': main()
8cb5ab4f1ccbd2ce090e5aaa8be12b60b81e7ca5
nathanlct/cp
/project_euler/53.py
734
3.6875
4
""" There are exactly ten ways of selecting three from five, 12345: 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 In combinatorics, we use the notation C(3, 5) = 10. In general, C(r, n) = n! / (r! (n - r)!) for r <= n. It is not until n >= 23, that a value exceeds one-million: C(10, 23) = 1144066 How many, not necessarily distinct, values of C(r, n) for 1 <= n <= 100, are greater than one-million? """ fact_memoiz = { 0: 1 } def fact(n): if n not in fact_memoiz: fact_memoiz[n] = n * fact(n - 1) return fact_memoiz[n] def binomial(r, n): return fact(n) // (fact(r) * fact(n - r)) ans = 0 for n in range(1, 101): for r in range(n): if binomial(r, n) > 1e6: ans += 1 print(ans)
9bc0819dfc68a94b14910e8c33751ca86869cbe8
jonfisik/ScriptsPython
/Scripts3/exercicio1.py
1,078
4.28125
4
print('-----'*10) frase1 = input(' Digite uma frase: ') print(' A frase >> {} << será "fatiada".'.format(frase1)) print(' ',frase1[3]) print(' ',frase1[6:]) print(' ',frase1[:6]) print(' ',frase1[4:10]) print(' ',frase1[::2]) print(' O tamanho da frase é {} '.format(len(frase1))) print('-----'*10) print(' O caracter "a" repete {} vezes.'. format(frase1.count('a'))) print(' O caracter "e" repete {} vezes.'. format(frase1.count('e'))) print(' O caracter "i" repete {} vezes.'. format(frase1.count('i'))) print(' O caracter "o" repete {} vezes.'. format(frase1.count('o'))) print(' O caracter "u" repete {} vezes.'. format(frase1.count('u'))) print('-----'*10) print(' Tudo maiúsculo! --> {}'.format(frase1.upper())) print(' Tudo minúsculo! --> {}'.format(frase1.lower())) print(' Tudo captalizado! --> {}'.format(frase1.capitalize())) print(' Título! --> {}'.format(frase1.title())) print('-----'*10) print(' {} existe a palavra "física" na frase.'.format('física' in frase1)) print(' Frase em forma de lista: {}'.format(frase1.split())) print('-----'*10)
da0047c0fd4264ed22474955e5d39bc0b5da708d
andylws/SNU_Lecture_Computing-for-Data-Science
/HW4/P8.py
1,890
4.0625
4
""" A sparse vector is a vector whose entries are almost all zero, like [1, 0, 0, 0, 0, 0, 3, 0, 0, 0]. Storing all those zeros in a list wastes memory, so programmers often use dictionaries instead to keep track of just the nonzero entries. For example, the vector shown earlier would be represented as {0:1, 6:3}, because the vector it is meant to represent has the value 1 at index 0 and the value 3 at index 6. The sum of two vectors is just the element-wise sum of their elements. For example, the sum of [1, 2, 3] and [4, 5, 6] is [5, 7, 9]. Implement a function that takes two sparse vectors stored as dictionaries and returns a new dictionary representing their sum. * Condition: All entries of vector are integers. >>> P8({0:1, 6:3}, {0:2, 5:2, 6:2, 7:1}) {0:3, 5:2, 6:5, 7:1} >>> P8({0:1, 6:3}, {0:-1, 5:2, 6:2, 7:1}) {6: 5, 5: 2, 7: 1} >>> P8({0:1, 6:3}, {0:-1, 1:1, 2:2, 6:-3}) {1: 1, 2: 2} >>> P8({0:1, 6:-3}, {0:-1, 6:3}) {} """ def P8(dct1, dct2): def dictToVector(dct): vector = [] keyList = [] for key in dct: keyList.append(key) keyList.sort() for i in range(keyList[-1] + 1): if i in keyList: vector.append(dct[i]) else: vector.append(0) return vector def sumVector(v1, v2): resultVector = [] while len(v1) * len(v2) != 0: resultVector.append(v1.pop(0) + v2.pop(0)) resultVector = resultVector + v1 + v2 return resultVector def vectorToDict(v): resultDict = {} for i in range(len(v)): if v[i] != 0: resultDict[i] = v[i] else: continue return resultDict vector1 = dictToVector(dct1) vector2 = dictToVector(dct2) result = vectorToDict(sumVector(vector1, vector2)) return result
e13d3e962f94204a2b6578722cfc279dd4089b2b
Donal-lynch/CMPU4060
/lab6.py
2,613
3.84375
4
# Exercise 1: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def counter(num): for i in range(1, num+1): print (i, end = ' ') print() counter(5) print('*--------------------*') # Exercise 2: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def even_checker(num): # Output wants a comma between each print out, but not at end end = ', ' for i in range(num+1): if i % 2 == 0: print(i, 'is even', end = end) else: print(i, 'is odd', end = end) if i == num-1: end = '.' print() even_checker(4) print('*--------------------*') # Exercise 3: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def times_tables(num): for i in range(num+1): print(i, '* 9 =', i*9) print() times_tables(12) print('*--------------------*') # Exercise 4: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def add_up(num): i = 0 for j in range(1, num+1): i += j print (i) add_up(6) print (1 + 2 + 3 + 4 + 5 + 6) print('*--------------------*') # Exercise 5: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def factorial(num): i = 1 for j in range(2, num+1): i*= j print(i) factorial(5) print(5*4*3*2) print('*--------------------*') # Exercise 6: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def head_and_tail(string): if len(string) < 4: print('string should have 4 or more characters') else: return string[:2] + string[-2:] print(head_and_tail('hello there')) print('*--------------------*') # Exercise 7: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def odd_out(string): return string[1:len(string):2] print(odd_out('1a2a3a4a5a6a7a8a9b')) print('*--------------------*') # Exercise 8: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def string_first_half(string): return (string[0:int(len(string)/2)]) print(string_first_half('Python')) print('*--------------------*') # Exercise 9: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def insert_sting_middle(out_string, in_string): return out_string[:int(len(out_string)/2)] + in_string + out_string[int(len(out_string)/2):] print(insert_sting_middle('{{}}', 'PHP')) print('*--------------------*') # Exercise 10: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def remove_substring(string, pos1, pos2): return string[:pos1] + string[pos2+1:] print(remove_substring('Hello there', 2, 6))
d325e095fe2042d2a26e6f152674f0489c71d1b8
SRIVARSHINEE/Guvi-task
/loopuntil.py
113
3.71875
4
a=input("please enter the name"); q=quit; if(a==q): print("quit"); else: print("please enter the name");
b2f3d16d1df7b4a01d950fae9d6962eb39bd4683
swapnil96/Data-Structures-and-Algorithms
/Maths/fibonacci_efficient.py
282
3.828125
4
past_fib = {} def fibonacci(n): '''Using recursion but storing value each time''' if n in past_fib: return past_fib[n] if n == 0 or n == 1: past_fib[n] = 1 return 1 total = fibonacci(n-1) + fibonacci(n - 2) past_fib[n] = total return total print fibonacci(999)
d3a7c66f84a07d16eddeb27604751172147c8997
aschmied/advent-of-code-2016
/day03/main.py
1,121
4
4
def main(): with open('input') as f: matrix = parse_input(f.read()) print count_triangles_in_horizontal_triples(matrix) print count_triangles_in_horizontal_triples(transpose(matrix)) def transpose(matrix): to_l = lambda t: list(t) return map(to_l, zip(*matrix)) def parse_input(input): out = [] for line in input.strip().split('\n'): out.append(parse_line(line)) return out def parse_line(line): ints_as_strings = filter(None, line.strip().split(' ')) return map(int, ints_as_strings) def count_triangles_in_horizontal_triples(matrix): number_triangles = 0 for row in matrix: number_triangles += count_triangles_in_triples(row) return number_triangles def count_triangles_in_triples(array): number_triangles = 0 for start in xrange(0, len(array), 3): end = start + 3 candidate_sides_lengths = array[start:end] if do_side_lengths_form_a_triangle(candidate_sides_lengths): number_triangles += 1 return number_triangles def do_side_lengths_form_a_triangle(sides): sides.sort() return sides[0] + sides[1] > sides[2] if __name__ == '__main__': main()
b023bff4ca58a1bb9dd3abaafd236635bed4ab07
ilshadrin/lesson3
/date.py
522
3.875
4
''' Напечатайте в консоль даты: вчера, сегодня, месяц назад Превратите строку "01/01/17 12:10:03.234567" в объект datetime ''' from datetime import datetime, timedelta dt_now = datetime.now() print('today ',dt_now) delta = timedelta(days=1) print('yesterday ',dt_now-delta) delta2 = timedelta(days=30) print('month ago ',dt_now-delta2) date_string='01/01/17 12:10:03.234567' a=datetime.strptime(date_string, '%m/%d/%y %H:%M:%S.%f') print(a)
e3737f53f5170387fc2ea3743fccfb6cf3ecf6f5
murilosleite/PycharmProjects
/pythonExercicios/ex013.py
205
3.6875
4
salario = float(input('Qual o salário do funcionário? ')) novosal = salario * (1 + 0.15) print('O Funcionário que ganhava R${}, com um aumento de 15%, passa a receber R${:.2f}'.format(salario, novosal))
e02c89231e0de77787cda6b2a37c87268bafda46
DatBiscuit/Projects_and_ChallengeProblems
/Projects/Roll_A_Dice/dice.py
802
3.5
4
import random import time def six_sided(): min = 1 max = 6 print("Rolling dice...") time.sleep(2) return random.randint(min,max) def four_sided(): min = 1 max = 4 print("Rolling dice...") time.sleep(2) return random.randint(min,max) def eight_sided(): min = 1 max = 8 print("Rolling dice...") time.sleep(2) return random.randint(min,max) def ten_sided(): min = 1 max = 10 print("Rolling dice...") time.sleep(2) return random.randint(min,max) def twelve_sided(): min = 1 max = 12 print("Rolling dice...") time.sleep(2) return random.randint(min,max) def twenty_sided(): min = 1 max = 20 print("Rolling dice...") time.sleep(2) return random.randint(min,max) print(four_sided())
c432106c59437e3007183c69cd75e2684986fff6
junnnnn06/python
/06.単位変換.py
643
4
4
''' 単位変換プログラム  ''' def print_menu(): print('1.kmをmilesへ') print('2.milesをkmへ') def km_miles(): km = float(input('Kmを入力してください')) miles = km / 1.609 print('kmをmileに直すと...{0}になります'.format(miles)) def miles_km(): miles = float(input('マイルを入力してください')) km = miles * 1.609 print('mileをkmに直すと...{0}になります.'.format(km)) if __name__ == '__main__': print_menu() choice = input('希望の処理を選んでください') if choice == '1': km_miles() if choice == '2': miles_km()
52a320e22597a98261153957417137f2ecc4ac19
MussabTanveer/Python-Programming
/10-FilesAndExceptions/remember_me.py
1,417
4.21875
4
# Refactoring # improve the code by breaking it up into a series of functions is called refactoring # makes your code cleaner, easier to understand, and easier to extend import json """ def greet_user(): filename = "username.json" try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: username = input("Enter your name: ") with open(filename, "w") as f_obj: json.dump(username, f_obj) print("We'll remember you next time, " + username.title() + "!") else: print("Welcome back, " + username + "!") """ def get_stored_username(): """Get stored username if available""" filename = "username.json" try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: return None else: return username def get_new_username(): """Prompt for a new username""" username = input("Enter your name: ") filename = "username.json" with open(filename, "w") as f_obj: json.dump(username, f_obj) return username def greet_user(): """Greet user by name""" username = get_stored_username() if username: print("Welcome back, " + username + "!") else: username = get_new_username() print("We'll remember you next time, " + username.title() + "!") greet_user()
829bcd737d0ec6a2d55419bb09435d2b4ca76b23
inno-v/regexpgen
/src/regexpgen/__init__.py
12,328
4.1875
4
# -*- coding: utf-8 -*- ''' Set of functions to generate regular expressions from a pattern similar to printf function. ''' import builder import re def integer(frmt, minV = None, maxV = None): """ Generating regular expression for integer numbers (-2, -1, 0, 1, 2, 3...). :param frmt: format similar to C printf function (description below) :param minV: optional minimum value :param maxV: optional maximum value :return: regular expression for a given format Supported formats: FORMAT = '%d' description: leading zeros are optional, correct examples: -1, -005, 0, 1, 001, 012 incorrect examples: N/A FORMAT = '%0d' description: leading zeros are forbidden correct examples: -2, -2123, 0, 1, 255 incorrect examples: 001, 012 FORMAT = '%0Xd' description: number written with X characters, in case of number lesser than int('9'*X) it should be leaded with zeros, correct examples for %04d: 0001, 5678 incorrect examples for %04d: 00011, 111 Examples of use: >>> import regexpgen >>> regexpgen.integer("%0d", -10, 10) '^(-?([0-9]|10))$' >>> regexpgen.integer("%04d", -10, 10) '^(-?(000[0-9]|0010))$' """ b = builder.RegexpBuilder() return b.createIntegerRegex(frmt, minV, maxV) def nnint(frmt, minV = None, maxV = None): """ Generating regular expression for a non negative integer numbers. :param frmt: format similar to C printf function (description below) :param minV: optional minimum value :param maxV: optional maximum value :return: regular expression for a given format Generating regular expressions for non-negative integers (0, 1, 2, 3...). Supported formats: see :py:class:`regexpgen.integer` Examples of use: >>> import regexpgen >>> regexpgen.nnint("%0d") '^([1-9][0-9]*|0)$' >>> regexpgen.nnint("%04d", 71, 85) '^(007[1-9]|008[0-5])$' """ b = builder.RegexpBuilder() return b.createNNIntegerRegex(frmt, minV, maxV) def real(frmt, minV = None, maxV = None): """ Generating regular expressions for real numbers with accuracy of float() function. :param frmt: format similar to C printf function (description below) :param minV: optional minimum value :param maxV: optional maximum value :return: regular expression for a given format Supported formats: FORMAT = '%lf' description: leading zeros are optional correct examples: 0.1, 1.32, 001.21, 012.123 FORMAT = '%0lf' description: leading zeros are forbidden correct examples: 22.1, 1.1 incorrect examples: 001.2, 012.9 FORMAT = '%0.Ylf' description: leading zeros are forbidden, after the comma exactly Y characters are expected correct examples for %0.1lf: 22.1, 1.1 incorrect examples for %0.1lf: 001.2, 012.9 FORMAT = '%.Ylf' description: leading zeros are optional, after the comma exactly Y characters are expected correct examples for %0.1lf: 022.1, 1.1, 001.2, 012.9 incorrect examples for %0.1lf: 3.222, 0.22 FORMAT = '%X.Ylf' description: X is ignored (works like '%.Ylf') FORMAT = '%0X.Ylf' description: leading zeros are required, number written with at least X characters (including dot), after the comma exactly Y characters are expected, if number of characters is lesser than X, it should be leaded with zeros correct examples for %5.1lf: 002.1, 32431.2, 022.9 incorrect examples for %5.2lf: 22.111, 1.1 Examples of use: >>> import regexpgen >>> regexpgen.real("%lf", -1.5, 2.5) '^(-?(0*((0)\\.0|(0)(\\.(([0-9])[0-9]*))|(1)(\\.(([0-3]|4)[0-9]*))|(1)\\.50*))|0*((1)\\.5|(1)(\\.(5|([5-9])[0-9]*))|(2)(\\.(([0-3]|4)[0-9]*))|(2)\\.50*))$' >>> regexpgen.real("%0.1lf", -1.0, 2.0) '^(-?(((0)\\.(([0-9]))|(1)\\.0))|((1)\\.(([0-9]))|(2)\\.0))$' """ b = builder.RegexpBuilder() return b.createRealRegex(frmt, minV, maxV) def time(frmt, minV = None, maxV = None): """ Generating regular expressions for time. :param format: format similar to C printf function (description below) :param min: optional minimum value :param max: optional maximum value :return: regular expression for a given format Supported formats consists following syntaxes: %H hours (00..23) %I hours (00..12) %M minutes (00..59) %S seconds (00..59) %p AM or PM %P am or pm Additional information: :It is possible to add a time zone to the regexp - it should be added directly to format, eg. "%H:%M:%S +01" :%I must come with %p or %P :%H can not come with %I, %p or %P :%P and %p can not come together :%H can not come with %S without %M :%P and %p can not be only syntaxes Examples of use: >>> import regexpgen >>> regexpgen.time("%H:%M", "12:24", "17:59") '^(12\\:(2[4-9]|[3-4][0-9]|5[0-9])|(1[3-5]|16)\\:[0-5][0-9]|17\\:[0-5][0-9])$' >>> regexpgen.time("%I-%M-%S %P", "10-00-00 PM", None) '^(10\\-00\\-[0-5][0-9]\\ PM|10\\-(0[1-9]|1[0-9]|[2-4][0-9]|5[0-9])\\-[0-5][0-9]\\ PM|11\\-(0[0-9]|1[0-9]|[2-4][0-9]|5[0-8])\\-[0-5][0-9]\\ PM|11\\-59\\-[0-5][0-9]\\ PM)$' """ b = builder.RegexpBuilder() return b.createTimeRegex(frmt, minV, maxV) def date(frmt, minV = None, maxV = None): """ Generating regular expressions for date. :param format: format similar to C printf function (description below) :param min: optional minimum value :param max: optional maximum value :return: regular expression for a given format Supported formats consists following syntaxes: %d day (01..31) %m month (01..12) %y two last digits of year (00..99) %Y year (four digits) Additional information: :Leap years are supported :Supported years: 1970 - 2099 :%Y or %y can not be only syntaxes :%d can not come with %Y without %m :%Y and %y can not come together Examples of use: >>> import regexpgen >>> regexpgen.date("%Y-%m-%d", "2013-03-15", "2013-04-24") '^(2013\\-03\\-(1[5-9]|2[0-9]|3[0-1])|2013\\-03\\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])|2013\\-04\\-(0[1-9]|1[0-9]|2[0-9]|30)|2013\\-04\\-(0[1-9]|1[0-9]|2[0-4]))$' >>> regexpgen.date("%d/%m", "15/09") '^((1[5-9]|2[0-9]|30)\\/09|(0[1-9]|1[0-9]|2[0-9]|3[0-1])\\/10|(0[1-9]|1[0-9]|2[0-9]|30)\\/11|(0[1-9]|1[0-9]|2[0-9]|3[0-1])\\/12)$' """ b = builder.RegexpBuilder() return b.createDateRegex(frmt, minV, maxV) def concatenate(concatenationList): """ Concatenating regular expressions of integer, real, time and date. :param concatenationList: list of tuples - if tuple has only one element is placed directly into regexp, otherwise appropriate function is called (first parameter of tuple should be string - real, int, date or time) Supported formats consists syntaxtes from integer, real, date and time formats Additional information: It is assumed that user knows if the single element should be escaped or not. Examples of use: >>> import regexpgen >>> regexpgen.concatenate([('int', "%d", 100, 105), ('\.',), ('int', "%d", 250, 255)]) '^((0*(10[0-5]))\\.(0*(25[0-5])))$' >>> regexpgen.concatenate([('date', "%m"), (' ',), ('time', "%M")]) '^(((0[1-9]|1[0-2])) ([0-5][0-9]))$' """ result = "" for element in concatenationList: if len(element) == 1: result += element[0] elif len(element) == 4: b = builder.RegexpBuilder() if element[0] == "int": result += b.createIntegerRegex(element[1], element[2], element[3]).replace("^", "") elif element[0] == "real": result += b.createRealRegex(element[1], element[2], element[3]).replace("^", "") elif element[0] == "date": result += b.createDateRegex(element[1], element[2], element[3]).replace("^", "") elif element[0] == "time": result += b.createTimeRegex(element[1], element[2], element[3]).replace("^", "") else: raise ValueError("Bad input") elif len(element) == 3: b = builder.RegexpBuilder() if element[0] == "int": result += b.createIntegerRegex(element[1], element[2], None).replace("^", "") elif element[0] == "real": result += b.createRealRegex(element[1], element[2], None).replace("^", "") elif element[0] == "date": result += b.createDateRegex(element[1], element[2], None).replace("^", "") elif element[0] == "time": result += b.createTimeRegex(element[1], element[2], None).replace("^", "") else: raise ValueError("Bad input") elif len(element) == 2: b = builder.RegexpBuilder() if element[0] == "int": result += b.createIntegerRegex(element[1], None, None).replace("^", "") elif element[0] == "real": result += b.createRealRegex(element[1], None, None).replace("^", "") elif element[0] == "date": result += b.createDateRegex(element[1], None, None).replace("^", "") elif element[0] == "time": result += b.createTimeRegex(element[1], None, None).replace("^", "") else: raise ValueError("Bad input") else: raise ValueError("Bad input") return "^({0})$".format(result.replace("^", "").replace("$", "")) def auto(frmt, minV = None, maxV = None): """ Generating regular expressions for integer, real, date and time. :param format: format similar to C printf function (description below) :param min: optional minimum value :param max: optional maximum value :return: regular expression for a given format Supported formats: see :py:class:`regexpgen.integer`, :py:class:`regexpgen.real`, :py:class:`regexpgen.date`, :py:class:`regexpgen.time` Additional information: Because single %d occurs as well in integer format and in date format, the integer function is preferred. To generate single %d for date please use regexpgen.date Examples of use: >>> import regexpgen >>> regexpgen.auto("%Y-%m-%d", "2013-03-15", "2013-04-24") '^(2013\\-03\\-(1[5-9]|2[0-9]|3[0-1])|2013\\-03\\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])|2013\\-04\\-(0[1-9]|1[0-9]|2[0-9]|30)|2013\\-04\\-(0[1-9]|1[0-9]|2[0-4]))$' >>> regexpgen.auto("%0d", -10, 10) '^(-?([0-9]|10))$' """ if (frmt is None or not isinstance(frmt, str)): raise ValueError("Bad input") b = builder.RegexpBuilder() integerFormats = frmt in ["%d", "%0d"] or re.match("^%0[0-9]+d$", frmt) integerFormatsNotd = frmt in ["%0d"] or re.match("^%0[0-9]+d$", frmt) realFormats = frmt in ["%lf", "%0lf"] or re.match("^%\.[0-9]+lf$", frmt) or re.match("^%0\.[0-9]+lf$", frmt) or re.match("^%0[1-9][0-9]*\.[0-9]+lf$", frmt) or re.match("^%[1-9][0-9]*\.[0-9]+lf$", frmt) timeFormats = str(frmt).find("%H") >= 0 or str(frmt).find("%I") >= 0 or str(frmt).find("%M") >= 0 or str(frmt).find("%p") >= 0 or str(frmt).find("%P") >= 0 or str(frmt).find("%S") >= 0 dateFormats = str(frmt).find("%d") >= 0 or str(frmt).find("%m") >= 0 or str(frmt).find("%Y") >= 0 or str(frmt).find("%y") >= 0 if integerFormats and realFormats: raise ValueError("Bad input") elif integerFormatsNotd and dateFormats: raise ValueError("Bad input") elif integerFormats and timeFormats: raise ValueError("Bad input") elif realFormats and dateFormats: raise ValueError("Bad input") elif realFormats and timeFormats: raise ValueError("Bad input") elif dateFormats and timeFormats: raise ValueError("Bad input") elif integerFormats: return b.createIntegerRegex(frmt, minV, maxV) elif realFormats: return b.createRealRegex(frmt, minV, maxV) elif dateFormats: return b.createDateRegex(frmt, minV, maxV) elif timeFormats: return b.createTimeRegex(frmt, minV, maxV) else: raise ValueError("Bad input") if __name__ == "__main__": import doctest doctest.testfile("__init__.py")
c804fd55ff64c867b0347babd94b307c5333dcfd
DSouzaM/java-nullness
/dacapo/analysis.py
3,620
3.609375
4
import csv import sys from collections import Counter def read_csv(filename: str): with open(filename, "r") as f: return list(csv.DictReader(f)) def print_stats(filename: str): rows = read_csv(filename) # Total events # events = Counter() # total = 0 # for row in rows: # count = int(row["count"]) # events[row["result"]] += count # total += count # print(f"Total events measured: {total}") # print(f"\tNull values returned: {events['0']} ({100*events['0']/total}%)") # print(f"\tNon-null values returned: {events['1']} ({100*events['1']/total}%)") # print(f"\tExceptions thrown: {events['2']} ({100*events['2']/total}%)") def print_summary(rows, prefix): num_total = sum(int(row["count"]) for row in rows) num_null = sum(int(row["count"]) for row in rows if row["result"] == '0') num_nonnull = sum(int(row["count"]) for row in rows if row["result"] == '1') num_thrown = sum(int(row["count"]) for row in rows if row["result"] == '2') print(f"{prefix}: {num_total}") print(f"\tNull values returned: {num_null} ({100*num_null/num_total}%)") print(f"\tNon-null values returned: {num_nonnull} ({100*num_nonnull/num_total}%)") print(f"\tExceptions thrown: {num_thrown} ({100*num_thrown/num_total}%)") return (num_total, num_null, num_nonnull, num_thrown) overall = print_summary(rows, "Total events measured") rows_with_null_fields = [row for row in rows if '0' in row["fields"]] null_fields = print_summary(rows_with_null_fields, "Events where the receiver has null fields") rows_with_nonnull_fields = [row for row in rows if '0' not in row["fields"]] nonnull_fields = print_summary(rows_with_nonnull_fields, "Events where the receiver has no null fields") rows_with_null_params = [row for row in rows if '0' in row["params"]] null_params = print_summary(rows_with_null_params, "Events where the receiver has null params") rows_with_nonnull_params = [row for row in rows if '0' not in row["params"]] nonnull_params = print_summary(rows_with_nonnull_params, "Events where the receiver has no null params") # rows_by_field_nullity = {} # buckets = 5 # bucket_size = 1.0/buckets # for i in range(buckets): # bucket_min = i*bucket_size # bucket_max = bucket_min + bucket_size # in_bucket = [row for row in rows if ] # Null events # null_rows = [row for row in rows if row["result"] == '0'] # num_null = sum(int(row["count"]) for row in null_rows) # num_null_with_null_params = sum(int(row["count"]) for row in null_rows if '0' in row["params"]) # num_null_with_nonnull_params = sum(int(row["count"]) for row in null_rows if '0' not in row["params"]) # print(f"When a null value was returned,") # print(f"\tOne or more parameter was null: {num_null_with_null_params} ({100*num_null_with_null_params/num_null}%)") # print(f"\tAll parameters were non-null: {num_null_with_nonnull_params} ({100*num_null_with_nonnull_params/num_null}%)") # print() # num_null_with_null_fields = sum(int(row["count"]) for row in null_rows if '0' in row["fields"]) # num_null_with_nonnull_fields = sum(int(row["count"]) for row in null_rows if '0' not in row["fields"]) # print(f"\tOne or more field was null: {num_null_with_null_fields} ({100*num_null_with_null_fields/num_null}%)") # print(f"\tAll fields were non-null: {num_null_with_nonnull_fields} ({100*num_null_with_nonnull_fields/num_null}%)") if __name__ == "__main__": print_stats(sys.argv[1])
7c7763dff0b481bd8c20ed2877b1fcb54c7f384a
gabrielrps/MIT-6.00.1x
/Final Test/is_list_permutation.py
976
3.8125
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 21 22:00:43 2020 @author: gabri """ L1 = [1, 'b', 1, 'c', 'c', 1] L2 = ['c', 1, 'b', 1, 1, 'c'] def isPermutation(list1,list2): if len(list1) != len(list2): return False; #two list does not have same length so impossible being permutation of each other for i in range(0, len(list1)): if list1.count(list1[i]) != list2.count(list1[i]): return False def is_list_permutation(list1,list2): if (isPermutation(list1,list2) == False): #use the above method isPermutation to check if they are permutation of each other return False #if not return false elif not list1: return (None, None, None) else: mostOccurItem = max(set(list1), key=list1.count) numberOfTimes = list1.count(mostOccurItem) theType = type(mostOccurItem) return (mostOccurItem, numberOfTimes, theType) print(is_list_permutation(L1,L2))
8694a6b72f0480ddf5fcf503f6293b7f54aea2ef
pBouillon/codesignal
/arcade/intro/3_Exploring_the_Waters/alternatingSums.py
926
3.96875
4
""" Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on. You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete. Example For a = [50, 60, 60, 45, 70], the output should be alternatingSums(a) = [180, 105]. Input/Output [execution time limit] 4 seconds (py3) [input] array.integer a Guaranteed constraints: 1 ≤ a.length ≤ 10, 45 ≤ a[i] ≤ 100. [output] array.integer """ def alternatingSums(a): l1 = [a[x] for x in range(len(a)) if x%2 == 0] l2 = [a[x] for x in range(len(a)) if x%2 != 0] return [sum(l1), sum(l2)]
e0b94be27aa3950952fa34539b28a1e1f19ce998
RosemaryDavy/Python-Code-Samples
/Chapter2.py
2,033
4.21875
4
#Rosemary Davy import time import intro import Chapter1 def ch2choice1(): print("Your train has arrived at Union Station.") time.sleep(1) print("There are people asking for donations.") time.sleep(2) ch2choice1 = input("Will you give them money? Press 1 for yes or 2 for no.") ch2choice1 == " " while ch2choice1 != "1" and ch2choice1 != "2": ch2choice1 = input("Will you give them money? Press 1 for yes or 2 for no.") if ch2choice1 == "1": print("That was nice of you! You received 2 extra hours of daylight.") time.sleep(1) if ch2choice1 == "2": print("Okay. Let's move on.") time.sleep(1) def ch2CircleBack(): intro.intro() intro.ready() Chapter1.ch1choice() ch2choice1() print("Now what would you like to do?") time.sleep(1) print("You can take a train ride home or walk to the Sears Tower.") time.sleep(1) ch2choice2 = input("Press 1 to get on a train or 2 to go to the tower.") ch2choice2 == " " while ch2choice2 != "1" and ch2choice2 != "2": ch2choice2 = input("Press 1 to get on a train to go home or 2 to go to the tower.") if ch2choice2 == "1": print("Okay.") time.sleep(1) intro.ch2CircleBack() if ch2choice2 == "2": print("Okay. The Sears Tower is just down the street.") time.sleep(1) def ch2choice2(): print("Now what would you like to do?") time.sleep(1) print("You can take a train ride home or walk to the Sears Tower.") time.sleep(1) ch2choice2 = input("Press 1 to get on a train or 2 to go to the tower.") ch2choice2 == " " while ch2choice2 != "1" and ch2choice2 != "2": ch2choice2 = input("Press 1 to get on a train to go home or 2 to go to the tower.") if ch2choice2 == "1": print("Okay.") time.sleep(1) ch2CircleBack() if ch2choice2 == "2": print("Okay. The Sears Tower is just down the street.") time.sleep(1) #ch2choice1() #ch2choice2()