blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
8aac003c68d88e5eb5a51bc7bdef6399f4a9ee14
landrea-velez/pyton-45
/medio-avanzado/Ejercicio1.py
457
4.125
4
# Ejercicio 1: Dado un número natural x, mostrar su último dígito. # Concepto matemático x = int(input("Ingresa un número natural: ")) if x >= 0: ultimo_digito = x % 10 print("El último dígito es:", ultimo_digito) else: print("Oops!, ingresa un número natural") # Estilo Python x = input("Ingresa un número natural: ") if x.isnumeric(): print("El último dígito es:", x[-1]) else: print("Oops!, ingresa un número natural")
fa001f637528afd1f812c35233aa74ed7d960a04
smridhisharma/assignment-4
/asignment4.py
700
3.875
4
#ques 1 lst=[1,2,3,4,5] lst.reverse() print(lst) #ques 2 strt=input("enter the string") null=" " for i in strt: if i.isupper(): null=null+i+',' print(null) #ques 3 lst=[] lst1=[] p=input() lst=p.split(',') for i in range (len(lst)): lst1.append(int(lst[i])) print(type(lst1[0])) print(lst1) #ques 4 number=(input('enter no')) temp=number rev=number[::-1] if(temp==rev): print("pallindrome") else: print("not a pallindrome") #ques 5 #shallow copy import copy as c list1=[1,2,[3,4],5] list2=c.copy(list1) list1[2][0]='sam' print(list1) print(list2) #ques 6 #deep copy import copy as c list1=[1,2,[3,4],5] list2=c.deepcopy(list1) list1[2][1]='sam' print(list1) print(list2)
dcdecca9f7b411f98ef0943022cccfe710509741
roadsidegravel/advent-of-code
/2019/Day 03/tests.py
7,528
3.609375
4
import unittest # unittest most used asserts: # self.assertEqual(a,b) # self.assertFalse(bool) # self.assertTrue(bool) # self.assertRaises(error) # https://docs.python.org/3/library/unittest.html # def setUp(self): # def tearDown(self): # def suite for custom test suite building (which tests to run) from WireGrid import wireGrid,ManhattanDistance,wirePath class testWireGrid(unittest.TestCase): def test_EmptyWireGrid(self): wireLayout = wireGrid() origin = wireLayout.O self.assertEqual(0,origin.x,f'origin x coordinate should be 0') self.assertEqual(0,origin.y,f'origin y coordinate should be 0') def test_ManhattanDistance5x6y(self): result = ManhattanDistance(5,6) self.assertEqual(11,result,f'Manhattan distance for 5,6 should be 11') def test_ManhattanDistance0xminus5y(self): result = ManhattanDistance(0,-5) self.assertEqual(5, result, f'Manhattan distance for 0,-5 should be 5') def test_wirePathR3(self): wire = wirePath(['R3']) result = wire.locations self.assertEqual(4,len(result),f'R3 should be 4 positions, O and 0,1 0,2 0,3') self.assertEqual(0, result[0].x, f'R3 should be 4 positions, O and 0,1 0,2 0,3') self.assertEqual(0, result[0].y, f'R3 should be 4 positions, O and 0,1 0,2 0,3') self.assertEqual(1, result[1].x, f'R3 should be 4 positions, O and 0,1 0,2 0,3') self.assertEqual(0, result[1].y, f'R3 should be 4 positions, O and 0,1 0,2 0,3') self.assertEqual(2, result[2].x, f'R3 should be 4 positions, O and 0,1 0,2 0,3') self.assertEqual(0, result[2].y, f'R3 should be 4 positions, O and 0,1 0,2 0,3') self.assertEqual(3, result[3].x, f'R3 should be 4 positions, O and 0,1 0,2 0,3') self.assertEqual(0, result[3].y, f'R3 should be 4 positions, O and 0,1 0,2 0,3') def test_wirePathU2(self): wire = wirePath(['U2']) result = wire.locations self.assertEqual(3,len(result),f'U2 should be 3 positions, O, and 1,0 2,0') self.assertEqual(0, result[0].x, f'U2 should be 3 positions, O, and 1,0 2,0') self.assertEqual(0, result[0].y, f'U2 should be 3 positions, O, and 1,0 2,0') self.assertEqual(0, result[1].x, f'U2 should be 3 positions, O, and 1,0 2,0') self.assertEqual(1, result[1].y, f'U2 should be 3 positions, O, and 1,0 2,0') self.assertEqual(0, result[2].x, f'U2 should be 3 positions, O, and 1,0 2,0') self.assertEqual(2, result[2].y, f'U2 should be 3 positions, O, and 1,0 2,0') def test_wirePathL1(self): wire = wirePath(['L1']) result = wire.locations self.assertEqual(2, len(result), f'L1 should be 2 positions, O, and -1,0') self.assertEqual(0, result[0].x, f'L1 should be 2 positions, O, and -1,0') self.assertEqual(0, result[0].y, f'L1 should be 2 positions, O, and -1,0') self.assertEqual(-1, result[1].x, f'L1 should be 2 positions, O, and -1,0') self.assertEqual(0, result[1].y, f'L1 should be 2 positions, O, and -1,0') def test_wirePathD1(self): wire = wirePath(['D1']) result = wire.locations self.assertEqual(2, len(result), f'D1 should be 2 positions, O, and 0,-1') self.assertEqual(0, result[0].x, f'D1 should be 2 positions, O, and 0,-1') self.assertEqual(0, result[0].y, f'D1 should be 2 positions, O, and 0,-1') self.assertEqual(0, result[1].x, f'D1 should be 2 positions, O, and 0,-1') self.assertEqual(-1, result[1].y, f'D1 should be 2 positions, O, and 0,-1') def test_wirePathXUnknownCatcher(self): #had eerder gemoeten #https://medium.com/python-pandemonium/testing-sys-exit-with-pytest-10c6e5f7726f with self.assertRaises(SystemExit) as e: wirePath(['X2']) self.assertEqual('@wirepath, requested direction not understood: X',e.exception.code) def test_wirePathL2D1(self): wire = wirePath(['L2','D1']) result = wire.locations self.assertEqual(4,len(result)) self.assertEqual(-2,result[-1].x) self.assertEqual(-1,result[-1].y) def test_wirePathExampleDay3(self): wire = wirePath(['R8','U5','L5','D3']) result = wire.locations self.assertEqual(3,result[-1].x) self.assertEqual(2,result[-1].y) def test_wireGridTwoWires(self): wireALocations = wirePath(['R8','U5','L5','D3']).locations wireBLocations = wirePath(['U7','R6','D4','L4']).locations wiresOnGrid = wireGrid([wireALocations,wireBLocations]) lastWireAOnGrid = wiresOnGrid.wireLocations[0][-1] lastWireBOnGrid = wiresOnGrid.wireLocations[1][-1] self.assertEqual(3,lastWireAOnGrid.x) self.assertEqual(2,lastWireAOnGrid.y) self.assertEqual(2,lastWireBOnGrid.x) self.assertEqual(3,lastWireBOnGrid.y) def test_wireGridIntersections(self): wireALocations = wirePath(['R8','U5','L5','D3']).locations wireBLocations = wirePath(['U7','R6','D4','L4']).locations wiresOnGrid = wireGrid([wireALocations, wireBLocations]) intersections = wiresOnGrid.intersections self.assertEqual(2,len(intersections)) ManhattanX1 = ManhattanDistance(intersections[0].x,intersections[0].y) self.assertEqual(11,ManhattanX1) ManhattanX2 = ManhattanDistance(intersections[1].x,intersections[1].y) self.assertEqual(6,ManhattanX2) def test_ManhattanAcceptsXYclass(self): wireALocations = wirePath(['R8', 'U5', 'L5', 'D3']).locations wireBLocations = wirePath(['U7', 'R6', 'D4', 'L4']).locations wiresOnGrid = wireGrid([wireALocations, wireBLocations]) intersections = wiresOnGrid.intersections self.assertEqual(2, len(intersections)) ManhattanX1 = ManhattanDistance(intersections[0]) ManhattanX2 = ManhattanDistance(intersections[1]) self.assertEqual(11, ManhattanX1) self.assertEqual(6, ManhattanX2) def test_ManhattanAcceptsXYList(self): wireALocations = wirePath(['R8', 'U5', 'L5', 'D3']).locations wireBLocations = wirePath(['U7', 'R6', 'D4', 'L4']).locations wiresOnGrid = wireGrid([wireALocations, wireBLocations]) intersections = wiresOnGrid.intersections Manhattans = ManhattanDistance(intersections) self.assertEqual(2,len(Manhattans)) self.assertEqual(11,Manhattans[0]) self.assertEqual(6,Manhattans[1]) def test_Example1(self): path = 'example1' wiresExample1 = wireGrid(path) closestManhattan = wiresExample1.closestManhattan self.assertEqual(159,closestManhattan) def test_Example2(self): path = 'example2' wiresExample2 = wireGrid(path) closestManhattan = wiresExample2.closestManhattan self.assertEqual(135,closestManhattan) def test_speedup(self): #self.assertEqual('day3','solution correct but its way too slow') #made changes to _intersections, slow part found and fixed pass def test_intersectionDistanceExample1part2(self): path = 'part2example1' wiresOnGrid = wireGrid(path) closest = wiresOnGrid.shortedDistance self.assertEqual(610,closest) def test_intersectionDistanceExample2part2(self): path = 'part2example2' wiresOnGrid = wireGrid(path) closest = wiresOnGrid.shortedDistance self.assertEqual(410,closest) if __name__ == '__main__': unittest.main()
dbf955ac45f680b12bb4e2a35fb0b200a0534e13
JeeHwan21/CS550
/Currency.py
545
4.09375
4
# Dollars to Yen dollars = float(input("Dollars: ")) yen = dollars * 111.61 # * is only for floating numbers and integers # print(type(dollars)) print("Yen: " + str(yen)) # print("Yen:", yen) - the comma creates a space x = '5.5' # int(x) - error # float(x) = 5.5 x = '5' # int(x) = 5 # float(x) = 5. x = 3.7 # int(x) = 3 farenheit = float(input("Farenheit: ")) celcius = (farenheit - 32) * 5 / 9 print("Celcius:", celcius) if celcius > 25: print("You should wear lightly today!") else: print("You should wear warm clothes today!")
7d2179d537301a4aee932ff4689888b7d72e7802
Kate-Pod/Hangman_game
/Hangman.py
2,024
3.703125
4
# Игра Виселица def hangman(word): wrong = 0 #сколько неправильных предположений сделано stages = ["_____________ ", "| | ", "| | ", "| O ", "| / | \ ", "| / \ ", "| ", ] rletters = list(word) board = ["__"] * len(word) #визуал - какие буквы уже угаданы (или ничего: __ __ __) win = False #победил ли уже игрок? print("Добро пожаловать на казнь") while wrong < len(stages): print("\n") #для лучшего отображения msg = "Введите букву: " char = input(msg) if char in rletters: #если значение буквы-догадки содержится в загаданном слове cind = rletters.index(char) #находим индекс этой буквы в загаданном слове board[cind] = char #обновляем board-вывод визуального отображения rletters[cind] = '$' #заменяем правильно угаданный символ в слове знаком $ (чтобы в случае повторяющихся букв, алгоритм не выводил один и тот же индекс) else: wrong += 1 print((" ".join(board))) e = wrong + 1 print("\n".join(stages[0: e])) if "__" not in board: print("Вы выиграли! Было загадано слово:") print(" ".join(board)) win = True break if not win: print("\n".join(stages[0:wrong])) print("ВЫ проиграли! Было загадано слово: {}.".format(word))
05314df3545b3df0bf7bc422ae835a3554ccd30c
iambenkay/project-euler
/problem10.py
303
3.875
4
def is_prime(n): if n == 1 or n == 0: return False if n == 2 or n == 3: return True if n % 2 == 0: return False for i in range(2, int(n/2)): if n % i == 0: return False return True print(sum([i for i in range(1, 2000000) if is_prime(i)]))
9ae4c7e0bf70fc532bfa26f0b498370dc015c014
jeffysam6/July-Leetcoding-Challenge
/day-13-same-tree.py
1,081
3.828125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: if(p and q): return p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right) return p is q # stack = [(p,q)] # while(stack): # pnode,qnode = stack.pop() # if(not pnode and not qnode): # continue # elif(None in [pnode,qnode]): # return False # else: # if(pnode.val != qnode.val): # return False # stack.append((pnode.left,qnode.left)) # stack.append((pnode.right,qnode.right)) # return True
298bdfe27cecee06bef8f56fd2fe849f15f64cd5
rachelzhang1/python-practice
/binaryTreeandStack.py
2,421
3.578125
4
from stackADT import Stack from binaryTreeClass import Binary_tree import operator def build_parse_tree(parse_exp): p_list = parse_exp.split() p_stack = Stack() r = Binary_tree('') p_stack.push(r) current_tree = r for i in p_list: if i == '(': current_tree.insert_left('') p_stack.push(current_tree) current_tree = current_tree.get_left_child() elif i not in ['+','-','*','/',')']: current_tree.set_root_val(int(i)) parent = p_stack.pop() current_tree = parent elif i in ['+','-','*','/']: current_tree.set_root_val(i) current_tree.insert_right('') p_stack.push(current_tree) current_tree = current_tree.get_right_child() elif i == ')': current_tree = p_stack.pop() else: raise ValueError return r def evaluate(parse_tree): opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv} left = parse_tree.get_left_child() right = parse_tree.get_right_child() if left and right: fn = opers[parse_tree.get_root_val()] return fn(evaluate(left), evaluate(right)) else: return parse_tree.get_root_val() # external method of preorder - better because we may want traversal and use it to do other things def preorder(tree): if tree: print(tree.get_root_val()) preorder(tree.get_left_child()) preorder(tree.get_right_child()) # internal method of preorder def preorder_internal(self): print(self.key) if self.left_child: self.left.preorder() else: self.right_child: self.right.preorder() def postorder(tree): if tree != None: postorder(tree.get_left_child()) postorder(tree.get_right_child()) print(tree.get_root_val()) def inorder(tree): if tree != None: inorder(tree.get_left_child()) print(tree.get_root_val()) inorder(tree.get_right_child()) def print_exp_inorder(tree): str_val = "" if tree: str_val = '(' + print_exp_inorder(tree.get_left_child()) str_val = str_val + str(tree.get_root_val()) str_val = str_val + print_exp_inorder(tree.get_right_child()) + ')' return str_val def postorder_eval(tree): opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv} res1 = None res2 = None if tree: res1 = postorder_eval(tree.get_left_child()) res2 = postorder_eval(tree.get_right_child) if res1 and res2: return opers[tree.get_root_val()](res1, res2) else: return tree.get_root_val pt = build_parse_tree("((3+5)*2") pt.postorder()
9f011fecaa585d887065941ff578acc89fa91b12
trunghieult1807/AI
/csp/n_queen.py
1,455
3.875
4
import numpy as np def isViolateRow(matrix, row): for i in range(matrix.shape[0]): if matrix[row][i] == 1: return True return False def isViolateDiagonal(matrix, row, col): i = 0 while row + i < matrix.shape[0] or row - i >= 0 or col + i < matrix.shape[0] or col - i >= 0: if row + i < matrix.shape[0] and col + i < matrix.shape[0] and matrix[row + i][col + i] == 1: return True if row + i < matrix.shape[0] and col - i >= 0 and matrix[row + i][col - i] == 1: return True if row - i >= 0 and col + i < matrix.shape[0] and matrix[row - i][col + i] == 1: return True if row - i >= 0 and col - i >= 0 and matrix[row - i][col - i] == 1: return True i += 1 return False def nqueens(matrix, col=0): for row in range(matrix.shape[0]): if not isViolateRow(matrix, row) and not isViolateDiagonal(matrix, row, col): matrix[row][col] = 1 if col == matrix.shape[0] - 1: return True flag = nqueens(matrix, col + 1) if not flag: matrix[row][col] = 0 else: return True return False def main(): n = int(input("Enter n(greater than 3) : ")) matrix = np.zeros([n, n], dtype=int) if nqueens(matrix): print(matrix) else: print("No solution") if __name__ == "__main__": main()
f575855b8e7e6b3ad4122918940b525f7f48986a
acganesh/euler
/114_CountingBlockCombinations.py
316
3.703125
4
def main(n): vals = [1,1,1,2,4] #Recursive solution: f(n) = f(n-1) + f(n-4) + f(n-5) + ...+ f(1) + f(0) + 1 #Analogous to previous solution length = 5 while length < n+1: val = vals[-1]+1 for i in range(length-3): val += vals[i] vals.append(val) length += 1 print vals return val print main(50)
94cd9776c6fc47ec3b2780838b17985a48e71db6
JCapestany/CS-126-Python
/LAB2/gamebook.py
6,077
3.9375
4
# Jose Capestany and Adam Douglass # CS126L # 2/5/2016 # Lab2: Game Book success_mountains = '''You eventually come across a mountain town. The citizens offer you a ride home. You finally escape the woods. YOU SURVIVED THE WOODS!''' success_river = '''You keep moving on and encounter a forest ranger cabin. The rangers help you return home. YOU SURVIVED THE WOODS!''' print("Game Book: Survive the woods!") print("=============================") print("You decide to go hunting.") print("What type of weapon do you bring?") weapon = input("SHOTGUN, BOW, or RIFLE: ").lower() # Three choices print("You become lost in the woods and you do not know where you are going.") print("You come across a fork in the woods.") print("To the left you see a river and the right heads toward the mountains.") print("Which way do you go?") fork = input("RIGHT or LEFT: ").lower() if fork == "right": print("On the way towards the mountains you spot a bear in your path.") print("The bear notices you and starts approaching.") print("What do you do?") bear = input("RUN, NOTHING, APPROACH: ").lower() # Three choices if bear == "run": print("The bear starts chasing you.") print("It catches you and mauls you to pieces.") print("YOU DIED!") elif bear == "nothing": print("The bear continues to approach you.") print("What do you do?") nothing = input("FIRE or NOTHING: ").lower() if nothing == "fire": if weapon == "shotgun": print("You fire your shotgun but miss the bear.") print("The bear comes after you and kills you.") print("YOU DIED!") elif weapon == "bow": print("You hit the bear with your arrow.") print("The now angry bear chases you and catches you.") print("You are shredded to pieces.") print("YOU DIED!") elif weapon == "rifle": print("You fire your rifle.") print("You hit the bear square in the eyes.") print("The bear drops dead and you proceed past its corpse.") print(success_mountains) elif nothing == "nothing": print("The bear stops and leaves the trail after a few seconds.") print("You move on ahead.") print(success_mountains) elif bear == "approach": print("The bear takes this as a sign of aggression.") print("The bear starts running towards you.") print("What do you do?") approach = input("NOTHING or FIRE: ").lower() if approach == "nothing": print("The bear kills you.") print("YOU DIED!") elif approach == "fire": if weapon == "bow": print("You fire your bow.") print("The bear isn't fazed.") print("It reaches you and shreds you to pieces.") print("YOU DIED!") elif weapon == "rifle": print("You fire your rifle.") print("You hit the bear in its shoulder.") print("However, it continues running towards you.") print("It reaches you and swipes you.") print("YOU DIED!") elif weapon == "shotgun": print("You fire your shotgun.") print("The bear stops dead in its tracks and falls over dead.") print("You move on ahead.") print(success_mountains) elif fork == "left": print("You reach the bank of the river.") print("The river seems crossable.") print("Do you cross the river?") river = input("YES or NO: ").lower() if river == "no": print("You head downstream of the river.") print("Another hunter mistakes you for a deer and fires at you.") print("The shot kills you instantly.") print("YOU DIED!") elif river == "yes": print("You managed to cross the river.") print("You are exhausted and decide to take a break.") print("How long is your break?") rest = float(input("LENGTH OF BREAK IN MINUTES: ")) # Numerical comparison if rest >= 60: print("You take a nice long break.") print(success_river) elif rest >= 10: print("You take a break.") print("You keep moving on ahead and encounter a bobcat.") print("What do you do?") bobcat = input("RUN or FIRE: ").lower() if bobcat == "run": print("The bobcat chases you and bites you in the throat.") print("YOU DIED!") elif bobcat == "fire": if weapon == "bow": print("You fire your bow.") print("You hit the bobcat in its throat.") print(success_river) elif weapon == "shotgun" or weapon == "rifle": print("You can't fire your weapon because it is wet.") print("The bobcat pounces and bites you in the throat.") print("YOU DIED!") elif rest < 10: print("You take a short break.") print("You keep moving on ahead and encounter a bobcat.") print("What do you do?") bobcat = input("RUN or FIRE: ").lower() if bobcat == "run": print("The bobcat chases you and bites you in the throat.") print("YOU DIED!") elif bobcat == "fire": if weapon == "bow": print("You fire your bow.") print("Your exhaustion causes you to miss.") print("The bobcat pounces and bites you in the throat.") print("YOU DIED!") elif weapon == "shotgun" or weapon == "rifle": print("You can't fire your weapon because it is wet.") print("The bobcat pounces and bites you in the throat.") print("YOU DIED!")
4564ef17632ee26c8af040a007578a2bff1c3f25
dhengkt/CourseProjects
/Python/110/Grades.py
607
4
4
# Grades # HsinYu Chi(Katie) # This program will assign leter grades, # after getting an exam score as input. def getInput(): #x = round(eval(input("Enter your grade: ")),2) x = 82 return(x) def calcGrade(s): if s >= 90: grade = "A" elif s >= 80: grade = "B" elif s >= 70: grade = "C" elif s >=60: grade = "D" else: grade = "F" return(grade) def main(): score = getInput() letterGrade = calcGrade(score) print(letterGrade) #OutputResult(score,letterGrade) main()
ba75712e6e4f42cfaf6532a88baf3dc915c72981
haodam87/array-
/assignment2.py
672
4.15625
4
# palindrome=input(("Enter a word:")) # if(palindrome==palindrome [::-1]): # print("Yes") # else: # print("No") def palindrome(): word= input("Enter a word:") originalword = [] palindromecheck = [] for index in range(0, len(word)): originalword.append(word[index]) print(originalword) for index in range(len(word) -1, -1, -1): palindromecheck.append(word[index]) print(palindromecheck) for index in range(0, len(word)): if originalword[index] != palindromecheck[index]: return input('This is not a Palindrome') return input("This is a Palindrome") print(palindrome())
b9a6a96437c0e7debf712191fbd21c0ed8341b4d
Ryuchi25/pythonintask
/task_9_12.py
2,156
3.671875
4
# Задача 9. Вариант 12 # #Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. #Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, #есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". #Вслед за тем игрок должен попробовать отгадать слово.. # Курятников П.В # 25.05.2016 import random slova =( "человек", "метрология", "программирование ", "горожанин", "умиротворение") slovo = random.choice(slova) tries = 5 length = len(slovo) print(''' Здравствуйте! Добро пожаловать в игру 'Угадай букву'! В данной игре я загадываю случайное слово, а вы по буквам должны его отгадать. Называете букву, а я говорю: есть ли она в загаданном слове. У вас есть 5 попыток!''') print("В загаданном слове",length, "букв.") look_for = input("Введите букву\n") while tries>1: if look_for in slovo: print("Вы угадали, такая буква в слове есть!") else: print("Оу... в этом слове нет такой буквы") tries -=1 print("у вас еще",tries,"попыток") look_for =input("Введите букву\n") print("Теперь ваша задача: угадать слово целиком. Вам помогут угаданные буквы") ugaday =input("Итак, ваше слово\n") if ugaday == slovo: ptint('Вы совершенно правы! Вы победили!') else: print("Слово угадано неверно, вы проиграли. Правильный ответ:\n", slovo) input("Нажмите Enter для выхода.")
84fe676a8accd51c869739e9e487343e6a22fe8a
purujeet/internbatch
/fact.py
109
4.0625
4
i=int(input('Enter the number')) fact=1 while(i!=1): fact=fact*i i=i-1 print('Factorial is:',fact)
5285281a76221d941bddfb90fbdfcd37cf5b2ac4
Lagom92/TIL
/Algorithm/BOJ/sort_inside.py
462
3.53125
4
# 백준 1427번 소트인사이드 # https://www.acmicpc.net/problem/1427 ''' 내림차순으로 정렬하기 ''' # sort(reverse=True) 사용 nums = list(int(i) for i in input()) nums.sort(reverse=True) for n in nums: print(n, end='') # 다른 사람 코드 ''' 9 ~ 0까지 순회하면서 array에 해당 숫자가 있으면 출력 ''' array = input() for i in range(9, -1, -1): for j in array: if int(j) == i: print(i, end='')
83b224bc079bbb0dec07b4a0353ef3e51d605c1f
ishantk/KnowledgeHutHMS2020
/Session1C.py
985
3.5
4
# Single Value Containers instagram_id = "auribises" print("instagram id is:", instagram_id) print("HashCode of instagram_id is:", id(instagram_id)) print("Type of instagram_id is:", type(instagram_id)) age = 10 print("Type of age is:", type(age)) pi = 3.14 print("Type of pi is:", type(pi)) print() # Multi Value Container # Tuple -> MVC i.e. contains lot of data :) # Homogeneous Multi Value Container followers = "john", "jennie", "jim", "jack", "joe" print("Followers is:", followers) print("Followers HashCode is:", id(followers)) print("Followers Type is:", type(followers)) print("followers[0] is:", followers[0]) print("followers[0] HashCode is:", id(followers[0])) print() # Hetrogeneous Multi Value Container data = "john", 10, 3.3, "sia" print(data) print(type(data)) # Limitation on Tuple or Feature of Tuple # we can not modify tuple after it is created :) # Tuple is IMMUTABLE, once created cannot be modified :) # followers[1] = "jennie watson" # del followers[0] error
630d0600686ffbdb15b5bdaca32987a252efec98
Fabricio-Lopees/computer-science-learning
/exercises/01.python-for-everybody/chapter03/ex01.py
317
3.984375
4
# Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours. # Enter Hours: 45 # Enter Rate: 10 # Pay: 475.0 hours = int(input('Enter hours: ')); rate = float(input('Enter rate: ')); if hours > 40: rate = rate * 1.5 pay = hours * rate; print('Pay',pay);
fbf7b296a7a053be9b4452fc127b66290bb2e852
moon0331/baekjoon_solution
/level2/1181.py
170
3.828125
4
N = int(input()) words = [] for _ in range(N): words.append(input()) words = list(set(words)) words.sort() words.sort(key=len) for word in words: print(word)
09386445d5c4cf2f62ebfad7dce4bc0125fbe8c1
Ashik549/Stock-Price-Prediction
/Final_stock.py
3,342
3.65625
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 9 17:26:27 2018 @author: Md. Ashikur Rahman """ import pandas as pd import datetime import matplotlib.pyplot as plt import numpy as np from sklearn import preprocessing, model_selection from sklearn.linear_model import LinearRegression import math import matplotlib.pyplot as plt def cost_function(X, Y, B): m = len(Y) J = np.sum((X.dot(B.T) - Y) ** 2)/(2 * m) return J def gradient_descent(X, Y, B, alpha, iterations): cost_history = [0] * iterations m = len(Y) for iteration in range(iterations): # Hypothesis Values h = X.dot(B.T) # Difference b/w Hypothesis and Actual Y loss = h - Y # Gradient Calculation gradient = X.T.dot(loss) / m # Changing Values of B using Gradient B = B - alpha * gradient # New Cost Value cost = cost_function(X, Y, B) cost_history[iteration] = cost return B, cost_history def multiple_regression (X, Y): B = np.array ([0, 0, 0, 0, 0, 0]) #initial coef alpha = 0.0001 inital_cost = cost_function(X_train, Y_train, B) newB, cost_history = gradient_descent(X_train, Y_train, B, alpha, 100000) return newB # Model Evaluation - RMSE def rmse(Y, Y_pred): rmse = np.sqrt(sum((Y - Y_pred) ** 2) / len(Y)) return rmse # Model Evaluation - R2 Score def r2_score(Y, Y_pred): mean_y = np.mean(Y) ss_tot = sum((Y - mean_y) ** 2) ss_res = sum((Y - Y_pred) ** 2) r2 = 1 - (ss_res / ss_tot) return r2 '''# we will look at stock prices over the past year pd.set_option('display.max_rows',100) pd.set_option('display.max_columns',10) pd.set_option('display.max_colwidth',10) pd.set_option('display.width',None) ''' apple=pd.read_csv('AAPL.csv') type(apple) pd.core.frame.DataFrame apple.head() #pure microsoft=pd.read_csv('MSFT.csv') google=pd.read_csv('GOOG.csv') facebook = pd.read_csv('FB.csv') twitter = pd.read_csv ('TWTR.csv') snap_inc = pd.read_csv ('SNAP.csv') # Below I create a DataFrame consisting of the adjusted closing price of these stocks, first by making a list of these objects and using the join method stocks = pd.DataFrame ({"AAPL": apple ["Adj Close"], "MSFT": microsoft ["Adj Close"], "GOOG": google ["Adj Close"], "FB": facebook ["Adj Close"], "TWTR": twitter ["Adj Close"], "SNAP": snap_inc ["Adj Close"]}) stocks.fillna (-99999, inplace = True) forecast_out = int (math.ceil (0.005 * len (stocks))) stocks ['TWTR'] = stocks ['TWTR'].shift (-forecast_out) X = np.array (stocks.drop (['TWTR'], 1)) X = preprocessing.scale (X) m = len (stocks) X0 = np.ones (m, dtype = np.float64) X = np.insert (X, 0, X0, axis = 1) X_lately = X [-forecast_out:] X = X [:-forecast_out] stocks.dropna (inplace = True) Y = np.array (stocks ['TWTR']) #OLS import statsmodels.formula.api as sm X_opt = X regressor_OLS = sm.OLS (endog = Y, exog = X_opt).fit () regressor_OLS.summary () #Final X_train, X_test, Y_train, Y_test = model_selection.train_test_split (X_opt, Y, test_size = 0.2, random_state = 4) #X_train = X_train.T coef = multiple_regression (X_train, Y_train) Y_pred = X_test.dot(coef) print(rmse(Y_test, Y_pred)) print(r2_score(Y_test, Y_pred))
b099a4db74ecd5f74fc71607371165b4e252461d
S-M-J-I/Python-Codes
/Python Basic,Advanced, OOP/Python Basics/Dictionary_example.py
1,040
3.84375
4
# Dictionary example #1 Create a user profile for your new game. This user profile will be stored in a dictionary with keys: 'age', 'username', 'weapons', 'is_active' and 'clan' user_profile = { 'age':20, 'username':'Skyabyss', 'weapons':['pistol','shotgun','rifle','assault-rifle'], 'is_active':True, 'clan':'Grimhold Reapers' } #2 iterate and print all the keys in the above user. print(user_profile.keys()) print() #3 Add a new weapon to your user # list value in weapons key user_profile['weapons'].append("knife") # accessing key, then list #4 Add a new key to include 'is_banned'. Set it to false user_profile.update({"is_banned":False}) #5 Ban the user by setting the previous key to True user_profile['is_banned'] = True #6 create a new user2 my copying the previous user and update the age value and username value. user_profile2 = user_profile.copy() user_profile2.update({ "age":25, "username":"Clairant" }) print(user_profile) print() print(user_profile2)
27824449172c15acb24ae283bc73c680bde8fb6f
parv-jain/programs
/chefrout.py
302
3.578125
4
import re T=int(input()) n=1 while n<=T: S=input() f=0 pattern1=r"^(C)+(E)*(S)*$" pattern2=r"^(E)+(S)*$" pattern3=r"^(S)+$" result1=re.match(pattern1,S) result2=re.match(pattern2,S) result3=re.match(pattern3,S) if (result1 or result2 or result3): print ('yes') else: print ('no') n+=1
f41164a1ce6dde0955e8219509eff34330e59871
SanjanaSrabanti16/urban-chronicles
/preprocessing/Model/categoricalSummary.py
1,808
3.859375
4
class CategoricalSummary: SUM = 1 APPEND = 2 def __init__(self, initClass): ''' this method initialize Categorical Summary object @param initClass initialization Class for "Folha" ''' self.__initializationType = initClass if initClass != "int" else int self.__abstractSummary = {} def insertItem(self, key, subKey, value, insertType): # Getting key Data keyData = self.__abstractSummary.get(key) if keyData is None: keyData = {} self.__abstractSummary[key] = keyData # Getting subkey Data an then do some operations due to insertType subkeyData = keyData.get(subKey) if subkeyData is None: subkeyData = self.__initializationType() # Do some operation if insertType == CategoricalSummary.SUM: subkeyData += value elif insertType == CategoricalSummary.APPEND: subkeyData.append(value) # update Key Data with subkey Data keyData[subKey] = subkeyData def getSummaryFromKey(self, key): """ Get summary from a given key, in this case year will be the key. """ result_aux = self.__abstractSummary.get(key) subKeyFreq = 0 subKeyName = "" for subKey in result_aux: val = result_aux.get(subKey) val_aux = 0 if type(self.__initializationType) is list: val_aux = len(val) if val_aux > subKeyFreq: subKeyFreq = val_aux subKeyName = subKey result = {subKeyName: subKeyFreq} return result def getFullSummaryData(self): return self.__abstractSummary
4d5a3959cbe03c8264d975dee046e655d3740ace
jdurbin/sandbox
/chatGPT/pricecalories2.py
1,003
4.03125
4
#!/usr/bin/env python3 # import necessary libraries import pandas as pd import matplotlib.pyplot as plt # read in the tsv file df = pd.read_csv("beer.tab", sep="\t") # compute the correlation between price and calories corr = df["price"].corr(df["calories"]) # print the correlation print("The correlation between price and calories is: ", corr) # create a scatter plot of price vs calories plt.scatter(df["price"], df["calories"]) plt.xlabel("Price") plt.ylabel("Calories") plt.title("Price vs Calories") plt.show() # Straight out of chatGPT # Only changes were adding shebang and making file name beer.tab. # Prompt: write a python program to read in a tsv file and compute # the correlation between the price and calories columns, then plot # a scatter plot of price vs calories. # The first version was based on numpy and didn't use named columns. # Version three is this one but was presented as a description not # as code. I asked it to convert it to code and got this program.
daf8bf6f14c15d2505f68003c54ef5475254f87f
pflun/advancedAlgorithms
/Amazon-grandparentNode.py
1,105
3.96875
4
# -*- coding: utf-8 -*- # 让你找出所有leaves的 grandparents node。Follow Up:如果是找出所有node距离any leaf with distance k # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def grandparentNode(self, root, k): self.res = [] def dfs(root, ancestors, k): if not root.left and not root.right and len(ancestors) >= k: self.res.append(ancestors[-k].val) ancestors.append(root) if root.left: dfs(root.left, ancestors[:], k) if root.right: dfs(root.right, ancestors[:], k) dfs(root, [], k) return self.res head_node = TreeNode(0) n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(5) n6 = TreeNode(6) head_node.left = n1 head_node.right = n2 n1.left = n3 n1.right = n4 n3.left = n5 n5.right = n6 test1 = Solution() print test1.grandparentNode(head_node, 2) # 0 # 1 2 # 3 4 # 5 # 6
8d940adaa0e9efca4929b5b931b010ce8200bdf8
basyair7/control_led_with_python-GUI
/control_led_rev.py
2,132
3.59375
4
from tkinter import * from tkinter import font as tkfont import serial # create function led def led_1_on(): with board as s: s.write(b'led_1_on') def led_1_off(): with board as s: s.write(b'led_1_off') def led_2_on(): with board as s: s.write(b'led_2_on') def led_2_off(): with board as s: s.write(b'led_2_off') def all_on(): with board as s: s.write(b'all_leds_are_on') def all_off(): with board as s: s.write(b'all_leds_are_off') # Create home App tkinter home = Tk(); home.geometry('260x230') home.title("control led v0.1") # Create label for led 1 lbl_led_1 = Label(home, text="Led 1", font="Purisa") lbl_led_1.grid(row=0, column=1, pady=(10,0)) # Create button for led 1 btn_led_1_on = Button(home, text="Led 1 ON", font="chilanka", command=led_1_on) btn_led_1_on.grid(row=1, column=1, columnspan=2, pady=10, padx=10, ipadx=15) btn_led_1_off = Button(home, text="Led 1 OFF", font="chilanka", command=led_1_off) btn_led_1_off.grid(row=3, column=1, columnspan=2, ipadx=10) # Create label for Led 2 lbl_led_2 = Label(home, text="Led 2", font="Purisa") lbl_led_2.grid(row=0, column=3, pady=(10,0), padx=12) # Create button for led 2 btn_led_2_on = Button(home, text="Led 2 ON", font="chilanka", command=led_2_on) btn_led_2_on.grid(row=1, column=3, columnspan=2, ipadx=15) btn_led_2_off = Button(home, text="Led 2 OFF", font="chilanka", command=led_2_off) btn_led_2_off.grid(row=3, column=3, columnspan=2, ipadx=10) # Create on all led button btn_on = Button(home, text="ON All Led", font="chilanka", command=all_on) btn_on.grid(row=4, column=0, columnspan=2, pady=10, padx=10, ipadx=10) # Create off all Led button btn_off = Button(home, text="OFF All Led", font="chilanka", command=all_off) btn_off.grid(row=4, column=2, columnspan=4, ipadx=6) # Create author app author = Label(home, text="Creator : @basyair7", font="chilanka") author.grid(row=6, column=1, columnspan=5, pady=12, padx=12) # create connect to serial board = serial.Serial('com3', 9600) # see in device manager or port in tool arduino # home window mainloop home.mainloop()
3c0b209d65a1967ec5ba572a1535f901f4fa01d0
kaituoxu/Neural-Network-Python
/checkNNGradients.py
2,718
3.546875
4
#!/usr/bin/env python # coding: utf-8 import numpy as np import NN def debugInitializeWeights(len_out, len_in): """ W = DEBUGINITIALIZEWEIGHTS(len_out, len_in) initializes the weights of a layer with len_in incoming connections and len_out outgoing connections using a fix set of values. """ W = np.zeros((len_out, len_in + 1)) # Initialize W using "sin", this ensures that W is always of the same # values and will be useful for debugging c, r = W.shape W = np.reshape(np.sin(range(1, W.size+1)), (r, c)).T / 10 return W def computeNumericalGradient(J, W): """ COMPUTENUMERICALGRADIENT Computes the gradient using "finite differences" and gives us a numerical estimate of the gradient. """ numgrad = np.zeros(W.shape) perturb = np.zeros(W.shape) epsilon = 1e-4 for i in range(W.shape[0]): for j in range(W.shape[1]): perturb[i][j] = epsilon loss1, _ = J(W - perturb) loss2, _ = J(W + perturb) numgrad[i][j] = (loss2 - loss1) / (2 * epsilon) perturb[i][j] = 0 return numgrad def checkNNGradients(learn_rate): """ checkNNGradients(learn_rate) Creates a small neural network to check the backpropagation gradients, it will output the analytical gradients produced by your backprop code and the numberical gradients (computed using compute- NumericalGradient). These two gradient computations should result in very similar values. """ input_layer_size = 3 hidden_layer_size = 5 num_labels = 3 m = 5 # Generate some 'random' test data W1 = debugInitializeWeights(hidden_layer_size, input_layer_size) W2 = debugInitializeWeights(num_labels, hidden_layer_size) # Generate X, y X = debugInitializeWeights(m, input_layer_size - 1) y = 1 + np.array([i % num_labels for i in range(1, m + 1)]) # Unroll parameters W = np.hstack((W1.flatten(0), W2.flatten(0))) W = W.reshape((len(W), 1)) def costFunc(p): return NN.nnCostFunction(p, input_layer_size, hidden_layer_size, num_labels, X, y, learn_rate) cost, grad = costFunc(W) numgrad = computeNumericalGradient(costFunc, W) for i in range(len(grad)): print "%10f\t%10f" % (grad[i], numgrad[i]) print "The above two lines you get should be very similar.\n" diff = np.linalg.norm(numgrad-grad) / np.linalg.norm(numgrad+grad) print ("If your backpropagation implementation is correct, then" "\nthe relative difference will be small (less than 1e-9).\n" "\nRelative Difference: %g\n") % diff if __name__ == '__main__': checkNNGradients(0)
a4de14956d07c1ac652549cbfc964ec4f8e77ff2
kruschk/etc
/Python/Dec-Hex_Converter.py
1,515
4
4
def hexToDec(): # Get a hexadecimal input from the user and reverse it. hex_in = input("Please enter a hexadecimal number: ").upper() if not hex_in.isalnum(): print("Invalid input! Please try again.") hexToDec() return hex_in = hex_in[::-1] # Initialize variables. hex_list = [] dec_out = 0 idx = 0 # Append each character of the hexadecimal input to a new list, hex_list. for symbol in hex_in: if symbol.isalpha(): if symbol == 'A': hex_list.append(int(10)) elif symbol == 'B': hex_list.append(int(11)) elif symbol == 'C': hex_list.append(int(12)) elif symbol == 'D': hex_list.append(int(13)) elif symbol == 'E': hex_list.append(int(14)) elif symbol == 'F': hex_list.append(int(15)) else: print("Please ensure your number only uses characters from 0 - 9 and A - F inclusive.") hexToDec() return else: hex_list.append(int(symbol)) # Loop through hex_list, multiplying each number by 16 to the power of its index. while idx < len(hex_list): dec_out += hex_list[idx]*16**(idx) idx += 1 # Print and return result. print("In decimal form, that number is equivalent to: %d" % dec_out) return dec_out hexToDec()
948e8fbb67dc9ac338c8a78890a4f30c14a812a5
Hank02/capstone
/capstone.py
9,222
3.5625
4
import sys import urllib.request import time import random import csv import datetime import calendar def get_ticker_list(): # takes in csv file with tickers in Google Finance format # and stores them in list # open file in read mode datafile = open(sys.argv[2], "r") # read file and split by newline reader = datafile.read().strip().split() # store contents into list ticker_list = [] for row in reader: ticker_list.append(row) # close csv file and return datafile.close() print("Ticker list contains {} stocks...".format(len(ticker_list))) return ticker_list def get_historic(ticker_list): # receives a list of tickers and outputs time series with date and close # saves hispotical prices into csv # function takes list of tickers as input # places 0 where no data is available # first ticker in list MUST be the one with the longest series # places newest data at bottom # build URL from Google Finance API chunk1 = "http://www.google.com/finance/historical?q=" chunk2 = "&startdate=Jul+01%2C+2014&output=csv" # create and open outfile outfile = open("histirical_prices.csv", "a") # create writer object writer = csv.writer(outfile) # iterate over list and call Google Finance API for indx, ticker in enumerate(ticker_list): # wait for next call to avoid being blocked by Google time.sleep(random.randint(1, 20)) # add ticker to URL url = chunk1 + ticker + chunk2 # open URL as "response" and read it into "data" with urllib.request.urlopen(url) as response: # read url object and store as string rawdata = response.read().decode('utf-8') # split string into continuous list (D, O, H, L, C, V) splitdata = rawdata.split('\n') # remove last element which is always empty splitdata.pop() # store column headers if indx == 0: outdata = [["Date", ticker]] # keep track of trade days in first ticker only trade_days = 0 # iterate over list... for index, each in enumerate(splitdata): # split each element into list splitter = each.split(',') # reset temporary list temp = [] # skip firs element with column headers if index != 0: # append date [0] and close [4] "fields" temp.append(splitter[0]) temp.append(float(splitter[4])) # append date/close to outdata as a list of two elements outdata.append(temp) trade_days = index else: # store ticker as column header outdata[0].append(ticker) # determine length of series less 1 (header) length = len(splitdata) - 1 # iterate over time series control = 0 for index, each in enumerate(splitdata): # split each element into list splitter = each.split(',') # skip firs element with column headers if index != 0: # append price to outdata outdata[index].append(float(splitter[4])) control += 1 if control < trade_days: for index in range(trade_days - control): control += 1 outdata[control].append(float(0)) print("Done with {}".format(ticker)) # create new list to store data correctly (oldest data first) correctdata = [] # first add headers correctdata.append(outdata[0]) # then add oldest data (at end of outdata) to top of correctdada for each in outdata[::-1]: correctdata.append(each) correctdata.pop() # write date/close to outfile as a list of two elements writer.writerows(correctdata) outfile.close() def update_db(ticker_list): # takes in csv with historical price db # checks latest date in db # downloads prices from said date to last avalable # references ticker_list # open existing csv file data_file = open("histirical_prices.csv", "r") # create reader object reader = csv.reader(data_file) # convert object into list reader = list(reader) # close file data_file.close() # store 0th element of list in last position last_date = reader[-1][0] print("Last trading day on file is {}".format(last_date)) # split to make date easier to work with last_date = last_date.split("-") year = "20" + last_date[2] month = last_date[1] # add leading zero to day, if needed if len(last_date[0]) == 1: day = "0" + last_date[0] else: day = last_date[0] # check if file is up to date today = str(datetime.date.today()) today = today.split("-") # convert month to numeric format today_month = calendar.month_abbr[int(today[1])] # compare today to last date on file if day == today[2] and month == today_month and year == today[0]: print("File is up-to-date!") return # build URL from Google Finance API chunk1 = "http://www.google.com/finance/historical?q=" chunk2 = "&startdate="+month+"+"+day+"%2C"+"+"+year+"&output=csv" # iterate over list and call Google Finance API for indx, ticker in enumerate(ticker_list): # wait for next call to avoid being blocked by Google time.sleep(random.randint(1, 20)) # add ticker to URL url = chunk1 + ticker + chunk2 # open URL as "response" and read it into "data" with urllib.request.urlopen(url) as response: # read url object and store as string rawdata = response.read().decode('utf-8') # split string into continuous list (D, O, H, L, C, V) splitdata = rawdata.split('\n') # remove last element which is always empty splitdata.pop() # remove last element which contains last trading day in DB (repeated) splitdata.pop() # open outfile with existing db outfile = open("histirical_prices.csv", "a") # create writer object writer = csv.writer(outfile) # store column headers if indx == 0: outdata = [["Date", ticker]] # keep track of trade days in first ticker only trade_days = 0 # iterate over list... for index, each in enumerate(splitdata): # split each element into list splitter = each.split(',') # reset temporary list temp = [] # skip firs element with column headers if index != 0: # append date [0] and close [4] "fields" temp.append(splitter[0]) temp.append(float(splitter[4])) # append date/close to outdata as a list of two elements outdata.append(temp) trade_days = index else: # store ticker as column header outdata[0].append(ticker) # determine length of series less 1 (header) length = len(splitdata) - 1 # iterate over time series control = 0 for index, each in enumerate(splitdata): # split each element into list splitter = each.split(',') # skip firs element with column headers if index != 0: # append price to outdata outdata[index].append(float(splitter[4])) control += 1 if control < trade_days: for index in range(trade_days - control): control += 1 outdata[control].append(float(0)) print("Done with {}".format(ticker)) # create new list to store data correctly (oldest data first) correctdata = [] # then add oldest data (at end of outdata) to top of correctdada for each in outdata[::-1]: correctdata.append(each) # remove last element which is always empty correctdata.pop() # remove headers (comment out this line to check ticker alignment) del correctdata[0] # write date/close to outfile as a list of two elements writer.writerows(correctdata) outfile.close() def create_db(): arguments = len(sys.argv) if arguments != 3: print("Please enter path to csv file containing ticker list") return tlist = get_ticker_list() get_historic(tlist) def recent_prices(): arguments = len(sys.argv) if arguments != 3: print("Please enter path to csv file containing ticker list") return tlist = get_ticker_list() update_db(tlist) if __name__ == '__main__': if sys.argv[1] == "create_db": create_db() elif sys.argv[1] == "recent_prices": recent_prices()
82df43af2b45e94d358bf6c9547fffc6ac892d96
harshit4567/Captcha-Decoder
/create_model.py
2,487
3.53125
4
# Importing the Keras libraries and packages import keras from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense import pickle # Initialising the CNN classifier = Sequential() # Step 1 - Convolution classifier.add(Conv2D(32, (3, 3), input_shape=(50, 65, 3), activation='relu')) # Step 2 - Pooling classifier.add(MaxPooling2D(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(Conv2D(32, (3, 3), activation='relu')) classifier.add(MaxPooling2D(pool_size=(2, 2))) classifier.add(Conv2D(64, (3, 3), activation='relu')) classifier.add(MaxPooling2D(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(Flatten()) # classifier.add(Dense(units = 200, activation = 'relu')) # classifier.add(Dense(units = 100, activation = 'relu')) # classifier.add(Dense(units = 128, activation = 'relu')) # Step 4 - Full connection classifier.add(Dense(units=120, activation='relu')) classifier.add(Dense(units=28, activation='softmax')) # classifier.add(Dense(units = 1, activation = 'softmax')) # Compiling the CNN classifier.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # Part 2 - Fitting the CNN to the test_images from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale=1. / 255) test_datagen = ImageDataGenerator(rescale=1. / 255) training_set = train_datagen.flow_from_directory('train_data', target_size=(50, 65), batch_size=32, class_mode='categorical') test_set = test_datagen.flow_from_directory('val_data', target_size=(50, 65), batch_size=32, class_mode='categorical') print(classifier.summary()) classifier.fit_generator(training_set, steps_per_epoch=200, epochs=40, validation_data=test_set, validation_steps=20) # Part 3 - Making predictions predictions classifier.save('store') pickle_out = open("dict.pickle", "wb") pickle.dump(training_set.class_indices, pickle_out) pickle_out.close() file = open('class_indices.txt', 'w') file.write(str(training_set.class_indices)) file.close()
065f431944b6c55eff7a20c1ed7b70d3bc71d79b
appsjit/testament
/LeetCode/ctuoJul/wbTreeHeightBuntoro.py
945
3.53125
4
class Vertex: def __init__(self, id): self.id = id self.edges = [] def deserialize(n, edges): vertices = {} while n > 0: n -= 1 vertices[n] = Vertex(n) # Vertex(7) -- Vertex(1) total 6 for edge in edges: v1 = edge[0] v2 = edge[1] vertices[v1].edges.append(vertices[v2]) vertices[v2].edges.append(vertices[v1]) # vertices[0] = [1] vertices[1] = [0] # UNCOMMENT OUT THIS AREA IF YOU WOULD LIKE TO SEE THE GRAPH YOU'VE BUILT: # # for vertex_key in vertices: # vertex = vertices[vertex_key] # print('\nID: ' + str(vertex.id)) # for edge in vertex.edges: # print('Edge ID: ' + str(edge.id)) return vertices[0] graph = deserialize(6, [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]) def findTree(pgraph, n): print(pgraph) height = [n] * n for x in height: print(x) findTree(graph, 6)
bfded0641726a42528f8b2475c89c37d4b1cbdd0
ccbrantley/Python_3.30
/LibraryManagementSystem/remove.py
999
3.828125
4
def remove_author(cursor): #Necessary Rows = name_first, name_last #Ordered Unique Rows = author_id(auto), name_last, name_first, country print("Remove Author...") name_first = raw_input("Author's First name: ") name_last = raw_input("Author's Last Name: ") cursor.execute("delete from authors where name_first = %s and name_last = %s", (name_first, name_last)) def remove_user(cursor): #Necessary input = name_first, phone #Ordered Unique Rows = UserID(auto), name_first, name_last, phone print("Remove User...") name_first = raw_input("User First Name: ") phone = raw_input("Phone: ") cursor.execute("delete from users where name_first = %s and phone = %s", (name_first, phone)) def remove_book(cursor): #Necessary input = isbn #Ordered Unique Rows = isbn, title, author_id, publisher_id, year_pub, description print("Remove Book...") isbn = raw_input("ISBN: ") cursor.execute("delete from books where isbn = %s", (isbn,))
c43a150d5e0b9c342b3c953eaf8c9ce85e7d3ee5
ajustinpadilla/python_projects
/Student_Tracking/Stu_Track_func.py
4,815
3.765625
4
import os from tkinter import * from tkinter import messagebox import tkinter import sqlite3 # importing other modules import Stu_Track_main import Stu_Track_GUI # Creating the database if it hasn't yet def create_db(self): conn = sqlite3.connect("Student_info.db") with conn: cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS tbl_student_info( \ ID INTEGER PRIMARY KEY AUTOINCREMENT, \ fname TEXT, \ lname TEXT, \ fullname TEXT, \ phone TEXT, \ email TEXT, \ courseTaken TEXT);") conn.commit() conn.close() def onSelect(self, event): varList = event.widget select = varList.curselection()[0] value = varList.get(select) conn = sqlite3.connect("Student_info.db") with conn: cursor = conn.cursor() cursor.execute("""SELECT fname,lname,phone,email,courseTaken FROM tbl_student_info WHERE fullname = (?)""", [value]) varBody = cursor.fetchall() # This returns a tuple and we can slice it into 4 parts using data[] during the iteration for data in varBody: self.txt_fname.delete(0,END) self.txt_fname.insert(0,data[0]) self.txt_lname.delete(0,END) self.txt_lname.insert(0,data[1]) self.txt_phone.delete(0,END) self.txt_phone.insert(0,data[2]) self.txt_email.delete(0,END) self.txt_email.insert(0,data[3]) self.txt_course.delete(0,END) self.txt_course.insert(0,data[4]) def onSubmit(self): fname = self.txt_fname.get().strip().title() lname = self.txt_lname.get().strip().title() #stripping off extra spaces that might have been put in fname = fname.strip() lname = lname.strip() fname = fname.title() lname = lname.title() fullname = ("{} {}".format(fname,lname)) phone = self.txt_phone.get().strip() email = self.txt_email.get().strip() course = self.txt_course.get().strip() if (len(fname) > 0) and (len(lname) > 0) and (len(phone) > 0) and(len(email) > 0) and (len(course) > 0): conn = sqlite3.connect('Student_info.db') with conn: cursor = conn.cursor() cursor.execute("""INSERT INTO tbl_student_info (fname,lname,fullname,phone,email,courseTaken) VALUES (?,?,?,?,?,?)""",(fname, lname, fullname, phone, email, course)) self.lstbox.insert(END, fullname) onClear(self) conn.commit() conn.close() else: messagebox.showerror("Missing Text Error","Please ensure that there is data in all four fields.") def onClear(self): # clear the text in these textboxes self.txt_fname.delete(0,END) self.txt_lname.delete(0,END) self.txt_phone.delete(0,END) self.txt_email.delete(0,END) self.txt_course.delete(0,END) def onDelete(self): selected = self.lstbox.get(self.lstbox.curselection()) conn = sqlite3.connect('Student_info.db') with conn: cur = conn.cursor() # Making sure to not delete the last record to avoid an error cur.execute("""SELECT COUNT(*) FROM tbl_student_info""") count = cur.fetchone()[0] if count > 1: confirm = messagebox.askokcancel("Delete Confirmation", "All information associated with, ({}) \nwill be permenantly deleted from the database. \n\nProceed with the deletion request?".format(selected)) if confirm: conn = sqlite3.connect('Student_info.db') with conn: cursor = conn.cursor() cursor.execute("""DELETE FROM tbl_student_info WHERE fullname = '{}'""".format(selected)) onDeleted(self) conn.commit() else: confirm = messagebox.showerror("Last Record Error", "({}) is the last record in the database and cannot be deleted at this time. \n\nPlease add another record first before you can delete ({}).".format(selected,selected)) conn.close() def onDeleted(self): onClear(self) try: index = self.lstbox.curselection()[0] self.lstbox.delete(index) except IndexError: pass def onRefresh(self): # Populate the listbox, coinciding with the database self.lstbox.delete(0,END) conn = sqlite3.connect('Student_info.db') with conn: cursor = conn.cursor() cursor.execute("""SELECT COUNT(*) FROM tbl_student_info""") count = cursor.fetchone()[0] i = 0 while i < count: cursor.execute("""SELECT fullname FROM tbl_student_info""") varList = cursor.fetchall()[i] for item in varList: self.lstbox.insert(0,str(item)) i = i + 1 conn.close()
7925722dfb957dad1e0fab4d95731d4465a018b9
jgates5/python_learning
/multiple_methods_deleting_items.py
995
4.4375
4
teams = { "astros" : ["Altuve", "Correa", "Bregman"], "angels": ["Trout", "Pujols"], "yankees": ["Judge", "Stanton"], "red sox": ["Price", "Betts"], } #most basic way to delete an item from a dictionary #del teams['astros'] #print(teams) #Results = {'angels': ['Trout', 'Pujols'], # 'yankees': ['Judge', 'Stanton'], # 'red sox': ['Price', 'Betts']} #using get function #print(teams.get('mets', 'No team found by that name')) #results = No team found by that name """using pop to delete the dictionary teams.pop('astros', 'No team found by that name') print(teams) = {'angels': ['Trout', 'Pujols'], 'yankees': ['Judge', 'Stanton'], 'red sox': ['Price', 'Betts']} """ #typing in a key and a name that does not exist #teams.pop('rays', 'No team found by that name') #print(teams) #returns no defalt value or returns the default element #typing in a key and a name that does not exist removed_team= teams.pop('rays', 'No team found by that name') print(teams) print(removed_team)
f352133ce1caab41589f988d1c5a40b6ffed38da
aryan-upa/Python-Lab
/Set_Item_Remove.py
341
4.0625
4
def set_make(x): s = set() for q in range(x): s.add(input('Enter element: ')) return s inp = int(input('Enter number of elements in the set : ')) S = set_make(inp) print(S) st = 'a' while st != '': st = input('enter the element to delete, (just press enter to exit) : ') S.discard(st) print(S)
d94614b20489fbba56e82c2bb4f67360b1b68f5b
ncommella/automate-boring
/exercises/petGuess.py
213
4.0625
4
pets = ['Luger', 'Roman', 'Roxy'] print('Please enter a pet name:') inquiry = input() if inquiry not in pets: print('I do NOT have a pet named ' + inquiry) else: print('I do have a pet named ' + inquiry)
9bde2c81081e657ea4dad1e14e07c2eb80ec38cb
ukrainets/iss
/iss.py
1,183
3.625
4
import requests r = requests.get("http://api.open-notify.org/iss-now.json") status = r.status_code response = requests.get("http://api.open-notify.org/astros.json") data = response.json() # Replasing http status code with text if status == 200: ConStatus = "200 - Connection is OK!" elif status == 400: ConStatus = "400 - Bad Request.\n(Please check your request code for correctness.)" elif status == 404: ConStatus == "404 - Not found.\n(The server has not found anything matching the Request-URI.)" elif status == 500: ConStatus == "500 - Internal Server Error.\n(The server encountered an unexpected condition which prevented it from fulfilling the request.)" else: ConStatus = "Uncnown HTTP status code.\n(http status code doesn't match our records.)" # UI q = input('ISS API \n Type "cnnection" to see conncetion status:\n Type "astros" to see number of astronauts on ISS board:\n') if q == "connection": print("ISS API conection status is:\n", ConStatus) if q == "astros": print("There is", data["number"], "people on ISS now.\n", data) else: print("Ooops, you entered incorrect command \nor \nwe can't check ISS conection status at the moment")
aecd9e03f59e4ac4a01137e8019c8e6428fc3721
Mrweiwei/Python_learning
/Python 代码库/Python 作业/提取字符串中的电话号码.py
592
3.875
4
#使用正则表达式提取字符中的电话号码 import re telNumber='''Suppose my phone number is 0535-1234567,yours is 010-12345678,his is 025-87654321.''' pattern=re.compile(r'(\d{3,4})-(\d{7,8})') index=0 while True: matchResult=pattern.search(telNumber,index) if not matchResult: break print('-'*30) print('success:') for i in range (3): print('Searched content:',matchResult.group(i),\ 'Start from:',matchResult.start(i),'End at:',matchResult.end(i),\ 'Its span is:',matchResult.span(i)) index=matchResult.end(2)
a9bc4635e491003f28dd148ad2d554586586eeb7
christinecoco/python_test
/test47.py
247
3.984375
4
#将两个变量值互换 a=10 b=20 c=a d=b print('a=',d) print('b=',c) #第二种方法使用函数 def exchange(a,b): print('交换前:a=%d,b=%d' % (a, b)) a,b=b,a print('交换后:a=%d,b=%d'%(a,b)) return a,b exchange(10,20)
5fde08e66d6569064df57657f7df4ae952e90019
anna-0/cs50
/cs50x/dna/dna.py
2,064
3.65625
4
from sys import argv import sys import csv # Checks for correct usage if len(argv) != 3: print("Usage: python dna.py data.csv sequence.txt") sys.exit() # Opens and reads sequence.txt with open(argv[2], "r") as sequencefile: sequence = sequencefile.readline() # Initialises list to put STR field names into STRlist = [] # Opens and reads database.csv and puts header STRs into list with open(argv[1], "r") as databasefile: database = csv.DictReader(databasefile) STRlist = database.fieldnames[1:] # Initialises STR values dictionary with value baseline set explicitly to zero, otherwise not all results would be checked against when finding match STRvalues = dict.fromkeys(STRlist, 0) # Sets up to find repeats of STRs as were stipulated in field names STR list for STR in STRlist: maxcount = 0 L = len(STR) count = 0 start = 0 # Finds locations of STRs and checks if they repeat, and tallies up counter. Modified from https://stackoverflow.com/questions/51690245/consecutive-substring-in-python while True: loc = sequence.find(STR, start) if loc == -1: break if start != loc: count = 0 count += 1 start = loc + L else: count += 1 start = loc + L # Sets maximum numbers of STRs found if count > maxcount: maxcount = count # Puts maximum counts into list with corresponding STRs STRvalues[STR] = maxcount # Reopens database file and lists people and their values with open(argv[1], "r") as databasefile: suspects = csv.DictReader(databasefile) # Counts up number of matches between maxcounts and people's numbers, prints if match for person in suspects: match = 0 for STR in STRvalues: if STRvalues[STR] == int(person[STR]): match += 1 if match == len(STRvalues): print(f"{person['name']}") sys.exit(0) # Print no match if none print("No match") sys.exit(1)
37369bceffb8970139aad7157cc7a058aa421cba
YunSeokJun/Mycats
/baekjoon_9012_failToSuccess.py
601
3.671875
4
def VPS(): st_list = input() check = 0 if not st_list: # "입력없을때" return False else: if st_list[0] is ')' or st_list[-1] is '(':# "처음과 마지막 확인" return False for x in st_list: #"괄호 갯수 확인" if x is '(': check = check + 1 else: if check < 0 : return False check = check -1 return not check num = int(input()) result = list() for i in range(num): result.append(VPS()) for i in range(num): if result[i]: print('YES') else: print('NO')
62cd8cced4ae05b6e7a13cfb295c19d6cefb7b46
davemolk/python_practice
/7kyu_vowel_count.py
341
3.578125
4
def get_count(sentence): # count = 0 # for i in list(sentence): # if i in ['a', 'e', 'i', 'o', 'u']: # count += 1 # return count # return len(list(filter(lambda x: x in ['a', 'e', 'i', 'o', 'u'], list(sentence)))) return sum(1 for i in sentence if i in "aeiou") print(get_count('abracadabra'))
3607d5c9a1d9d49d3db7ec6071fb1297d4db5f3e
fgrelard/fgrelard.github.com
/ens/algo/correction_td_recursivite.py
6,620
3.765625
4
# -*- coding: utf-8 -*- ############# # Exercice 1 ############# def factoriel(n): """ Calcul la factorielle de n Exemple: >>> [ factoriel(i) for i in range(5) ] [1, 1, 2, 6, 24] """ if n==0: return 1 return n*factoriel(n-1) ############ # Exercice 2 ############ def suite_exo_2(n): """ Calcul le nième élément de la suite définie par: u_0 = 3 u_n = 2 . u_{n-1} + 1 Exemple: >>> [suite_exo_2(i) for i in range(5)] [3, 7, 15, 31, 63] """ if n == 0: return 3 return 2*suite_exo_2(n-1) + 1 ############ # Exercice 3 ############ def suite_exo3(n): """ Retour la valeur de la suite définie par u_0 = 0 u_1 = 1 u_{n+2} = 2. u_{n+1} - u_{n} + 1 Exemple: >>> [suite_exo3(i) for i in range(5)] [0, 1, 3, 6, 10] """ if n==0: return 0 if n==1: return 1 return 2*suite_exo3(n-1) - suite_exo3(n-2) + 1 ############# # Exercice 4 ############# def binomial(n, k): """ Renvoie la valeur du binomial (n,k). Exemples: >>> n = 0; [ binomial(n,n-i) for i in range(n+1) ] [1] >>> n = 1; [ binomial(n,n-i) for i in range(n+1) ] [1, 1] >>> n = 2; [ binomial(n,n-i) for i in range(n+1) ] [1, 2, 1] >>> n = 3; [ binomial(n,n-i) for i in range(n+1) ] [1, 3, 3, 1] >>> n = 4; [ binomial(n,n-i) for i in range(n+1) ] [1, 4, 6, 4, 1] """ if k == 0 or k == n: return 1 return binomial(n-1,k-1) + binomial(n-1,k) ############# # Exercice 5 ############# def recherche_rec(T, e, idx): if idx >= len(T): return None if T[idx] == e: return idx return recherche_rec(T, e, idx+1) def recherche(T, e): """ Renvoie l'index du premier élément e dans le tableau T, et None sinon. Exemples: >>> recherche([4,2,5,2,4,10,5], 5) 2 >>> recherche([4,2,5,2,4,10,5], 9) >>> recherche([4,2,5,2,4,10,5], 10) 5 """ return recherche_rec(T, e, 0) ############# # Exercice 7 ############# from turtle import * def flocon_rec( distance, n ): if n==0: forward(distance) else: flocon_rec( distance/3.0, n-1 ) left(60) flocon_rec( distance/3.0, n-1 ) right(120) flocon_rec( distance/3.0, n-1 ) left(60) flocon_rec( distance/3.0, n-1 ) def flocon( size=100, n=3 ): """ Dessine un flocon de von Koch INPUT: size : la taille du flocon n : la profondeur de la récursion """ flocon_rec( size, n ) right(120) flocon_rec( size, n ) right(120) flocon_rec( size, n ) right(120) ############# # Exercice 8 ############# from turtle import * from math import sqrt speed(0) def dragon(size, n, go_to_left): if n == 0: forward(size) return if go_to_left: angle = 45 else: angle = -45 left(angle) dragon( ( sqrt(2.0)/2.0 )*size, n-1, True ) right(2*angle) dragon( ( sqrt(2.0)/2.0 )*size, n-1, False ) left(angle) def dragon_rec(size=100, n=10): dragon(size, n, go_to_left=True) ############# # Exercice 9 ############ def compositions(n): """ Renvoie les compositions de n. Exemple: >>> compositions(0) [[]] >>> compositions(1) [[1]] >>> compositions(2) [[1, 1], [2]] >>> compositions(3) [[1, 1, 1], [1, 2], [2, 1], [3]] >>> compositions(4) [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]] """ if n==0: return( [[]] ) res = [] for i in range(1,n+1): for c in compositions( n-i ): res.append( [i] + c ) return res ############# # Exercice 10 ############# def partitions_bornees(n ,max_part): """ Renvoie les partitions de taille n dont les parts sont plus petites que max_part Exemples: >>> partitions_bornees(4, 2) [[2, 2], [2, 1, 1], [1, 1, 1, 1]] """ if n==0: return [[]] res = [] for i in range(min(n,max_part), 0, -1): for p in partitions_bornees( n-i, i ): res.append( [i] + p ) return res def partitions(n): """ Renvoie les partitions de n. Exemples: >>> partitions(0) [[]] >>> partitions(1) [[1]] >>> partitions(2) [[2], [1, 1]] >>> partitions(3) [[3], [2, 1], [1, 1, 1]] >>> partitions(4) [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]] """ return partitions_bornees( n , n ) ############# # Exercice 12 ############# def permutations( n ): """ Renvoie toutes les permutations de taille n. >>> permutations(0) [[]] >>> permutations(1) [[1]] >>> permutations(2) [[2, 1], [1, 2]] >>> permutations(3) [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]] """ if n==0 : return [[]] res = [] for p in permutations( n-1 ): for position in range(n): res.append( p[:position] + [n] + p[position:] ) return res ############# # Exercice 11 ############# def tour_hanoi( taille_tour, depart, arrivee ): """ Résoue le problème des tours de Hanoï. Entrée: taille_tour : la taille de la tour situé sur la position depart depart : la position de départ de la tour (un entier entre 1 et 3) arrivée : la position d'arrivée de la tour (un entier entre 1 et 3) Exemples: >>> tour_hanoi( 0, 1, 3 ) >>> tour_hanoi( 1, 1, 3 ) 1 -> 3 >>> tour_hanoi( 2, 1, 3 ) 1 -> 2 1 -> 3 2 -> 3 >>> tour_hanoi( 3, 1, 3 ) 1 -> 3 1 -> 2 3 -> 2 1 -> 3 2 -> 1 2 -> 3 1 -> 3 >>> tour_hanoi( 4, 1, 3 ) 1 -> 2 1 -> 3 2 -> 3 1 -> 2 3 -> 1 3 -> 2 1 -> 2 1 -> 3 2 -> 3 2 -> 1 3 -> 1 2 -> 3 1 -> 2 1 -> 3 2 -> 3 """ if taille_tour==0 or depart == arrivee: return milieu = 6 - depart - arrivee tour_hanoi(taille_tour-1, depart, milieu) print(str(depart) + " -> " + str(arrivee)) tour_hanoi(taille_tour-1, milieu, arrivee) if __name__ == "__main__": import doctest doctest.testmod()
aa6b6c4c033392d4745b21138f3aaf7c1d857fba
nickrod518/project-euler
/problem12.py
426
3.625
4
tri_num = 0 top_divisors = 0 divisors = 1 while divisors <= 500: for i in range(1, 100): tri_num = tri_num + i divisors = 1 for j in range(1, tri_num//2 + 1): if (tri_num/j) % 1 == 0: divisors = divisors + 1 if divisors > top_divisors: top_divisors = divisors print("TriangleNumber: " + str(tri_num)) print("Divisors: " + str(divisors))
a72adf6d173a145ff1047e4141e0c9d365051755
itzelot/CYPItzelOT
/libro/problemas_resueltos/capitulo1/problema1_8.py
465
3.828125
4
X1 = float(input("Ingresa el valor de la coordenada del eje x del Punto 1:")) Y1 = float(input("Ingresa el valor de la coordenada del eje y del Punto 1:")) X2 = float(input("Ingresa el valor de la coordenada del eje x del Punto 2:")) Y2 = float(input("Ingresa el valor de la coordenada del eje y del Punto 2:")) DIS = ((X1-X2)**2 + (Y1-Y2)**2)**0.5 print(f"La distancia entre los puntos P1 de coordenadas ({X1},{Y1}) y P2 de coordenadas ({X2},{Y2}) es de {DIS}")
e5bd912d7c977d32b92af430306761f6253dae6f
fangjh13/Snippet
/Sort/selection_sort.py
473
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' selection sort ''' def sel_sort(L): for i in range(len(L) - 1): small_index = i small_value = L[i] j = i + 1 while j < len(L): if L[j] < small_value: small_index = j small_value = L[j] j += 1 temp = L[i] L[i] = L[small_index] L[small_index] = temp return L print(sel_sort([1, 34, 4, 5, 1, 1, 4]))
1faf7f47dfe8dcd0821cb441e3be10708ba62ad0
angelodpadron/data-structure-and-algorithms
/Searching/binary_search.py
350
3.609375
4
def bin_search(A, left, right, k): while(left<=right): mid=(left+right)//2 if A[mid]==k: return mid elif A[mid]>k: right=mid-1 else: left=mid+1 return -1 n=int(input()) arr=list(map(int, input().strip().split(' '))) x=int(input()) print (bin_search(arr, 0, n-1, x))
4195b70fb68c585767702cf31041ee98535aea48
ianbel263/geekbrains_python
/lesson_1/task_5.py
920
4.125
4
company_income = int(input('Введите прибыль фирмы: ')) company_costs = int(input('Введите издержки фирмы: ')) if company_income > company_costs: print('Фирма работает с прибылью') company_profit = company_income - company_costs profitability = round(company_profit / company_income * 100, 2) print(f'Рентабельность фирмы составляет: {profitability}%') staff_number = int(input('Введите численность сотрудников фирмы: ')) profit_per_staff = round(company_profit / staff_number, 2) print(f'Прибыль фирмы в расчете на одного сотрудника составляет: {profit_per_staff}') elif company_income < company_costs: print('Фирма работает в убыток') else: print('Фирма работает в ноль')
d682cfc1d9422f84266aa49b437300514ee0fc2b
AmeliaMaier/Project-Euler
/Problem7_10001stPrime.py
1,138
3.953125
4
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? ''' ''' # temp_list = [range(3, 1000000000000000, 2)] not_primes = set([]) count = 1 for possible_prime in range(3,10000000000,2): if not(possible_prime in not_primes): #print(possible_prime) count +=1 print(count) if (count == 10001): #get a memory error when I switch to 10001 print (possible_prime) break else: not_primes.remove(possible_prime) for multiple in range(2,10000): #print(len(not_primes)) not_primes.add(possible_prime*multiple) ''' possible_primes = [True]*2369620 count = 0 for possible_prime, is_prime in enumerate(possible_primes): if possible_prime == 0 or possible_prime == 1: continue if is_prime: count += 1 if(count == 1000): print(possible_prime) break for not_prime in range(possible_prime,len(possible_primes),possible_prime): possible_primes[not_prime] = False ''' [1,2,3,4,...] [3.5.7.9.11.13] ''
883a82dcabbb85f812d3c5c0b8b1ddb66d83de39
PDXDevCampJuly/john_broxton
/python/king_of_tokyo/king_of_tokyo.py
2,221
4.09375
4
__author__ = 'jbroxton' class Monster: def __init__(self): """The Monster Class controls the parameters for a giant, city-smashing monster. The Monster initializes with a name, a status of 'Out of Tokyo', health = 10, and 0 victory points.""" self.name = "Bojangles the Howling Leviathan" self.status = "Out of Tokyo" self.health = 10 self.victory_points = 0 def reset(self): """The reset function sets the Monster's status, health and victory points to their original values""" self.status = "Out of Tokyo" self.health = 10 self.victory_points = 0 def in_tokyo(self): """The in_tokyo function returns a bool, True for 'In Tokyo', False for 'Out of Tokyo' """ if self.status == "In Tokyo": return True else: return False def flee(self): """Return True if the monster would like to flee Tokyo, False for anything else. """ answer = input("Do you want to flee Tokyo? (y or n) >>> ") answer = answer.lower() if answer == "y": return True elif answer == "n": return False def heal(self, balm): """The heal function passes in a balm integer and adds it to the Monster's health. The health cannot exceed 10 """ balm = int(balm) if self.health + balm < 10: self.health = self.health + balm elif self.health + balm >= 10: self.health = 10 def attack(self, damage): """The attack function takes a damage integer and subtracts it from the Monster's health. If the health is less than or equal to zero, the health is 'K.O.'d' """ damage = int(damage) if self.health - damage > 0: self.health = self.health - damage elif self.health - damage <= 0: self.health = "K.O.'d" return self.health def score(self, wins): if self.victory_points + wins < 20: self.victory_points = self.victory_points + wins elif self.victory_points + wins >= 20: self.victory_points = "WINNING" return self.victory_points
6fd457be073eaa0f27862eb3ee2311d2f57680b4
chauhan2000/PFB
/exercise_2.py
180
4.03125
4
user_name = input("Enter your name:") age, year = input("Enter your age and year").split(",") print(f"Your name is {user_name} and your age is {age} and your birth is {year} ")
31743749fa364f7df2afa4633b1913a977479be2
NHRD/The-second
/chapt12/train1.py
258
3.578125
4
class Apple: def __init__(self, w, c, t, k): self.weight = w self.color = c self.taste = t self.kind = k print("Created!") apple = Apple("50", "Red", "Bad", "Fuji") print(apple.color) print(apple.kind)
b68dd02434cabf03814c08f4517ffa8544ff0334
AntonioRafaelGarcia/LPtheHW
/ex19/ex19.py
1,121
4.1875
4
# defines primary function with cheese and crackerbox input variables # prints a series of embedded strings def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("Man that's enough for a party!") print("Get a blanket.\n") # prints string, calls function with specific integer inputs print("We can just give the function numbers directly:") cheese_and_crackers(20, 30) # prints string, assigns integer values to new variables print("OR, we can use variables from our script:") amount_of_cheese = 10 amount_of_crackers = 50 # calls function using new variables cheese_and_crackers(amount_of_cheese, amount_of_crackers) # prints string, calls function with arithmetic variable inputs print("We can even do math inside too:") cheese_and_crackers(10 + 20, 5 + 6) # prints string, calls function with arithmetic variable inputs that combine integer and new variables print("And we can combine the two, variables and math:") cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
3419a6040318821318c1f15349ffc8db96eac757
m04kA/my_work_sckool
/pycharm/Для школы/в разработке/ПанаринЯрослав_Прог_ИР_8.py.py
1,791
3.546875
4
from random import randint import time my_len_mass = int(input('Введите длинну массива: ')) my_num = int(input('Введите число: ')) test = int(input('Введите количество тестов: ')) def app_mass(len_mass): mas = [] for _ in range(len_mass): mas.append(randint(-1000, 1000)) return mas def perebor(mass, num): znach = False for idx in range(len(mass)): if mass[idx] == num: znach = True idx_el = idx break return znach def fast(mass, num): znach = False start = 0 end = len(mass) - 1 while start <= end: mid = (start + end) // 2 if mass[mid] == num: znach = True idx = mid break elif num < mass[mid]: end = mid - 1 else: start = mid + 1 return znach my_mass = app_mass(my_len_mass) my_mass.sort() start_test_1 = [] end_test_1 = [] start_test_2 = [] end_test_2 = [] for i in range(test): start_1 = time.time() start_test_1.append(start_1) test_01 = perebor(my_mass, my_num) end_1 = time.time() end_test_1.append(end_1) start_2 = time.time() start_test_2.append(start_2) test_02 = fast(my_mass, my_num) end_2 = time.time() end_test_2.append(end_2) strt_1 = 0 for el in start_test_1: strt_1 += el strt_1 = strt_1 / test en_1 = 0 for el in end_test_1: en_1 += el en_1 = en_1 / test strt_2 = 0 for el in start_test_2: strt_2 += el strt_2 = strt_2 / test en_2 = 0 for el in end_test_1: en_2 += el en_2 = en_2 / test time_work_1 = en_1 - strt_1 time_work_2 = en_2 - strt_2 print(f'Различие перебора от быстрого поиска на: {time_work_1 - time_work_2}')
43aad2f45693a0633c42166104c5440e44df06c8
wwebb/datasci_course_materials
/assignment3/matrix.py
1,559
3.5
4
__author__ = 'wwebb' import MapReduce import sys matrixDimensionRow = 5 matrixDimensionCol = 5 """ Assume you have two matrices A and B in a sparse matrix format, where each record is of the form i, j, value. Design a MapReduce algorithm to compute the matrix multiplication A x B """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): [matrix, row, col, value] = record #print 'Matrix: {}, i: {}, j: {}, Value: {}'.format(matrix, row, col ,value) if matrix == 'a': for k in xrange(0, matrixDimensionCol): mr.emit_intermediate((row, k), [matrix, col, value]) elif matrix == 'b': for l in xrange(0, matrixDimensionRow): mr.emit_intermediate((l, col), [matrix, row, value]) def reducer(key, list_of_values): (row, col) = key # create blank dictionary for two matrices dictA = {key: 0 for key in xrange(5)} dictB = {key: 0 for key in xrange(5)} total = 0 # populate matrices from list_of_values for (matrix, cell, value) in list_of_values: if matrix == 'a': dictA[cell] = value elif matrix == 'b': dictB[cell] = value # multiply and sum each value through range for x in xrange(5): total += dictA[x] * dictB[x] # emit the row, col, and total mr.emit((row, col, total)) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
561b0d33ea4d9094d746a74d6227c391fecdd15e
nestormarlier/python
/Listas/list.py
1,109
4.15625
4
nombres=["Nestor",38,"Estefy",32,"Julia",4,"Mia",10] print(nombres) print("---------------------------------------") print(nombres[3]) # numero 32 print("---------------------------------------") print(nombres[-8]) print("---------------------------------------") milista=["Mia","Julia","Estefy","Nestor","Julia","Julia"] print("---------------------------------------") print (milista[0:3])#posicion 0 al 2 print (milista[:3])#del principio a la posicion 3-1=2 print (milista[1:2])#de la posicion 1 a la 1=2-1 print (milista[1:3])#de la posicion 1 a la 2=3-1 milista.append("Sandra") print(milista[:]) milista.insert(2, "Juan Pablo") #inserta en la posicion [2] el valor print(milista) print(len(milista)) milista.extend(["Liliana","Mariano","Valen"])#debe ponerse entre corchetes print(milista) print(milista.index("Mariano")) print("Julia"in milista) milista.remove("Julia") print(milista) print(milista.pop()) print(milista) milista2=[3,6,"Perro",False,5.99] print(milista+milista2) milista3=["Perro","Gato","raton",5,False]*3 print(milista3) print(milista.count("Julia")) print(milista3.count("Perro"))
c8f600b01b5160f7f1ffe57f8ff5786eb1d77387
TICK-TAX/Backend
/Result.py
2,892
3.515625
4
class Result: def __init__(self): self.salary_before_tax = 0 self.salary_after_tax = 0 self.tax_0_pay = 0 self.tax_5_pay = 0 self.tax_10_pay = 0 self.tax_15_pay = 0 self.tax_20_pay = 0 self.tax_25_pay = 0 self.tax_30_pay = 0 def get_annual(self, value): return round(value, 2) def get_month(self, value): return round(value / 12, 2) def get_day(self, value): return round(value / (52 * 5), 2) # SALARY BEFORE TAX def get_annual_salary_before_tax(self): return self.get_annual(self.salary_before_tax) def get_month_salary_before_tax(self): return self.get_month(self.salary_before_tax) def get_day_salary_before_tax(self): return self.get_day(self.salary_before_tax) # SALARY AFTER TAX def get_annual_salary_after_tax(self): return self.get_annual(self.salary_after_tax) def get_month_salary_after_tax(self): return self.get_month(self.salary_after_tax) def get_day_salary_after_tax(self): return self.get_day(self.salary_after_tax) # TAX 0% def get_annual_tax_0(self): return self.get_annual(self.tax_0_pay) def get_month_tax_0(self): return self.get_month(self.tax_0_pay) def get_day_tax_0(self): return self.get_day(self.tax_0_pay) # TAX 5% def get_annual_tax_5(self): return self.get_annual(self.tax_5_pay) def get_month_tax_5(self): return self.get_month(self.tax_5_pay) def get_day_tax_5(self): return self.get_day(self.tax_5_pay) # TAX 10% def get_annual_tax_10(self): return self.get_annual(self.tax_10_pay) def get_month_tax_10(self): return self.get_month(self.tax_10_pay) def get_day_tax_10(self): return self.get_day(self.tax_10_pay) # TAX 15% def get_annual_tax_15(self): return self.get_annual(self.tax_15_pay) def get_month_tax_15(self): return self.get_month(self.tax_15_pay) def get_day_tax_15(self): return self.get_day(self.tax_15_pay) # TAX 20% def get_annual_tax_20(self): return self.get_annual(self.tax_20_pay) def get_month_tax_20(self): return self.get_month(self.tax_20_pay) def get_day_tax_20(self): return self.get_day(self.tax_20_pay) # TAX 25% def get_annual_tax_25(self): return self.get_annual(self.tax_25_pay) def get_month_tax_25(self): return self.get_month(self.tax_25_pay) def get_day_tax_25(self): return self.get_day(self.tax_25_pay) # TAX 30% def get_annual_tax_30(self): return self.get_annual(self.tax_30_pay) def get_month_tax_30(self): return self.get_month(self.tax_30_pay) def get_day_tax_30(self): return self.get_day(self.tax_30_pay)
4726d822280f4cffc845e99f0ab658eeb8d04ad8
huangy10/SingingVoice
/utils/format.py
195
3.5625
4
from datetime import datetime def date_to_string(date): return date.strftime('%Y-%m-%d %H:%M:%S %Z') def str_to_date(string): return datetime.strptime(string, '%Y-%m-%d %H:%M:%S %Z')
5b7617ed53954927ec1af7ad2c23e309a22f1fb7
portugalafonso/hackerrank
/03 - Numpy.py
533
3.953125
4
import numpy #Receive an input from the user user_input = input() #Delete spaces and create a string user_input = (user_input.split()) string = "" for i in user_input: string += i #Create a new list with integers input_list = [] first_item_list = False for index in string: if first_item_list == False: input_list.append(int(index)) first_item_list = True else: input_list.append(int(index)) #Convert the list in array my_array = numpy.array(input_list) my_array.shape = (3, 3) print(my_array)
2757ae123881d8f5cc7be371c65bd3f9db01821b
Avani1992/eclipse_project
/extra/number_pairs.py
424
3.578125
4
"""Given two arrays X and Y of positive integers, find number of pairs such that xy > yx (raised to power of) where x is an element from X and y is an element from Y.""" for i in range(int(input())): m,n=input().split() l1=list(map(int,input().split())) l2=list(map(int,input().split())) c=0 for i in l1: for j in l2: if((i**j)>(j**i)): c=c+1 print(c)
358ffc39053e4bb9e7dc89545bdf2bbcc95a3006
forrestjan/Basic-Programming
/Week 03/thuis1.py
323
3.75
4
string = input("Geef een woord: >") count_lower = 0 for i in string: if(i.islower()): count_lower = count_lower+1 print(f"aantal lowercase letters zijn {count_lower}") count_high = 0 for i in string: if(i.isupper()): count_high = count_high + 1 print(f"aantal uppercase letters zijn {count_high}")
5c4d30ae1669a77cee69dea5bf3c68da8d8a0118
shane-burke/Foundations-Homework
/Homework3/burke_homework3_part1.py
2,618
3.609375
4
#Shane Burke #November 2, 2020 #Homework 3 # pip install requests in Terminal #code to install pretty printing from https://pypi.org/project/pprintpp/ # pip install pprintpp in Terminal from pprintpp import pprint as pp import requests #print(data.keys()) #1. print("The documentation can be found at: https://pokeapi.co/docs/v2#namedapiresource") print('\n') #2 and 3. q1_pokemon = 55 url = f"https://pokeapi.co/api/v2/pokemon/{q1_pokemon}" response = requests.get(url) q1_data = response.json() print("The pokemon with the ID number", q1_data['id'], "is", q1_data['name']+".") print(q1_data['name'], "is", q1_data['height']/10, "meters tall.") print("\n") print("~*~*~*~*~*~") print("\n") #4. id = 1 url = f"https://pokeapi.co/api/v2/version?offset=0&limit=100" response = requests.get(url) q4_data = response.json() #pp(q4_data) print("There are", q4_data['count'], "versions. They are:") q4_test_list = list(range(1, 34)) for test in q4_test_list: print("---", (q4_data)['results'][test]['name']) #Tested this out and 35 gave an error, as did 0, but this range does not. print("\n") print("~*~*~*~*~*~") print("\n") #5. url = f"https://pokeapi.co/api/v2/type/13" response = requests.get(url) q5_data = response.json() print("There are", len(q5_data['pokemon']), "electric type pokemon. They are:") q5_list = list(range(1, len(q5_data['pokemon']))) for electric_pokemon in q5_list: print("---", q5_data['pokemon'][electric_pokemon]['pokemon']['name']) print("\n") print("~*~*~*~*~*~") print("\n") #6. #I pretty printed pp(q5_data['names']) and saw the Korean name second in the list print("In Korean, the electric pokemon are called", q5_data['names'][1]['name']) print("\n") print("~*~*~*~*~*~") print("\n") #7. pokemon = ['eevee', 'pikachu'] eevee = ['eevee'] pikachu = ['pikachu'] for pokemon_name in pokemon: #print(pokemon_name) url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}" response = requests.get(url, allow_redirects=True) data = response.json() #pp data.keys() #pp(data['stats'][5]['base_stat']) if pokemon_name == "eevee": eevee_speed = data['stats'][5]['base_stat'] if pokemon_name == "pikachu": pikachu_speed = data['stats'][5]['base_stat'] if eevee_speed > pikachu_speed: print("Eevee has a higher speed stat (", eevee_speed, ") than Pikachu (", pikachu_speed, ").") elif pikachu_speed > eevee_speed: print("Pikachu has a higher speed stat (", pikachu_speed, ") than Eevee (", eevee_speed, ").") elif pikachu_speed == eevee_speed: print("Pikachu and Eevee have the same speed stat, at", pikachu_speed + ".")
93f7e52e2f5baa328686a10dbfb03a6d8042508e
rtemperv/challenge
/src/extra/closest_pair.py
703
3.875
4
import sys def find_closest_pair(arr1, arr2, x): """ Find i and j such that arr1[i] + arr2[j] - x are minimal """ if not arr1 or not arr2: return None i = 0 j = 0 turn = True last_minimum = abs(arr1[i] + arr2[j] - x) global_minimum = (last_minimum, i, j) while (i + 1 < len(arr1) ) or (j + 1 < len(arr2)): if turn and i + 1 < len(arr1): i += 1 else: j += 1 new_minimum = abs(arr1[i] + arr2[j] - x) if new_minimum > last_minimum: turn = not turn global_minimum = min((new_minimum, i, j), global_minimum) last_minimum = new_minimum return global_minimum
1c6c569ff13c4c8a7cf53791e3b7428fbc54532e
arjunrkaushik/SolveMySudoku
/solver.py
1,333
3.5625
4
def findEmpty(x): for i in range(len(x)): for j in range(len(x[0])): if x[i][j] == 0: return (i, j) # row, col return None def valid(x, num, pos): # row check for i in range(len(x[0])): if x[pos[0]][i] == num and pos[1] != i: return False # col check for i in range(len(x)): if x[i][pos[1]] == num and pos[0] != i: return False # box check box_x = pos[1] // 3 box_y = pos[0] // 3 for i in range(box_y*3, box_y*3 + 3): for j in range(box_x * 3, box_x*3 + 3): if x[i][j] == num and (i,j) != pos: return False return True def solve(x): find = findEmpty(x) if not find: return True else: row, col = find for i in range(1,10): if valid(x, i, (row, col)): x[row][col] = i if solve(x): return True x[row][col] = 0 return False def board(x): for i in range(len(x)): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - - ") for j in range(len(x[0])): if j % 3 == 0 and j != 0: print(" | ", end="") if j == 8: print(x[i][j]) else: print(str(x[i][j]) + " ", end="")
b7dd15dfe009522e9330fccf5133dcf511e48ec0
pforderique/Python-Scripts
/MIT_Courses/MIT 6.006/pset_code/past_psets/pset1/find_first_missing_element.py
956
3.6875
4
################################################## ## Problem 4.4. Find order ################################################## # Given a list of positive integers and the starting integer d, return x such that x is the smallest value greater than # or equal to d that's not present in the list def find_first_missing_element(arr, d): ''' Inputs: arr (list(int)) | List of sorted, unique positive integer order id's d (int) | Positive integer of smallest possible value in arr Output: - (int) | The smallest integer greater than or equal to d that's not present in arr ''' if len(arr) == 0: return d if len(arr) == 1: if d != arr[0]: return d return arr[0] + 1 mid = (len(arr)) // 2 if arr[mid] == d + mid: return find_first_missing_element(arr[mid:], d + mid) else: return find_first_missing_element(arr[:mid], d)
e30a432ac90d2a23ef8564076d42d7722596d043
chukstobi/first_repo
/classes/class_assignment.py
1,188
4
4
read_or_write = input("What would you like to do \n R for read W for write: ") if read_or_write.lower() == "w": name = input("Please enter your Username: ") password = input("Please enter your password: ") user_detail_file = open("data/{}_detail.csv".format(name), "w") user_detail_file.write(f"{name},{password}") database = open(f"data/{name}_database.txt", "a") data = input("please enter your symptom \nH for Headache N for Nothing: ") if data.lower() == "h": vomiting = ("Feeling nauseous\nY/N: ") elif data.lower()== "n": print("You fine!") database.write(f"{data}\n") elif read_or_write.lower() == "r": name = input("Please enter your unsername: ") password_input = input("Please enter your password: ") user_detail_file = open("data/{}_detail.csv".format(name), "r") username, password = user_detail_file.readline().split(",") username_is_correct = username == name password_is_correct = password == password_input if username_is_correct and password_is_correct: database = open(f"data/{name}_database.txt", "r") data = database.read() print(data) user_detail_file.close()
bd226262e6695f70cfcca18edc78bfac66a41913
MarcosFantastico/Python
/Exercicios/ex060for.py
553
3.96875
4
'''print('Fatorial com for!') n = int(input('Digite um número: ')) fatorial = 1 print(f'{n}! = ', end='') for cont in range(n, 0, -1): if cont != 1: print(f'{cont} X ', end='') else: print(cont) fatorial *= cont print(f'O fatorial de {n} é: {fatorial}')''' print('fatorial') n = int(input('Digite um n para calcular o fatorial: ')) fatorial = n for c in range(n, 0, -1): print(c, end='') print(' X ' if c > 1 else ' = ', end='') if c > 1: c -= 1 fatorial *= c print(fatorial)
7951d3f1af5b8b49935f3176873fa6dd4fa14dd8
JZTischler/srange
/srange/srange.py
21,317
3.5
4
#!/usr/bin/env python # # srange.py # # $Id: $ # $URL: $ # # Part of the "pydiffract" package # import sys __version__ = "$Revision: $" __author__ = "Jon Tischler, <tischler@aps.anl.gov>" +\ "Christian M. Schlepuetz, <cschlep@aps.anl.gov>, " +\ "Argonne National Laboratory" __date__ = "$Date: $" __id__ = "$Id: $" class srange: """ String-range class. Updated to work with both python 2 & 3 (previously only 2) by JZT on June 12, 2020. Also a suite of tests are included at the end. with conversion to python3, also had to deal with i/j --> float, not int This class provides functions to convert a string representing integers and ranges of integers to an object which can be iterated over all the values contained in the string. Also, a list of individual values or subranges can be retrieved. EXAMPLE:: >>> sr = srange("1,3,4-5,8-11,12-13,20") >>> for val in sr: print ("%d," % val), 1, 3, 4, 5, 8, 9, 10, 11, 12, 13, 20, NOTE: String ranges can only contain integer numbers and must be strictly monotonically increasing. Multiple identical values are not allowed. addition of __resort_list() now allows for mis-ordered simple ranges, but they still must not overlap. TODO: The issues of the above note should be addressed to make the code more robust and forgiving. There is no reason one should not specify sub- ranges in arbitrary orders. The range is checked to be monotonic, it returns None if no more values last is the last number obtained from this range, use -Inf to get start of range, it returns the next variables and methods that you may be interested in ======================= =================================================================================== variables of interest description ======================= =================================================================================== self.r the input string, after formatting and compacting self.previous_item the previous value produced, initially set very low self.auto_reset if True (default), then previous_item is reset to min at each call to __iter__ ======================= =================================================================================== ======================= =================================================================================== methods of interest action ======================= =================================================================================== next() returns next value, updates previous_item too reset_previous() reset the iterator so it starts with the first value after(prev) returns value that follows prev, without changing the current point in iteration first() returns the first number in the range, for self.r="3,5,9-20", self.first() returns 3 last() returns the last number in the range, for self.r="3,5,9-20", self.last() returns 20 len() returns number of points in the range, for self.r="3,5,9-20", self.len() returns 14 is_in_range(m) returns True if m is in self.r, otherwise False index(ipnt) return the ipntth number from range, first number is ipnt==0, returns None if ipnt negative or too big val2index(m) returns index into r that corresponds to m. e.g. for r='3,5,9-20', m=5 returns 1. sub_range(start,n,...) returns a new range that is a sub range of current one, setLast=False list(self) returns a list where each element is a value in the range, CAUTION this can make a VERY big list ======================= =================================================================================== ===================== ======================= =================================================================== special methods command result using: sr = srange('1-4') ===================== ======================= =================================================================== __getitem__(n) print (sr[2]) 3 __len__() print (len(sr)) 4 __str__() print (str(sr)) 1-4 __repr__() print (repr(sr)) srange('1-4', len=4, previous=0, auto_reset=True) ===================== ======================= =================================================================== """ def __init__(self, r='', auto_reset=True): """ Initialize the srange instance. """ try: self.intTypes = (int, long) # long is only in python2, not 3 except: self.intTypes = (int) try: self.MAXINT = sys.maxint # sys.maxint only exists in python2 except: self.MAXINT = sys.maxsize # for python3, maxsize is a good choice, = (2^63)-1 # if a numpy array is passed for r, convert r to an integer array try: if isinstance(r[0], numpy.integer): r_int = [] # a new empty array for i in r: r_int.append(int(i))# fill r_int with ints r = [] # need to remake r[], do not want the name r_int for i in r_int: r.append(i) # now reset new r[] to input values (but all ints) except: pass # convert input to a list of tuples, each tuple is one simple dash range, e.g. "1-17:2" try: if isinstance(r, unicode): r = r.encode() # convert any unicode to str except: pass if isinstance(r,str): if r.lower() == 'none': r = '' # 'none' is same as empty string self.l = self.__string_to_tuple_list(r) elif isinstance(r, self.intTypes): r = int(r) self.l = [(r,r,1)] r = str(r) elif hasattr(r, '__iter__'): # this works for list and numpy.array, fails for strings self.l = self.__list_to_srange(r) else: raise TypeError("String list must be a string or (list of) integers.") if not self.__is_monotonic(): self.__resort_list() # try to sort the list to be monotonic if not self.__is_monotonic(): # if still not monotonic, give up raise ValueError("String range is unsortable.") try: self.auto_reset = bool(auto_reset) except: raise TypeError("auto_reset must be boolean") self.reset_previous() # set self.previous_item to number before first number in range self.l = self.__compact(self.l) # compactify the list self.r = self.__tuple_list_to_str(self.l) # make a string representation of list def __iter__(self): """ The class iterator """ if self.auto_reset: self.reset_previous() # reset to start of range, changed July 24-2014 JZT return self def __repr__(self): """ Return string representation for srange. """ try: length = self.len() except: length = None return "srange('%s', len=%r, previous=%r, auto_reset=%r)" % (self.r, length, self.previous_item, self.auto_reset) def __str__(self): """ Return string value for srange. """ return self.r def __getitem__(self, n): """ Return the n-th element in the string range. """ return self.index(n) def __next__(self): # this is required for python3 iterator """ Return the n-th element in the string range. """ return self.next() def next(self): # this is required for python2 iterator """ Return the next value in the string range. Also update self.previous_item. """ if not self.l: raise StopIteration for (lo, hi, stride) in self.l: if self.previous_item < lo: # start of this simple range is big enough self.previous_item = lo return lo elif self.previous_item >= lo and self.previous_item < hi: # within this simple range self.previous_item += stride - ((self.previous_item-lo) % stride) return self.previous_item # self.reset_previous() # removed July 21-2014 JZT, do NOT reset at end of range raise StopIteration def after(self, val): """ Return the value or the element that follows after the given value. EXAMPLE:: >>> sr = srange("3,5,9-20") >>> print (sr.after(5)) 9 """ if not self.l: return None previous_save = self.previous_item # save self.previous_item for later resetting try: self.previous_item = int(val) # temporarily set self.previous_item to val except: raise ValueError("argument to srange.after() must be a number") try: after = self.next() except: after = None self.previous_item = previous_save # reset self.previous_item to original value return after def first(self): """ Return the number of the first item in the range. This method uses but does not change any internal variables, e.g. no self.xxxx EXAMPLE:: >>> sr = srange("3,5,9-20") >>> print (sr.first()) 3 """ if not self.l: raise ValueError("String range is empty.") return (self.l[0])[0] def last(self): """ Return the value of the last item in the range. This method uses but does not change any internal variables, e.g. no self.xxxx EXAMPLE:: >>> sr = srange("3,5,9-20") >>> print (sr.last()) 20 """ if not self.l: raise ValueError("String range is empty.") return (self.l[-1])[1] def len(self): """ Return the number of items in the string range. This method uses but does not change any internal variables, e.g. no self.xxxx EXAMPLE:: >>> sr = srange("3,5,9-20") >>> print (sr.len()) 14 """ if not self.l: return 0 total = 0 for (lo, hi, stride) in self.l: # total += (hi-lo)/stride + 1 # accumulate length of each simple range total += int((hi-lo)/stride) + 1 # accumulate length of each simple range, python3 (/ --> float) return total def __len__(self): """ This is redundant with len(), you can use s.len(), or len(s). This method uses but does not change any internal variables, e.g. no self.xxxx """ return self.len() def is_in_range(self, item): """ Return True if item is in string range self.r, False otherwise. This method uses but does not change any internal variables, e.g. no self.xxxx """ if not self.l: return False if not isinstance(item, self.intTypes): raise TypeError("Element must be integer number") for (lo, hi, stride) in self.l: if lo <= item and item <= hi: return (float(item-lo)/stride).is_integer() return False def index(self, n): """ Return the n-th element from the string range. This method uses but does not change any internal variables, e.g. no self.xxxx """ if not self.l: raise ValueError('String range is empty.') elif not isinstance(n, self.intTypes): raise TypeError('Element must be an integer number, not a '+str(type(n))) elif (n < 0): raise ValueError('Index must be non-negative, not '+str(n)) count = 0 for (lo, hi, stride) in self.l: # hi_count = count + (hi-lo)/stride # count at hi hi_count = count + int((hi-lo)/stride) # count at hi, in python3 i/j --> float if n <= hi_count: return lo + (n-count)*stride count = hi_count + 1 return None def val2index(self, val): """ Return the index into the srange that corresponds to val. This method uses but does not change any internal variables, e.g. no self.xxxx EXAMPLE:: >>> r = '3, 5, 9-20' >>> print (val2index(5)) 1 """ if not self.l: raise ValueError("String range is empty.") elif not isinstance(val, self.intTypes): raise TypeError('Value must be an integer, not a '+str(type(n))) index = 0 for (lo, hi, stride) in self.l: if lo <= val and val <= hi: # val is in this simple range index += float(val-lo)/stride if index.is_integer(): return int(index) else: return None index += int(hi-lo+1) / int(stride) # increment index for next simple range return None def sub_range(self, start, n, set_last=False): """ Return a sub range from the original range as a new range string. The new range starts at with the value start and has up to n elements. If start is not an element in the range, then it begin with first element after start. If set_last is True, then self.previous_item is set to the new end, otherwise no change is made. This method only changes an internal variable "self.previous_item" when set_last is True. EXAMPLE:: >>> sr = srange('3,5,9-20') >>> print (sr.sub_range(start = 5, n = 3)) 5,9-10 """ if not self.l: raise ValueError("String range is empty.") elif not isinstance(start, self.intTypes): raise TypeError("Start value (start) must be an integer.") elif not isinstance(n, self.intTypes): raise TypeError("Number of elements (n) must be an integer.") elif n < 0: raise ValueError("Number of elements must be greater zero.") hi = self.last() # in case hi not set in loop lout = [] for (lo, hi, stride) in self.l: if hi < start: # try next simple range continue start = max(start,lo) lo = start + ((start-lo) % stride) # either start or first number after start hi = min(lo + (n-1)*stride, hi) if lo>hi: # nothing in this simple range continue # n -= (hi-lo)/stride + 1 n -= int((hi-lo)/stride) + 1 # in python3 i/j --> float lout.append((lo,hi,stride)) if n < 1: break if set_last: # set previous_item was requested self.previous_item = hi lout = self.__compact(lout) # compactify the list return self.__tuple_list_to_str(lout) # return the string def list(self): """ Expand a string range into a standard python list. This method uses but does not change any internal variables, e.g. no self.xxxx EXAMPLE:: >>> print (srange("3,5,9-13").list()) [3, 5, 9, 10, 11, 12, 13] CAUTION: The following statement:: >>> list("1-100000",";") will produce a list with 100000 elements! Max list length for a 32 bit system is (2^32 - 1)/2/4 = 536870912 on my computer I get a MemoryError for lengths > 1e8, so limit to 1e7 """ if self.len() > 10000000: # 1e7, a big number raise IndexError("Resulting list too large, > 1e7.") elif not self.l: return [] lout = [] for (lo, hi, stride) in self.l: lout.extend(range(lo,hi+1,stride)) return lout def reset_previous(self): """ Reset previous_item to the lowest possible integer value. """ try: l0 = self.l[0] self.previous_item = int(l0[0]-1) # in python2, the srange may need longs except: self.previous_item = -self.MAXINT # just set to most negative 32bit int def __list_to_srange(self, input_list): """ Convert a python list to a string range, the tuple list. This method neither uses nor changes any internal variables, e.g. no self.xxxx Also this routine does NOT compact the returned list, you must do that. EXAMPLE:: >>> mylist = [3,5,9,10,11,12] >>> sr = srange('') >>> sr.__list_to_srange(mylist) >>> print (sr) '3,5,9-12' """ if not all(isinstance(n, self.intTypes) for n in input_list): raise ValueError("List elements must be integers.") new_tuple_list = [] for item in input_list: new_tuple_list.append((item,item,1)) return new_tuple_list def __string_to_tuple_list(self,r): """ Convert a string range to a list of simple ranges, tuples of the form (lo,hi,stride). r is the string, usually input at __init__(...) This routine does no compacting, just a simple translation Note, all values in the tuple list are integers. This method neither uses nor changes any internal variables, e.g. no self.xxxx """ if not r: return [] if r.find('@') > 0: raise ValueError("Invalid character ('@') in string range.") l = [] singles = r.split(',') # split string into a list of simple ranges for single in singles: s = single.lstrip() # look for a stride lo,mid,hi = s.partition(":") try: val = float(hi) except: val = 1.0 # default stride is 1 stride = int(val) if not val.is_integer() or stride<=0: raise ValueError("stride is not a positive integer in string range.") s = lo # A '-' after the first character indicates a contiguous range # If it is first character, it means a negative number # If no '-' is found, mid and hi will be empty strings i = s[1:].find('-') + 1 if i > 0: s = s[0:i] + '@' + s[i+1:] lo,mid,hi = s.partition('@') lo = lo.strip() if lo.lower().find('-inf') >= 0: lo = -self.MAXINT elif lo.lower().find('inf') >= 0: lo = self.MAXINT try: lo = int(lo) except: raise ValueError("Values in string range must be integers.") if(hi): hi = hi.strip() if hi.lower().find('-inf') >= 0: hi = -self.MAXINT elif hi.lower().find('inf') >= 0: hi = self.MAXINT try: hi = int(hi) hi -= ((hi-lo) % stride) # ensure that hi matches with stride, remove excess except: raise ValueError("Values in string range must be integer.") else: hi = lo stride = 1 l.append((lo, hi, stride)) return l def __resort_list(self): """ Re-order the set of tuples in self.l to be montonic. """ loVals = [] # a list of the lo values for l in self.l: # first produces the sorted indicies loVals.append(l[0]) ii = sorted(range(len(loVals)), key=loVals.__getitem__) lnew = [] for i in ii: # rebuild a sorted list from indicies lnew.append(self.l[i]) self.l = lnew def __is_monotonic(self): """ Return True if the tuple list self.l is monotonic, False otherwise. An empty range is assume to be monotonic. This method does not change any internal variables, e.g. no self.xxxx """ try: last_hi = int((self.l[0])[0]) - 1 except: return True # empty range is assumed monotonic. for (lo, hi, stride) in self.l: if (hi < lo) or (stride < 1) or (last_hi >= lo): return False last_hi = hi return True def __tuple_list_to_str(self,l): """ Convert a list of tuples to a string. This does NO compacting, just change the list l to a string. This method neither uses nor changes any internal variables, e.g. no self.xxxx EXAMPLE:: >>> print (self.__tuple_list_to_str([(0, 0, 1), (2, 3, 1), (4, 8, 2)])) '0,2-3,4-8:2' """ if not l: return '' range_string = '' for (lo, hi, stride) in l: range_string += str(lo) if hi>lo: # a lo-hi range range_string += '-'+str(hi) if stride>1: range_string += ':'+str(stride) range_string += ',' return range_string.rstrip(',') def __compact(self,l): """ Return the most compact way of describing a string range. This method neither uses nor changes any internal variables, e.g. no self.xxxx EXAMPLE:: >>> ## sr = srange('0,2,3,4-8:2') >>> l = self.__compact([(0, 0, 1), (2, 3, 1), (4, 8, 2)]) >>> print (l) [(1, 4, 1), (6, 6, 1)] NOTE: Compacting is always done during initialization. """ if not l: return None # first, see if there are any single value runs of 3 or more that can be combined into a stride # only combine simple ranges when there are 3 numbers in a row with the same stride. lcombine = [] # list or simple ranges to combine count = 0 i = 0 new_stride = -1 for (lo, hi, stride) in l: if not (lo==hi): # reset for next search, start again if count > 2: # done with this run, save info lcombine.append((istart,istart+count-1,new_stride)) new_stride = -1 istart = -1 count = 0 elif count==1: new_stride = lo - last_hi # set the new stride count = 2 elif count>1 and (lo-last_hi)==new_stride: count += 1 # accumulate more in this stride elif count > 2: # done with this run, save info lcombine.append((istart,istart+count-1,new_stride)) new_stride = -1 # reset for next search count = 1 istart = i else: # possibly start of a new stride new_stride = -1 # reset for next search count = 1 istart = i i += 1 last_hi = hi if count > 2: # one more to append lcombine.append((istart,istart+count-1,new_stride)) ltemp = [] # contains a shorter list using info in lcombine i0 = 0 # next one to do for (lc0, lc1, stride) in lcombine: # move ranges from l to ltemp for i in range(lc0-i0): # just copy [i0,lc0-1] ltemp.append(l[i+i0]) lo = (l[lc0])[0] hi = (l[lc1])[1] ltemp.append((lo,hi,stride)) i0 = lc1+1 for i in range(len(l)-i0): # move any remaining simple ranges from l to ltemp ltemp.append(l[i+i0]) # second, see if you can concatenate any simple ranges having the same stride # only combine ranges if one of them has hi>lo, do not combine two single number ranges. lnew = [] (last_lo, last_hi, last_stride) = ltemp[0] last_single = last_lo==last_hi for (lo, hi, stride) in ltemp: single = lo==hi if lo==last_lo: # the first one of ltemp[0], skip this continue elif single and (not last_single) and last_hi+last_stride == lo:# last complex joins current single last_hi = hi elif (not single) and last_single and last_hi+stride ==lo: # last single joins current complex last_hi, last_stride, last_single = (hi, stride, False) # re-set last (last_lo not changed) elif (not single) and (not last_single) and last_hi+stride==lo and stride==last_stride: # join two complex with same stride last_hi = hi else: lnew.append((last_lo,last_hi,last_stride)) # append last last_lo, last_hi, last_stride = (lo, hi, stride) # re-set last to current last_single = last_lo==last_hi lnew.append((last_lo,last_hi,last_stride)) # append the last one return lnew
d1e2229f93bd031cab91e9313c6822b8f0c4abd9
fahmed3/15_comprehension
/comprehension.py
1,220
3.859375
4
letters = 'abcdefghijklmnopqrstuvwxyz' numbers = [str(x) for x in range(0,10)] non_alphanumeric = '.?!&#,;:-_*' def password(p): if len([x for x in p if x in numbers]) == 0: print "Needs a number" if len([x for x in p if x in letters]) == 0: print "Needs a lowercase letter" if len([x for x in p if x in letters.upper()]) == 0: print "Needs an uppercase letter" else: print "Congratulations! You've met the minimum threshold." password("Hi123") def passwordStrength(p): score = 1 #min score num = [x for x in p if x in numbers] lowerLet = [x for x in p if x in letters] upperLet = [x for x in p if x in letters.upper()] nonAlpha = [x for x in p if x in non_alphanumeric] #0-5 points for mix of upper to lowercase letters if len(upperLet) > len(lowerLet): score += 10 * len(lowerLet)/(len(lowerLet) + len(upperLet)) else: score += 10 * len(upperLet)/(len(lowerLet) + len(upperLet)) #2 points for including a number if len(num) >= 1: score += 2 #2 points for including a non-alphanumeric char if len(nonAlpha) >= 1: score += 2 return score print passwordStrength("AbCDEfghiJkLmnoop123.")
b1ec7f5ee1cff1f63e44bf96fc35f4ebba5ef50a
jefferson-tavares-araujo/projetos
/Algoritmos - Python/Exercicios Python/exercicio04.py
455
3.8125
4
tanque_carro = int(input('Entre com a capacidade do tanque do carro = ')) litros = float(input('Entre com a quantidade de litros abastercidos = ')) km_corrido = float(input('Entre com KM percorrido antes do abastecimento = ')) diferenca = tanque_carro - litros kmlitro = km_corrido / litros kmrestante = diferenca * kmlitro kilometragem = print('O veiculo percorrera %.2f km '% kmrestante) print('O veiculo tem autonomia de %.2f km por litro' % kmlitro)
2c222bc7c70d1b095fc254f46e7e14653f906bee
arifinsugawa/CP1404Practicals_ArifinSugawa_jc261529
/Prac10/flask_project.py
627
3.6875
4
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return '<h1> Hello World! :) <h1>' @app.route('/greet') @app.route('/greet/<name>') def greet(name = ""): return "Hello {}".format(name) @app.route('/convert') @app.route('/convert/<degree>') def convert(degree = 0): try: CONST_FahrenheitConvert = 5/9 fahrenheit = (int(degree) - 32) * CONST_FahrenheitConvert return "<h1> {} degree is {:.2f} fahrenheit <h1> ".format(degree, fahrenheit) except ValueError: return "Degree provided is not number" if __name__ == '__main__': app.run()
c50ff1f943fcd7858919b383d7a7c3446969540c
falble/mythinkpython2
/CAP4-Case study_interface design/exercise&solutions/spirals.py
947
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 14 21:10:07 2019 @author: Utente """ """This module contains a code example related to Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ """ import turtle def draw_spiral(t, n, length=3, a=0.1, b=0.0002): """Draws an Archimedian spiral starting at the origin. Args: n: how many line segments to draw length: how long each segment is a: how loose the initial spiral starts out (larger is looser) b: how loosly coiled the spiral is (larger is looser) http://en.wikipedia.org/wiki/Spiral """ theta = 0.0 for i in range(n): t.fd(length) dtheta = 1 / (a + b * theta) t.lt(dtheta) theta += dtheta # create the world and bob bob = turtle.Turtle() draw_spiral(bob, n=1000) turtle.mainloop()
0e985414f2db62c8bb2afe47f5871899626e30cf
ibumarskov/tungsten-pytest
/tungsten_tests/helpers/utils.py
2,840
3.671875
4
import logging import random import re logger = logging.getLogger() def rand_name(name='', prefix='tft'): """Generate a random name that includes a random number :param str name: The name that you want to include :param str prefix: The prefix that you want to include :return: a random name. The format is '<prefix>-<name>-<random number>'. (e.g. 'prefixfoo-namebar-154876201') :rtype: string """ rand_name = str(random.randint(1, 0x7fffffff)) if name: rand_name = name + '-' + rand_name if prefix: rand_name = prefix + '-' + rand_name return rand_name def parser_iperf_output(text, udp=False): """Parse summary line written by an `iperf` run into a Python dict.""" pattern = (r'\[(.{3})\]\s+(?P<interval>.*?sec)\s+' r'(?P<transfer>.*?Bytes|bits)' r'\s+(?P<bandwidth>.*?/sec)') if udp: pattern += r'\s+(?P<jitter>.*?s)\s+(?P<datagrams>\d+/\s*\d+)\s+' \ r'\((?P<datagrams_rate>\d+)%\)' iperf_re = re.compile(pattern) for line in text.splitlines(): match = iperf_re.match(line) if match: iperf = match.groupdict() bval, bunit = iperf['bandwidth'].split() iperf['bandwidth'] = float(bval) iperf['bandwidth_unit'] = bunit tval, tunit = iperf['transfer'].split() iperf['transfer'] = float(tval) iperf['transfer_unit'] = tunit lost, total = iperf['datagrams'].replace(" ", "").split('/') iperf['datagrams_lost'] = int(lost) iperf['datagrams'] = int(total) iperf['datagrams_rate'] = int(iperf['datagrams_rate']) return iperf return {} def check_iperf_res(res, loss_rate=1): """Check `iperf` test results.""" logger.info("Iperf data:\n{}".format(res)) if not res: raise Exception("Traffic wasn't detected") elif res['datagrams_rate'] > loss_rate: raise Exception("The loss of traffic is too much.\n" "Expected: {}% Loss: {}%" "".format(loss_rate, res['datagrams_rate'])) def parser_lb_responses(text, req_num, member_num): res_list = text.splitlines() if len(res_list) != req_num: raise Exception("Amount of requests ({}) isn't equal to output:\n" "{}".format(req_num, res_list)) unique_res = set(res_list) if len(unique_res) != member_num: raise Exception("Amount of unique responses isn't equal to amount of " "pool members ({}):\n" "{}".format(member_num, unique_res)) stat = {} for i in unique_res: stat.update({i: res_list.count(i)}) logger.info("LB response statistics:\n{}".format(stat)) return stat
43324a5a73f5075e49c96aa82439b7da5985ddf9
Mtmh/py.1nivel1
/108ListaPop1.py
336
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 8 14:00:08 2017 @author: tizianomartinhernando """ lista=[10, 20, 30, 40, 50] print(lista) lista.pop(0) lista.pop(1) lista.pop(2) print(lista) ''' Crear una lista por asignación con 5 enteros. Eliminar el primero, el tercero y el último de la lista. '''
f74896a28a3253286a9d12a981fe0447bfb406e5
sr-sourabh/ds-in-python
/week 4/week4.py
4,289
3.75
4
''' 1. We represent scores of batsmen across a sequence of matches in a two level dictionary as follows: {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91} Each match is identified by a string, as is each player. The scores are all integers. The names associated with the matches are not fixed (here they are 'match1','match2','match3'), nor are the names of the players. A player need not have a score recorded in all matches Define a Python function "orangecap(d)" that reads a dictionary d of this form and identifies the player with the highest total score. Your function should return a pair (playername,topscore) where playername is a string, the name of the player with the highest score, and topscore is an integer, the total score of playername. The input will be such that there are never any ties for highest total score. For instance: >>> orangecap({'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}}) ('player3', 100) >>> orangecap({'test1':{'Ashwin':84, 'Kohli':120}, 'test2':{'ashwin':59, 'Pujara':42}}) ('Kohli', 120) Let us consider polynomials in a single variable x with integer coefficients: for instance, 3x^4 - 17x^2 - 3x + 5. Each term of the polynomial can be represented as a pair of integers (coefficient,exponent). The polynomial itself is then a list of such pairs. We have the following constraints to guarantee that each polynomial has a unique representation: -- Terms are sorted in descending order of exponent -- No term has a zero cofficient -- No two terms have the same exponent -- Exponents are always nonnegative For example, the polynomial introduced earlier is represented as [(3,4),(-17,2),(-3,1),(5,0)] The zero polynomial, 0, is represented as the empty list [], since it has no terms with nonzero coefficients. 2. Write Python functions for the following operations: addpoly(p1,p2) multpoly(p1,p2) that add and multiply two polynomials, respectively. You may assume that the inputs to these functions follow the representation given above. Correspondingly, the outputs from these functions should also obey the same constraints. Hint: You are not restricted to writing just the two functions asked for. You can write auxiliary functions to "clean up" polynomials --- e.g., remove zero coefficient terms, combine like terms, sort by exponent etc. Build a library of functions that can be combined to achieve the desired format. You may also want to convert the list representation to a dictionary representation and manipulate the dictionary representation, and then convert back. Some examples: >>> addpoly([(4,3),(3,0)],[(-4,3),(2,1)]) [(2, 1),(3, 0)] Explanation: (4x^3 + 3) + (-4x^3 + 2x) = 2x + 3 >>> addpoly([(2,1)],[(-2,1)]) [] Explanation: 2x + (-2x) = 0 >>> multpoly([(1,1),(-1,0)],[(1,2),(1,1),(1,0)]) [(1, 3),(-1, 0)] Explanation: (x - 1) * (x^2 + x + 1) = x^3 - 1 ''' #{'test1':{'Ashwin':84, 'Kohli':120}, 'test2':{'ashwin':59, 'Pujara':42}} def orangecap(d): a={} for match in d.keys(): for player in d[match]: if player not in a: a[player] = d[match][player] else : a[player] += d[match][player] big = 0 for player in a.keys(): if big < a[player]: big = a[player] capholder = player return (capholder,big) #addpoly([(4,3),(3,0)],[(-4,3),(2,1)]) = [(2, 1),(3, 0)] def addpoly(a,b): c=a+b f={} d=[] for i in range(len(c)): f[c[i][1]] = 0 for i in range(len(c)): total = c[i][0] for j in range(i+1,len(c)): if c[i][1] == c[j][1] : total += c[j][0] if not f[c[i][1]] : d.append(( total,c[i][1] )) f[c[i][1]] = 1 #print (d) for ed in d: for ed in d: if ed[0]==0: d.remove(ed) d.sort(key = lambda l : l[1] , reverse = True) #print (d) return (d) def multpoly(a,b): cc=[] d=[] for ea in a: for eb in b: cc.append((ea[0]*eb[0] , ea[1] + eb[1])) #print (cc) d = addpoly(cc[:1] , cc[1:]) return (d)
6a7625a679de5de88f9fdfc63183c2d8cf72debf
44746/Lists
/starter.py
670
4.21875
4
shopping_list = [] #Setting up an empty list finished = False #Setting up a variable and assigning it to False while not finished: #Creating a while loop to run until finished equals True shopping_item = input("Enter next item (-1 to end list): ") #Adding an item to the list if shopping_item == "-1": #An if statement to check if the user wants to end the program finished = True #re assigning finished to True to end the program else: shopping_list.append(shopping_item) #add new item to the list for index, item in enumerate(shopping_list): print("Item {0} is {1}".format(index +1,item))
9a8690d3206f085bf96f716d7e3a6d87b36f82c4
luanaamorim04/Competitive-Programming
/Resoluções OJ/uri/1739 - Sequência de Threebonacci.py
506
3.65625
4
# Autor: [GAPA] Francisco Arcos Filho<francisco.fepaf@gmail.com> # Nome: Sequência de Threebonacci # Nível: 2 # Categoria: AD-HOC # URL: https://www.urionlinejudge.com.br/judge/pt/problems/view/1739 def f3(x): return (str(x).count("3")>0 or x%3==0); try: while (True): n = int(input()) ant, atual = 0, 1 for i in range(n): ant, atual = atual , ant + atual while (not f3(atual)): ant, atual = atual , ant + atual print(atual) except: pass
b3f5ecf38585d8e75a4cdff714789f7228d69a3a
bibeksh101/MVPPollingApplication
/database.py
2,902
3.90625
4
import sqlite3 connection = sqlite3.connect("data.db") ########################################################################### # CREATE TABLES CREATE_PLAYERS_TABLE = """CREATE TABLE IF NOT EXISTS players ( username TEXT PRIMARY KEY, voted BOOLEAN );""" CREATE_VOTES_TABLE = """CREATE TABLE IF NOT EXISTS votes ( user_username TEXT, mvp_vote INTEGER, FOREIGN KEY(user_username) REFERENCES users(username) );""" def create_tables(): with connection: connection.execute(CREATE_PLAYERS_TABLE) connection.execute(CREATE_VOTES_TABLE) ########################################################################### # KEYBOARD INPUT = 3 # SORT BY VOTE COUNT AND RETURN IT # PARAM: NONE # RETURNS: FETCHES ALL MVP CANDIDATES SHOW_MVP = """SELECT mvp_vote AS "NAMES" , COUNT(*) AS "Final Count" FROM votes GROUP BY mvp_vote HAVING COUNT(*) >= 1 ORDER BY COUNT(*) DESC LIMIT 10;""" def show_mvp(): with connection: cursor = connection.cursor() cursor.execute(SHOW_MVP) return cursor.fetchall() ########################################################################### # KEYBOARD INPUT = 4 # FINDS OUT WHO VOTED FOR A PARTICULAR MVP CANDIDATE # PARAM: none # RETURNS: DATABASE OF SEARCHED MVP CANDIDATE WHO_VOTED_FOR_MVP = "SELECT * FROM votes WHERE mvp_vote LIKE ?" def who_voted_for_mvp(search_player): with connection: cursor = connection.cursor() cursor.execute(WHO_VOTED_FOR_MVP, (f"%{search_player}%",)) return cursor.fetchall() ########################################################################### # KEYBOARD INPUT = 5 # ADDS MVP VOTES FOR PLAYER # PARAM: NONE # RETURNS: none def check_valid_voter(name): with connection: cursor = connection.cursor() cursor.execute('SELECT * FROM players') check_username = cursor.fetchall() for username in check_username: if name.lower() == username[0].lower() and username[1] is None: return True return False UPDATE_VOTE = """UPDATE players set voted = true WHERE username = ?""" INSERT_VOTES = "INSERT INTO votes (user_username, mvp_vote) VALUES (?, ?)" def player_vote(username, mvp_vote): with connection: connection.execute(INSERT_VOTES, (username, mvp_vote)) def add_user(username): with connection: cursor = connection.cursor() if check_valid_voter(username): print("User exists and has not Voted yet!") vote_for_mvp = input("Vote For: ") player_vote(username, vote_for_mvp) cursor.execute(UPDATE_VOTE, (username,)) print(f"---- Thank you for your vote {username}.----") print() else: print("User Does not exists or has already voted!") print() ###########################################################################
2b789f8a9526d0100e865c7ed7b6443201083a35
OO-b/python_basic
/practice18_for2.py
553
3.625
4
# 출석번호가 1, 2, 3, 4 앞에 100을 붙이기로 함 -> 101, 102, 103, 104 studnets = [1,2,3,4,5] print(studnets) studnets = [i+100 for i in studnets] #students에서 값을 불러와서 i에 넣을건데 거기에 i+100씩해서 students 배열로 다시 만들거야. print(studnets) # 학생 이름을 길이로 변환 studnets = ["Iron man", "Thor", "I am groot"] print(studnets) studnets = [len(i) for i in studnets] print(studnets) studnets = ["Iron man", "Thor", "I am groot"] studnets = [i.upper() for i in studnets] print(studnets)
04a2fcce0a1a39799fb7f46d52cf1036fb217bdf
raphaelas/introtocsfinalproject
/tp.py
49,281
3.828125
4
#Pygame barebones taken from: #Sample Python/Pygame Program #Simpson College Computer Science #http://cs.simpson.edu import pygame import sys import random import copy from pygame.locals import * pygame.init() def loadTextList(): #Loads a text file. Copied from Kosbie.net fileHandler = open("save.txt", "rt") # rt stands for read text text = fileHandler.read() # read the entire file into a single string fileHandler.close() # close the file toReturn = "" for element in text: toReturn += element return [toReturn] def saveText(text): #Saves a file fileHandler = open("save.txt", "wt") # wt stands for write text toSave = "" for element in text: toSave += str(element) fileHandler.write(toSave) # write the text fileHandler.close() # close the file def defineColors(): #Defines black, green, khaki, and red colors. return (0,0,0),(0,100,0),(240,230,140),(255,0,0) def displayVariables(): #Initializes lineNumber,descriptionsText, #display, and randList variables. return 0, [], -1, [], " " def initialScores(): #Initializes scores. return 100,10,0,150 def initLengths(): #Initializes score lengths. return 0,2,3,3 def initScrolling(): #Initialize scrolling variables. #imageScroll,backHor, and backVer. return 0,20,20 def initDrag(): #Scroll and drag variables set. return False def initScorePositions(): #Score positions. return [470-6,1], [670-9,1],[870,1],[270-9,1] def initStates(): #Initializes variables that control which screens are displayed: #Splash screen, pause screen, game over screen, name screen. return True,False,False,True def makeCanvas(): # Set the height and width of the screen size = [1200,700] pygame.display.set_caption("EcoCity") return pygame.display.set_mode(size) screen = makeCanvas() def initLargeLists(): #Description display variable printed =\ [[False]*10, [False]*10, [False]*10, #Resevoir [False]*10, [False]*10, [False]*10, #Hospital [False]*10, [False]*10, [False]*10, [False]*10, [False]*10, [False]*10, [False]*10] newImages = [[0]*4, [0]*4, [0]*4, [0]*4] occupied = [[False]*4, [False]*4, [False]*4, [False]*4] oldOccupied = [[False]*4, [False]*4, [False]*4, [False]*4] oldImages = [] usedImages = [] return printed, newImages,occupied,oldOccupied,oldImages,usedImages def dPosition(printed): descriptionPosition = [] x = 927 y0 = 475 step = 20 for i in xrange(len(printed[0])): descriptionPosition += [[x,y0+step*i]] return descriptionPosition #Image uploads. All improvement images are my screenshots from the #computer game Civilization IV. Doing this is a copyright #infringement, even though I am citing the game. Therefore, #this game can not be distributed. farmImage = pygame.image.load("Corn.png").convert() universityImage = pygame.image.load("University3.png").convert() resevoirImage = pygame.image.load("Resevoir.png").convert() airportImage = pygame.image.load("Airport.png").convert() factoryImage = pygame.image.load("Factory.png").convert() hospitalImage = pygame.image.load("Hospital.png").convert() marketImage = pygame.image.load("Market.png").convert() massMediaImage = pygame.image.load("Mass Media.png").convert() militaryImage = pygame.image.load("Military.png").convert() bombImage = pygame.image.load("Bomb.png").convert() fishImage = pygame.image.load("Fish.png").convert() oilImage = pygame.image.load("Oil.png").convert() cowsImage = pygame.image.load("Cows.png").convert() manImage = pygame.image.load("Man.png").convert() upArrowImage = pygame.image.load("Up.png").convert() downArrowImage = pygame.image.load("Down.png").convert() highX = pygame.image.load("highx.png").convert() highY = pygame.image.load("highy.jpg").convert() corner1 = pygame.image.load("Corner1.png").convert() corner2 = pygame.image.load("Corner2.png").convert() corner3 = pygame.image.load("Corner3.jpg").convert() corner4 = pygame.image.load("Corner4.png").convert() miniGrass = pygame.image.load("miniGrass.jpg").convert() imageList = [farmImage,universityImage,resevoirImage,airportImage, factoryImage,hospitalImage,marketImage,massMediaImage,militaryImage, bombImage,fishImage,oilImage,cowsImage] imageNamesPositionsXList = [996,1022,1025,1027,1027,1026,1029,1015, 1027,995,1030,1004,1010] def initSidebarImages(imageList): #Establishes the improvement images that should appear #on the sidebar initially. i1 = imageList[0] i2 = imageList[1] i3 = imageList[2] return i1,i2,i3 def initTextPositions(imageNamesPositionsXList): #Establishes the initial positions improvement captions have. #It is necessary to have different positions for each captions #because I want the captions to be centered and each caption #has different lengths. y0 = 165 step = 130 oneTextPosition = [imageNamesPositionsXList[0],y0] twoTextPosition = [imageNamesPositionsXList[1],y0+step] threeTextPosition = [imageNamesPositionsXList[2],y0+step*2] return oneTextPosition,twoTextPosition,threeTextPosition def restarting(imageList,imageNamesPositionsXList): #Returns initial values for many different variables. This allows #for game restarts. I also use this function upon program load. lineNumber,descriptionsText,display,randList,name = displayVariables() satisfactionScore,populationScore,score,credits = initialScores() scoreLength,populationLength,satisfactionLength,creditsLength = initLengths() imageScroll,backHor,backVer = initScrolling() oneTextPosition,twoTextPosition,threeTextPosition =\ initTextPositions(imageNamesPositionsXList) populationPosition,satisfactionPosition,scorePosition,creditsPosition =\ initScorePositions() drOne = drTwo = drThree = recentlyScrolled = recentlyScrolled2 =\ displayThem = initDrag() printed, newImages,occupied,oldOccupied,oldImages,usedImages =\ initLargeLists() descriptionPosition = dPosition(printed) imageOne,imageTwo,imageThree = initSidebarImages(imageList) splashScreen,pauseScreen,over,nameScreen = initStates() highScores = loadTextList() return (lineNumber,descriptionsText,display,randList,satisfactionScore, populationScore,score,credits,scoreLength,populationLength, satisfactionLength,creditsLength,imageScroll,backHor,backVer,oneTextPosition, twoTextPosition,threeTextPosition,populationPosition, satisfactionPosition,scorePosition,creditsPosition,drOne,drTwo,drThree, recentlyScrolled,recentlyScrolled2,displayThem,descriptionPosition, printed,newImages,occupied,oldOccupied,oldImages,usedImages,imageOne,imageTwo,imageThree, splashScreen,pauseScreen,over,nameScreen,name,highScores) #Restarting() is called here upon game load. (lineNumber,descriptionsText,display,randList,satisfactionScore, populationScore,score,credits,scoreLength,populationLength, satisfactionLength,creditsLength,imageScroll,backHor,backVer, oneTextPosition,twoTextPosition,threeTextPosition,populationPosition, satisfactionPosition,scorePosition,creditsPosition,drOne,drTwo,drThree, recentlyScrolled,recentlyScrolled2,displayThem,descriptionPosition, printed,newImages,occupied,oldOccupied,oldImages,usedImages,imageOne, imageTwo,imageThree,splashScreen,pauseScreen,over,nameScreen,name,highScores) = restarting(imageList,imageNamesPositionsXList) black,green,khaki,red = defineColors() #Defines colors def updatedPositions(imageScroll,populationLength,satisfactionLength, scoreLength,creditsLength,imageNamesPositionsXList): #Updates X Values of improvements captions. oneTextPosition =\ [imageNamesPositionsXList[imageScroll],165] twoTextPosition =\ [imageNamesPositionsXList[imageScroll+1],295] threeTextPosition =\ [imageNamesPositionsXList[imageScroll+2],425] populationPosition = [470-3*populationLength,1] satisfactionPosition = [670-3*satisfactionLength,1] scorePosition = [870-3*scoreLength,1] creditsPosition = [270-3*creditsLength,1] return (oneTextPosition,twoTextPosition,threeTextPosition, populationPosition,satisfactionPosition, scorePosition,creditsPosition) #Map background. Taken from myinkblog.com. backgroundImage = pygame.image.load("Oversized.jpg").convert() def populationGrowth(newImages,universityImage): #Determines the speed of population growth. If a university #is built, population grows by 5 per game frame. Otherwise, #the population grows by 10 per frame. for i in range(len(newImages)): for j in range(len(newImages[0])): if newImages[i][j] == universityImage: return 5 return 10 def imageDrag(drOne,drTwo,drThree,imageScroll,display,event, onSidebar,newImages,credits,score,satisfactionScore,lineNumber, descriptionsList,descriptionsText,descriptionPosition,printed, imageOne,imageTwo,imageThree,usedImages,backHor,backVer): #Important function that is effective when an improvement has #been clicked on the sidebar for dragging. Sets "dr" variables #to indicate that an image is being dragged. This function is #also effective when a user is reading improvement descriptions. # Get the current mouse position. This returns the position # as a list of two numbers. pos = pygame.mouse.get_pos() # Fetch the x and y out of the list, #just like we'd fetch letters out of a string. x=pos[0] y=pos[1] botOne = 166 topOne = 60 incr = 130 left = 935 right = 1165 scoreAdd = 50 betweenOneTwo = y >= botOne and y <= topOne + incr betweenTwoThree = y >= botOne+incr and\ y <= topOne+incr*2 boxOne = y > topOne and y < botOne boxTwo = y > topOne + incr and y < botOne + incr boxThree = y > topOne + incr*2 and y < botOne + incr*2 if x <= left or x >= right or y <= topOne or y >= botOne+incr*2\ or betweenOneTwo == True or betweenTwoThree == True: #Resets description display. miniMap(backHor,backVer,newImages) for lineNumbers in range(len(printed[display])): printed[display][lineNumbers] = False descriptionsText = [] else: conditionals = (drOne == False and drTwo == False\ and drThree == False) if boxOne and conditionals == True and\ imageOne not in usedImages: #Checks if another description being displayed. display = imageScroll lineNumber = 0 if event.type == MOUSEBUTTONDOWN: drOne = True score += scoreAdd #Reward for building improvement usedImages += [imageOne] satisfactionScore,credits =\ changeCreditsAndSatisfaction(imageOne, satisfactionScore,credits) elif boxTwo and conditionals == True and\ imageTwo not in usedImages: display = imageScroll + 1 lineNumber = 0 if event.type == MOUSEBUTTONDOWN: drTwo = True score += scoreAdd #Reward for building improvement usedImages += [imageTwo] satisfactionScore,credits =\ changeCreditsAndSatisfaction(imageTwo, satisfactionScore,credits) elif boxThree and conditionals == True and\ imageThree not in usedImages: display = imageScroll + 2 lineNumber = 0 if event.type == MOUSEBUTTONDOWN: drThree = True score += scoreAdd #Reward for building improvement usedImages += [imageThree] satisfactionScore,credits =\ changeCreditsAndSatisfaction(imageThree, satisfactionScore,credits) for line in descriptionsList[display].splitlines(): if lineNumber < len(printed[display]): if printed[display][lineNumber] == False: descriptionFont =\ pygame.font.Font("Caslon Old Face Heavy BT.ttf",13) descriptionsText += [ descriptionFont.render(line,True,black)] printed[display][lineNumber] = True lineNumber += 1 if len(descriptionsText) > 4: printIt(descriptionsText,descriptionPosition) return (drOne,drTwo,drThree,imageScroll,display,event, onSidebar,newImages,credits,score,satisfactionScore, lineNumber,descriptionsText,x,y,printed,usedImages) def changeCreditsAndSatisfaction(image,satisfactionScore,credits): #Changes a user's score when an improvement is purchased. #Updates credits and satisfactionScore. satAdd = 25 if image == farmImage: satisfactionScore += satAdd credits -= 19 elif image == universityImage: credits -= 15 elif image == resevoirImage: satisfactionScore += satAdd credits -= 16 elif image == airportImage: satisfactionScore += satAdd credits -= 34 elif image == factoryImage: satisfactionScore += satAdd credits -= 21 elif image == hospitalImage: satisfactionScore += satAdd credits -= 19 elif image == marketImage: satisfactionScore += satAdd credits -= 21 elif image == massMediaImage: satisfactionScore += satAdd credits -= 2 elif image == militaryImage: satisfactionScore += satAdd credits -= 40 elif image == bombImage: credits -= 50 elif image == fishImage: satisfactionScore += satAdd credits -= 21 elif image == oilImage: satisfactionScore += satAdd credits -= 59 elif image == cowsImage: satisfactionScore += satAdd credits -= 36 return satisfactionScore,credits def isGameOver(credits,satisfactionScore,over): #Determines whether the user has lost. if credits <= 0 or satisfactionScore <= 0 or over == True: return True return False def printIt(descriptionsText,descriptionPosition): #Prints descriptions provided by imageDrag(). dLength = 9 for lineNum in range(len(descriptionsText)): if lineNum > dLength: lineNum = 0 continue screen.blit( descriptionsText[lineNum],descriptionPosition[lineNum]) def randomSelection(populationScore,satisfactionScore,manImage, randl,backHor,backVer): #Randomly selects a location for an image of a man to be blitted. popThreshold = 1000 if populationScore % popThreshold == 0: randList = [] randX,randY = doRand(populationScore) #Calls doRand to set random person coordinates if #the populationScore eclipses the population threshold. if randX != -1 and randY != -1: decrement = 20 randList = [randX,randY] if len(randList) > 0: if checkRand(randl,randList) == False: randList = [] satisfactionScore -= decrement #Satisfaction decremented. #Adds coordinates of a random person when the person is #first brought into being. return randList,satisfactionScore return [],satisfactionScore def doRand(populationScore): #Random location selection of a man occurs here. topLeftB = 21 rightB = 888 botB = 587 trial = populationScore/1000 for times in range(trial): x = random.randint(topLeftB,rightB) y = random.randint(topLeftB,botB) return x,y return -1,-1 def checkRand(randl,randList): #Ensures that no man overlaps each other. x,y = randList[0],randList[1] width = 31 height = 71 for i in range(0,len(randl),2): if abs(x-randl[i]) < width and abs(y-randl[i+1]) < height\ and (randl[i] != x and randl[i+1] != y): return False return True imageNamesList = ["Vegetable Farm", "University", "Resevoir", "Airport", "Factory", "Hospital", "Market", "Mass Media", "Military", "Bomb Development","Fishing", "Oil Production", "Cattle Farm"] descriptionsList = [""" Industrial Vegetable Farm Provides food to population at high ecological costs. Synthetic fertilizers, herbicides, pesticides, and insecticides deplete the soil. Fertilizer runoff harms ecosystems in nearby bodies of water. +25 Satisfaction -19 Credits""", """ University Provides education. In general, well-off, educated families produce fewer children than do poor families. Therefore, university construction slows the rate of population growth. -15 Credits -50% Population Growth""", """ Resevoir Provides water to population. +25 Satisfaction -16 Credits """, """ Airport Provides passengers high-speed transportation at high fuel costs. Car transportation is more eco-friendly. +25 Satisfaction -34 Credits """, """ Factory Allows for mass production of products and greater product accessability. Supply chains are ecologically damaging because they produce excessive amounts of waste and require trucking. +25 Satisfaction -21 Credits""", """ Hospital Provides health care to population. +25 Satisfaction -19 Credits """, """ Supermarket Allows for easier access to wide range of products. Fosters a culture of immoderate consumption. Favors industrial production practices, rather than small-scale production. +25 Satisfaction -21 Credits""", """ Mass Media Provides population entertainment. Commercial advertisements encourage population to consume immoderately. +25 Satisfaction -2 Credits """, """ Military Maintains national security at high economic costs. Also, Modern warfare is ecologically costly. +25 Satisfaction -40 Credits """, """ Bomb Development Modern warfare has increasingly involved use of bombs. In times of peace and war, bombs are developed and maintained at high economic and ecological costs. -50 Credits """, """ Fishing Provides high-protein food. Industrial fishing practices deplete natural fish sources. +25 Satisfaction -21 Credits """, """ Oil Production Oil is drilled overseas, then transported, refined, and converted into gasoline fuel. Gasoline is used for many purposes: transportation, electricity, heating, and more. +25 Satisfaction -59 Credits""", """ Industrial Cattle Farm Provides food to population at high ecological costs. Animals are overfed with corn and produce methane, a heat trapping gas. Worker conditions are sometimes dangerous and unhealthy. +25 Satisfaction -36 Credits"""] def blitCover(): #Blits green rectangles everywhere except where the map #is displayed in order to allow the map to be displayed #only where the map should be when it is being scrolled. pygame.draw.rect(screen,green,[920,0,1200,700],0) pygame.draw.rect(screen,green,[0,0,1100,20],0) pygame.draw.rect(screen,green,[0,0,20,700],0) pygame.draw.rect(screen,green,[0,680,1100,700],0) def blitBoard(backgroundImage,backgroundPosition,imageOne, imageTwo,imageThree,upArrowImage, downArrowImage,newImages,occupied, highX,highY,corner1,corner2,corner3,corner4,backHor, backVer,toAdd,randList,manImage): #This function blits stationary objects. It also calls #blitAddedImages() which blits moving objects. screen.blit(backgroundImage,backgroundPosition) blitAddedImages(newImages,occupied,highX,highY, corner1,corner2,corner3,corner4,backHor,backVer) randList = addRand(toAdd,randList,manImage,backHor,backVer) blitCover() upArrowPosition = [939,427] downArrowPosition = [1119,428] imageOnePosition=[935,60] imageTwoPosition = [935,190] imageThreePosition = [935,320] sidescreenPosition = [920,20,260,660] mapPosition = [20,20,900,660] screen.blit(imageOne,imageOnePosition) screen.blit(imageTwo,imageTwoPosition) screen.blit(imageThree,imageThreePosition) screen.blit(downArrowImage,upArrowPosition) screen.blit(upArrowImage,downArrowPosition) increment = 130 #Lines pygame.draw.rect(screen,khaki,sidescreenPosition,2) #Sidescreen pygame.draw.rect(screen,khaki,mapPosition,2) #Map for i in xrange(4): pygame.draw.rect(screen,khaki, [830-(200*i),0,90,20],2) #Score pygame.draw.line(screen,khaki,[920,470], [1180,470],2) #Partition for i in xrange(3): pygame.draw.rect(screen,khaki, [935,60+(i*increment),230,106],2) #Buttons #"Improvements" word in sidebar. improvementsFont = pygame.font.Font("Carleton.ttf", 25) improvementsText = improvementsFont.render( "Improvements",True,black) improvementsPosition=[960,30] screen.blit(improvementsText,improvementsPosition) nameFont = pygame.font.Font("Caslon Old Face Heavy BT.ttf",16) nameText = nameFont.render(name,True,black) namePosition = [1045-len(name)*5,0] screen.blit(nameText,namePosition) #Score caption text popTextPosition = [345,2] satisfactionTextPosition = [535,2] scoreTextPosition = [781,2] creditsTextPosition = [148,2] scoreFont = pygame.font.Font("Charrington Bold.ttf",15) popText = scoreFont.render("Population:",True,black) screen.blit(popText,popTextPosition) satisfactionText = scoreFont.render("Satisfaction:",True,black) screen.blit(satisfactionText,satisfactionTextPosition) scoreText = scoreFont.render("Score:", True,black) screen.blit(scoreText,scoreTextPosition) creditsText = scoreFont.render("EcoCredits:",True,black) screen.blit(creditsText,creditsTextPosition) return randList #randList changes when blitAddedImages() called. def blitAddedImages(newImages,occupied,highX,highY, corner1,corner2,corner3,corner4,backHor,backVer): #Blits improvements that the user drags on to the map. #Responsible for adjusting improvement positions if the map #had been scrolled. xSize = 330 ySize = 206 xOffset = 138 road = 50 diff = 41 for i in range(len(newImages)): for j in range(len(newImages[0])): if newImages[i][j] != 0 and type(newImages[i][j]) != list: #Note: backHor, backVer are map scrolling variables. #They stand for backgroundHorizontal #and backgroundVertical. tempImage = newImages[i][j] tempPosition = [j*xSize-xOffset + backHor, i*ySize+road+2+backVer] screen.blit(tempImage,tempPosition) screen.blit(highX, [j*xSize-xOffset + backHor,i*ySize+2 + backVer]) screen.blit(highX, [j*xSize-xOffset+backHor,i*ySize+ySize-road+2+backVer]) screen.blit(highY, [j*xSize-xOffset-road-1+backHor,i*ySize+road+2+backVer]) screen.blit(highY, [j*xSize+road+diff+1+backHor,i*ySize+road+2+backVer]) screen.blit(corner2, [j*xSize-xOffset-road + backHor,i*ySize+1 + backVer]) screen.blit(corner1, [j*xSize+road+diff+backHor,i*ySize+1 + backVer]) screen.blit(corner3, [j*xSize-xOffset-road + backHor, i*ySize+ySize-road+1+backVer]) screen.blit(corner4, [j*xSize+road+diff+1+backHor, i*ySize+ySize-road+1+backVer]) def fillOccupied(occupied,newImages,image): #Fills the "occupied" list, which is a list that ensures #that images added to the map do not overlap each other. cont = True for i in range(len(occupied)): if cont == True: for j in range(len(occupied[0])): if occupied[i][j] == False and cont == True: occupied[i][j] = True newImages[i][j] = image cont = False return occupied,newImages def crossOut(screen,imageList, onSidebar, newImages,khaki): #Crosses out appropriate image on improvements list when #an improvement is purchased. x0 = 935 x1 = 1165 y0 = 60 y1 = 165 increment = 130 for image in imageList: for i in range(len(newImages)): for j in range(len(newImages[0])): if image == newImages[i][j]: if image == onSidebar[0]: pygame.draw.line(screen, khaki,[x0,y0],[x1,y1],2) pygame.draw.line(screen, khaki,[x1,y0],[x0,y1],2) elif image == onSidebar[1]: pygame.draw.line(screen,khaki, [x0,y0+increment],[x1,y1+increment],2) pygame.draw.line(screen,khaki, [x1,y0+increment],[x0,y1+increment],2) elif image == onSidebar[2]: pygame.draw.line(screen,khaki, [x0,y0+increment*2],[x1,y1+increment*2],2) pygame.draw.line(screen,khaki, [x1,y0+increment*2],[x0,y1+increment*2],2) def arrowButtons(event,x,y,imageScroll, imageList,lineNumber,descriptionsText, recentlyScrolled,recentlyScrolled2): #The arrow buttons section. Changes important variables when #an arrow button on the sidebar is clicked. topBound = 470 botBound = 432 upALeft = 938 upARight = 984 downALeft = 1119 downARight = 1164 if event.type == MOUSEBUTTONDOWN and\ y > botBound and y < topBound: #recentlyScrolled and recentlyScrolled2 slow #down sidebar image scrolling. if recentlyScrolled == True: recentlyScrolled = False elif recentlyScrolled2 == True: recentlyScrolled2 = False elif x > upALeft and x <\ upARight and imageScroll < len(imageList) - 3: #Up clicked imageScroll += 1 #Important variable that establishes #which images to display on the sidebar. recentlyScrolled = True recentlyScrolled2 = True lineNumber = 0 descriptionsText = [] elif x > downALeft and x <\ downARight and imageScroll > -len(imageList) + 2: #Down clicked imageScroll -= 1 recentlyScrolled = True recentlyScrolled2 = True lineNumber = 0 descriptionsText = [] return (lineNumber,descriptionsText,imageScroll, recentlyScrolled,recentlyScrolled2) def dragAndPlace(drOne,drTwo,drThree,imageOne,imageTwo, imageThree,x,y,occupied,newImages): #IMAGE IS BEING DRAGGED AND THEN PLACED SECTION. if drOne == True: screen.blit(imageOne,[x,y]) #Blits image at mouse location during dragging. for eventOne in pygame.event.get(): if eventOne.type == MOUSEBUTTONDOWN: drOne = False #No longer dragging. occupied,newImages =\ fillOccupied(occupied,newImages,imageOne) elif drTwo == True: screen.blit(imageTwo,[x,y]) for eventTwo in pygame.event.get(): if eventTwo.type == MOUSEBUTTONDOWN: drTwo = False occupied,newImages =\ fillOccupied(occupied,newImages,imageTwo) elif drThree == True: screen.blit(imageThree,[x,y]) for eventThree in pygame.event.get(): if eventThree.type == MOUSEBUTTONDOWN: drThree = False occupied,newImages =\ fillOccupied(occupied,newImages,imageThree) return drOne,drTwo,drThree,occupied,newImages def addRand(toAdd,randList,manImage,backHor,backVer): if len(toAdd) > 0: #Adds coordinates of new random person to randList. randList += toAdd #This randList is complete with all random people positions. blitRand(randList,manImage,backHor,backVer) return randList def blitRand(randList,manImage,backHor,backVer): for i in xrange(0,len(randList),2): #Blits random people. screen.blit(manImage, [randList[i]+backHor,randList[i+1] + backVer]) def defineImages(imageList, imageScroll): #Returns the image that should be displayed on the sidebar. #This is a function that is repeatedly called in main loop. return (imageList[imageScroll], imageList[imageScroll+1],imageList[imageScroll+2]) def blitScores(): #Blits the score numbers. scoreNumberFont = pygame.font.Font( "Caslon Old Face Heavy BT.ttf",15) thresh = 1000 if populationScore % thresh == 0: col = khaki else: col = black satText =\ scoreNumberFont.render(str(satisfactionScore),True,black) screen.blit(satText,satisfactionPosition) popText = scoreNumberFont.render(str(populationScore),True,col) screen.blit(popText,populationPosition) scoreText = scoreNumberFont.render(str(score),True,black) screen.blit(scoreText,scorePosition) creditsText = scoreNumberFont.render(str(credits),True,black) screen.blit(creditsText,creditsPosition) def sidebarText(imageNamesList,imageScroll,oneTextPosition, twoTextPosition,threeTextPosition): #Blits improvement descriptions. Called repeatedly in main loop. font = pygame.font.Font("Care Bear Family.ttf",18) oneText = font.render(imageNamesList[imageScroll],True,black) screen.blit(oneText,oneTextPosition) twoText = font.render(imageNamesList[imageScroll+1],True,black) screen.blit(twoText,twoTextPosition) threeText = font.render(imageNamesList[imageScroll+2],True,black) screen.blit(threeText,threeTextPosition) def displaySplashScreen(event): #Displays the splash screen. if event.type == pygame.KEYDOWN and event.key == pygame.K_s: #Splash screen disappears and game begins when s pressed. return False elif event.type == pygame.KEYDOWN and event.key == pygame.K_i: displayInstructions() return True else: y = 0 outerPos = [20,20,1160,660] spacing = 40 splashMessage = """ ECO CITY By Raphael Astrow Purchase city improvements to satisfy your city's rapidly growing population. Every improvement costs credits, as will be described during the game. If you run into debt or your population's satisfaction reaches zero, it is game over. Press and hold i to read instructions PRESS S TO START!""" pygame.draw.rect(screen,khaki,outerPos,2) splashFont = pygame.font.Font("Carleton.ttf", 40) for line in splashMessage.splitlines(): splashText = splashFont.render( line,True,black) screen.blit(splashText,[100,70+y*spacing]) y += 1 return True def displayInstructions(): #Displays the game instructions. y = 0 outerPos = [20,20,1160,660] spacing = 50 instructionsMessage =""" INSTRUCTIONS 1. Press p to pause. 2. Press r to restart. 3. Use the arrow keys to scroll the map. 4. Purchase improvements from the "Improvements" sidebar. 5. Do not allow your credits or satisfaction score to reach zero. PRESS S TO START!""" pygame.draw.rect(screen,khaki,outerPos,2) instructionsFont = pygame.font.Font("Carleton.ttf", 40) for line in instructionsMessage.splitlines(): instructionsText = instructionsFont.render( line,True,black) screen.blit(instructionsText,[100,70+y*spacing]) y += 1 def displayPauseScreen(event): #Displays the pause screen. outerPos = [20,20,1160,660] spacing = 40 if event.type == pygame.KEYDOWN and event.key == pygame.K_u: #If u is pressed, game is unpaused. return False elif event.type == pygame.KEYDOWN and event.key == pygame.K_i: displayInstructions() return True else: y = 0 pauseMessage = """ Game paused. Press u to unpause. Press and hold i to view instructions.""" pygame.draw.rect(screen,khaki,outerPos,2) pauseFont = pygame.font.Font("Carleton.ttf", 40) for line in pauseMessage.splitlines(): pauseText = pauseFont.render( line,True,black) screen.blit(pauseText,[100,270+y*spacing]) y += 1 return True def displayGameOver(event,highScores,displayThem): #Displays the game over screen. outerPos = [20,20,1160,660] spacing = 40 if event.type == pygame.KEYDOWN and event.key == pygame.K_r: return False,False elif event.type == pygame.KEYDOWN and event.key == pygame.K_h: #If h is pressed and held, high score list appears. displayThem = displayHighScores(event,highScores) return True,displayThem else: y = 0 pauseMessage = """ GAME OVER. Press r to restart. Hold down h to view high scores.""" pygame.draw.rect(screen,khaki,outerPos,2) pauseFont = pygame.font.Font("Carleton.ttf", 40) for line in pauseMessage.splitlines(): pauseText = pauseFont.render( line,True,black) screen.blit(pauseText,[100,270+y*spacing]) y += 1 return True,displayThem def displayHighScores(event,highScores): #Displays the high score list. outerPos = [20,20,1160,660] spacing = 40 yStart = 270 nums = [] y1 = y2 = 0 high = highScores[0].split() for element in high: sor = element.split("...") nums += [int(sor[1])] nums.sort() scoreMessage = """ HIGH SCORES Press r to restart""" pygame.draw.rect(screen,khaki,outerPos,2) scoreFont = pygame.font.Font("Carleton.ttf", 40) for line in scoreMessage.splitlines(): messageText = scoreFont.render(line,True,black) screen.blit(messageText,[100,100+y1*spacing]) y1 += 1 toUse = [] for scr in range(len(nums)-1,-1,-1): for listing in high: if str(nums[scr]) in listing and listing not in toUse: toUse += [listing] break length = len(toUse) for element in range(len(toUse)): if element < 5: scoreText = scoreFont.render( toUse[element],True,black) numberText = scoreFont.render(str(y2+1),True,black) dotText = scoreFont.render(".",True,black) screen.blit(scoreText,[530,yStart+y2*spacing]) screen.blit(numberText,[480,yStart+y2*spacing]) screen.blit(dotText,[505,yStart+y2*spacing]) y2 += 1 def displayNameScreen(event,name,recentlyPressed,recentlyPressed2, recentlyPressed3): #Displays the name screen and establishes a name entering #system by defining key presses. y = 0 outerPos = [20,20,1160,660] spacing = 40 nameMessage = """ PRESS ENTER TO START! Please enter your first name or nickname. (Limit 8 characters)""" pygame.draw.rect(screen,khaki,outerPos,2) pygame.draw.rect(screen,khaki,[285,300,600,150],2) nameFont = pygame.font.Font("Carleton.ttf",40) for line in nameMessage.splitlines(): messageText = nameFont.render(line,True,black) screen.blit(messageText,[120,70+y*spacing]) y += 1 limit = 7 if event.type == pygame.KEYDOWN: if recentlyPressed == False: #Recently pressed variables are used to prevent #double counting of key presses. recentlyPressed = True elif recentlyPressed2 == False: recentlyPressed2 = True elif recentlyPressed3 == False: recentlyPressed3 = True elif event.key == K_RETURN: name += "" return False,name,False,False,False elif event.key == K_BACKSPACE: name = name[:-1] recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_a and len(name) <= limit: name += "A" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_b and len(name) <= limit: name += "B" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_c and len(name) <= limit: name += "C" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_d and len(name) <= limit: name += "D" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_e and len(name) <= limit: name += "E" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_f and len(name) <= limit: name += "F" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_g and len(name) <= limit: name += "G" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_h and len(name) <= limit: name += "H" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_i and len(name) <= limit: name += "I" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_j and len(name) <= limit: name += "J" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_k and len(name) <= limit: name += "K" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_l and len(name) <= limit: name += "L" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_m and len(name) <= limit: name += "M" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_n and len(name) <= limit: name += "N" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_o and len(name) <= limit: name += "O" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_p and len(name) <= limit: name += "P" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_q and len(name) <= limit: name += "Q" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_r and len(name) <= limit: name += "R" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_s and len(name) <= limit: name += "S" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_t and len(name) <= limit: name += "T" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_u and len(name) <= limit: name += "U" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_v and len(name) <= limit: name += "V" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_w and len(name) <= limit: name += "W" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_x and len(name) <= limit: name += "X" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_y and len(name) <= limit: name += "Y" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False elif event.key == K_z and len(name) <= limit: name += "Z" recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False if name != None: nameText = nameFont.render(name,True,black) screen.blit(nameText,[550-len(name)*11,352]) return (True,name,recentlyPressed, recentlyPressed2,recentlyPressed3) def miniMap(backHor,backVer,newImages): #Displays a minimap that mimics the main map. n = newImages adjust = 9 screen.blit(miniGrass,[960,490]) pygame.draw.rect(screen,khaki,[960,490,170,170],2) pygame.draw.rect(screen,black,[1012-backHor/adjust, 529-backVer/adjust,66,92],1)#This rectangle slides according #to main map scrolling. for i in range(len(newImages)): for j in range(len(newImages[0])): if newImages[i][j] != False: tempPosition = [j*31+981,i*26+520] new =\ pygame.transform.scale(newImages[i][j],(30,30)) screen.blit(new,tempPosition) miniFont =\ pygame.font.Font("Charrington Bold.ttf", 50) def keyPressedInGame(event,backVer,backHor,pauseScreen,over): #Calls function outside main loop that draws init images. if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and backHor <= 450\ and not drOne and not drTwo and not drThree: backHor += 6 elif event.key == pygame.K_RIGHT and backHor >= -447\ and not drOne and not drTwo and not drThree: backHor -= 6 elif event.key == pygame.K_UP and backVer <= 325\ and not drOne and not drTwo and not drThree: backVer += 6 elif event.key == pygame.K_DOWN and backVer >= -331\ and not drOne and not drTwo and not drThree: backVer -= 6 elif event.key == pygame.K_p: pauseScreen = True elif event.key == pygame.K_r: over = True #Map position changed according to user scrolling. backgroundPosition = [backHor-430,backVer-308] return backVer,backHor,pauseScreen,over,backgroundPosition def addScore(over): if over == True: c1 = "" for element in highScores: c1 += str(element) combo = c1 + " " + name + "..." + str(score) saveText(combo) recentlyPressed = recentlyPressed2 =\ recentlyPressed3 = False #Loop until the user clicks the close button. done=False # Used to manage how fast the screen updates clock=pygame.time.Clock() # -------- Main Program Loop ----------- while done==False: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done=True # Flag that we are done so we exit this loop # Set the screen background screen.fill(green) # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT #Control which screen is displayed. if splashScreen == True: splashScreen = displaySplashScreen(event) elif nameScreen == True: (nameScreen,name,recentlyPressed, recentlyPressed2,recentlyPressed3) =\ displayNameScreen(event,name,recentlyPressed, recentlyPressed2,recentlyPressed3) elif pauseScreen == True: pauseScreen = displayPauseScreen(event) elif over == True: highScores = loadTextList() over,displayThem =\ displayGameOver(event,highScores,displayThem) if over == False: #Restarts the game. highScores = loadTextList() (lineNumber,descriptionsText,display,randList, satisfactionScore,populationScore,score,credits, scoreLength,populationLength,satisfactionLength, creditsLength,imageScroll,backHor,backVer, oneTextPosition,twoTextPosition,threeTextPosition, populationPosition,satisfactionPosition, scorePosition,creditsPosition,drOne,drTwo,drThree, recentlyScrolled,recentlyScrolled2,displayThem, descriptionPosition,printed,newImages,occupied, oldOccupied,oldImages,usedImages,imageOne, imageTwo,imageThree,splashScreen,pauseScreen,over, nameScreen,name,highScores) =\ restarting(imageList,imageNamesPositionsXList) else: #Image scrolling control. imageOne,imageTwo,imageThree =\ defineImages(imageList,imageScroll) onSidebar = [imageOne,imageTwo,imageThree] #Scrolling and other in game key presses. backVer,backHor,pauseScreen,over,backgroundPosition =\ keyPressedInGame(event,backVer,backHor,pauseScreen,over) #Random person variables. toAdd,satisfactionScore = randomSelection( populationScore,satisfactionScore,manImage, randList,backHor,backVer) randList = blitBoard(backgroundImage,backgroundPosition, imageOne,imageTwo,imageThree,upArrowImage, downArrowImage,newImages,occupied,highX, highY,corner1,corner2,corner3,corner4,backHor,backVer, toAdd,randList,manImage) #Cross out used images. crossOut(screen,imageList, onSidebar, newImages,khaki) #Score lengths scoreLength = len(str(score))-1 populationLength = len(str(populationScore))-1 satisfactionLength = len(str(satisfactionScore))-1 creditsLength = len(str(credits))-1 #Updates X Values of improvements captions. (oneTextPosition,twoTextPosition,threeTextPosition, populationPosition,satisfactionPosition,scorePosition, creditsPosition) =\ updatedPositions(imageScroll,populationLength, satisfactionLength,scoreLength,creditsLength, imageNamesPositionsXList) #Scores and sidebar text sidebarText(imageNamesList,imageScroll,oneTextPosition, twoTextPosition,threeTextPosition) blitScores() #Population growth populationScore +=\ populationGrowth(newImages,universityImage) over = isGameOver(satisfactionScore,credits,over) addScore(over) #INITIALIZE IMAGE DRAG SECTION (drOne,drTwo,drThree,imageScroll,display,event, onSidebar,newImages,credits,score,satisfactionScore, lineNumber,descriptionsText,x,y,printed,usedImages) =\ imageDrag(drOne,drTwo,drThree,imageScroll,display,event, onSidebar,newImages,credits,score,satisfactionScore, lineNumber,descriptionsList,descriptionsText, descriptionPosition,printed,imageOne,imageTwo, imageThree,usedImages,backHor,backVer) #Arrow button clicking (lineNumber,descriptionsText,imageScroll, recentlyScrolled,recentlyScrolled2) =\ arrowButtons(event,x,y,imageScroll,imageList,lineNumber, descriptionsText,recentlyScrolled,recentlyScrolled2) #IMAGE IS BEING DRAGGED AND THEN PLACED SECTION drOne,drTwo,drThree,occupied,newImages =\ dragAndPlace(drOne,drTwo,drThree,imageOne, imageTwo,imageThree,x,y,occupied,newImages) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT # Limit to 20 frames per second clock.tick(20) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit ()
0b2ec1770322f78e5a1b3b6504675d8fb513a82a
kartsridhar/Problem-Solving
/HackerRank/Problem-Solving/Warmup/timeConversion.py
613
3.890625
4
#!/bin/python3 import os import sys # # Complete the timeConversion function below. # def timeConversion(s): zone = s[-2]+s[-1] hour = s[:2] x = int(hour) time = "" if zone == 'PM': if x < 12: x += 12 time = str(x) + s[2:8] else: time = s[:8] elif zone == 'AM': if x == 12: time = "00" + s[2:8] else: time = s[:8] return time if __name__ == '__main__': f = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = timeConversion(s) f.write(result + '\n') f.close()
771bbebbc74119ff7e08bb36063af7085ce187f5
JakeWorboys/CS50Projects
/pset6/sentimental/cash.py
622
3.953125
4
# Imports get_float from cs50 library. from cs50 import get_float # Prompts user for amount of change owed. change = get_float("Change owed: ") if change < 0.01: change = get_float("Change owed: ") # Sets coin count to 0. count = 0 # Increases change variable by *100 to negate floating point math imprecision. owed = (change * 100) # Loops through change owed with greedy algorithm. while owed >= 25: owed -= 25 count += 1 while owed >= 10: owed -= 10 count += 1 while owed >= 5: owed -= 5 count += 1 while owed > 0: owed -= 1 count += 1 # Prints smallest coin count. print(count)
9f607cef7b3fcbdd9d7e47560beaf4488b9d3ba9
tusharkailash/LeetCode-Problems-Python
/Amazon/reorderData.py
1,800
3.625
4
# You have an array of logs. Each log is a space delimited string of words. # # For each log, the first word in each log is an alphanumeric identifier. Then, either: # # Each word after the identifier will consist only of lowercase letters, or; # Each word after the identifier will consist only of digits. # We will call these two varieties of logs letter-logs and digit-logs. # It is guaranteed that each log has at least one word after its identifier. # Reorder the logs so that all of the letter-logs come before any digit-log. # The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. # The digit-logs should be put in their original order. # Return the final order of the logs. # Example 1: # Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"] # Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"] class Solution(object): def reorderLogFiles(self, logs): letter = [] digits = [] for log in logs: id, rest= log.split(' ',1) if rest[0].isalpha(): letter.append([rest, id]) else: digits.append(log) # print "letter:", letter [['art can', 'let1'], ['own kit dig', 'let2'], ['art zero', 'let3']] # print "digits:", digits ['dig1 8 1 5 1', 'dig2 3 6'] letter.sort() # print "letter:", letter [['art can', 'let1'], ['art zero', 'let3'], ['own kit dig', 'let2']] result = [] for item in letter: result.append(item[1] + ' ' + item[0]) return result + digits logs = ["dig1 8 1 5 1", "let1 art can", "dig2 3 6", "let2 own kit dig", "let3 art zero"] print Solution().reorderLogFiles(logs)
6f4b999c7ac2559ec99647813b7124b7b7555405
eduardocarneiro/python
/cursos_hugo_vasconcelos/python_hv/aula17-comparadores_and_e_or/comparadoresAndEOr_2.py
131
3.53125
4
idade = 16 if idade <=16 or idade >=70: print("Cidadao nao eh obrigado a votar") else: print("Cidadao obrigado a votar")
fb1abe98a12019a9b873de63664f15a43eec51e5
VladPotapov/python
/python_C++/path1/28-for.py
541
3.921875
4
# -*- coding: utf-8 # # Программа к учебному пособию # К.Ю. Поляков. Программирование на языках Python и C++ # Часть 1 (8 класс) # Программа № 28. Цикл по переменной # for i in range(10): print("Привет!") for i in [0,1,2,3,4,5,6,7,8,9]: print("Пока!") N = 2 for power in range(1,11): print(N) N *= 2 summa = 0 for i in range(1,1001): summa += i print(summa) for k in range(10,0,-1): print(k*k) for i in range(0, 101, 5): print(i)
aaba7ebb7c19f1d9c4bc0eb950f542fd30cfcb15
samhuynhle/Python_Algorithms
/climb_stairs/bf_solution.py
251
3.65625
4
class Solution: def climbStairs(self, n: int) -> int: return self.climbing(0, n) def climbing(self, i, n): if i > n: return 0 if i == n: return 1 return self.climbing(i + 1, n) + self.climbing(i + 2, n)
34694b6593c304192207930313c0367eea7f836c
jjena560/Data-Structures
/LinkedList/doublyLINKEDLIST/middle Node.py
938
3.875
4
import math class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return temp = self.head while temp.next is not None: temp = temp.next temp.next = new_node def middle(self): temp = self.head q = self.head i = 0 while temp: temp = temp.next i += 1 for j in range(math.floor(i/2)): q = q.next return q.data def printList(self): temp = self.head while(temp): print(temp.data) temp = temp.next llist =LinkedList() for i in range(7): llist.append(i) print(llist.middle())
47410cf1702884dfa3982339a6bd0abf40102e0e
dan55/challenges
/cake/40_dupes.py
1,425
3.984375
4
''' Problem: Find the duplicate number in a list in constant space, n(log(n)) time and without altering the list. Thoughts: Imagine the array were sorted. By determining how many of the elements are greater than the midpoint, we know in which direction to look next. It turns out we can do the same operation on an unsorted array, and it still works, somehow. Source: https://www.interviewcake.com/question/python/find-duplicate-optimize-for-space ''' def find_repeat(arr): floor = 1 ceiling = len(arr) - 1 while floor < ceiling: midpoint = (ceiling - floor) / 2 lower_range_floor, lower_range_ceiling = floor, midpoint upper_range_floor, upper_range_ceiling = midpoint + 1, ceiling elems_in_lower_range = 0 for elem in arr: if elem >= lower_range_floor and elem <= lower_range_ceiling: elems_in_lower_range += 1 number_of_possible_distinct_ints_in_lower_range = \ lower_range_ceiling - lower_range_floor + 1 if elems_in_lower_range > number_of_possible_distinct_ints_in_lower_range: floor, ceiling = lower_range_floor, lower_range_ceiling else: floor, ceiling = upper_range_floor, upper_range_ceiling return arr[floor] def main(): print find_repeat([4, 1, 4, 2]) == 4 print find_repeat([1, 1, 4, 3]) == 1 if __name__ == '__main__': main()
0bfa90fbc559632469d73fcc972c00340b30dc5f
zdenekhynek/data-science-capstone
/tokenizer/stop_words.py
224
3.75
4
from nltk.corpus import stopwords english_stops = stopwords.words('english') def filter_stop_words(words, stops=english_stops): filtered_words = [word for word in words if word not in stops] return filtered_words
87e39946a9d3d384ddf10c7b0511afe5dfafafba
riojano0/Python_Scripts
/Secret-Code/src/generator/secret_code.py
1,467
3.6875
4
#! /usr/bin/env python import random class SecretCode(object): def __init__(self): self.secret_code = self.generate_secret_code() def generate_secret_code(self): code = [] for id_colors in range(4): code.append(random.randint(0, 7)) return code def get_secret_code(self): return self.secret_code def compare_codes(self, guess_list): ''' Compare the guess colors with the secret code and check if the values are the same ''' self.compare_list_position = zip(self.secret_code, guess_list) self.no_matches_position_list = [] self.output_list = [] self.check_position() self.check_value_exist(guess_list) self.check_defaul_values() def check_position(self): for i, z in self.compare_list_position: if i == z: self.output_list.append(self.color_value("red")) else: self.no_matches_position_list.append((i, z)) def check_value_exist(self, guess_list): for i, z in self.no_matches_position_list: if i in guess_list: self.output_list.append(self.color_value("yellow")) def check_defaul_values(self): while len(self.output_list)<4: self.output_list.append(self.color_value("default")) def color_value(self, value): ''' The red value is asignated if the position and the guess value are the same, if the position is not the same but the guess value yes if asignate yellow ''' return {"red": 3, "yellow": 8, "default": 0}.get(value) def get_hints(self): return self.output_list
da5a3cfd1c0f5de1c839ec48d9e2103a9ff37a22
zche/pythonDemo
/obj/test.py
300
3.59375
4
class Test: ''' this is a test demo classs ''' classSpec="it's as test class" def __init__(self, name, salary): self.name = name self.salary = salary def hello(self): ''' say hello ''' print(self.name) print("say hello")
fdea0b34e14806f5b4946e9b97e65c53785f1f94
raghav1674/important-programs-in-python
/pythoncodes/9.py
270
3.578125
4
input="3,2,6,5,1,4,8,9".split(",") num1=0 num2="" index5=input.index("5") index8=input.index("8") for i in range(0,len(input)): if i<index5 or i>index8: num1+=int(input[i]) for i in range(index5,index8+1): num2+=input[i] print(num1+int(num2))
7206898679bcf6877e1882bea77b85109f3de4b1
mjjin1214/algorithm
/190325_power.py
421
3.6875
4
import sys sys.stdin = open('input1.txt') def power1(a, x): if x == 0: return 1 elif x == 1: return a elif x & 1: return power1(a, x - 1) * a else: temp = power1(a, x // 2) return temp * temp def power2(a, x): global ans while x: if x & 1: ans *= a a = a * a x >>= 1 ans = 1 power2(2, 10) print(power1(2, 10), ans)
866d4a5bf7d1c955ee9fd18467de33ef28435622
clstrni/pythonBrasil
/EstruturaDeDecisao/26.py
231
3.78125
4
liters = float(raw_input('How many liters?\n')) fuel = raw_input('Type of fuel: (A-ethanol, G-gasoline)\n').upper() if (fuel == 'A'): tot = liters * 1.9 elif (fuel == 'G'): tot = liters * 2.5 print "Amount to pay R$%f" % (tot)
9e033155250f4e6d055ba35f7ac5bcc0c92e2796
pondjames007/CodingPractice
/HashTable/438_FindAllAnagramsInString.py
637
3.59375
4
# TIPS: # don't need to use hashtable # sometimes we know the data range: like 26 chars # then we can just use array to store it class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: if not s: return [] ans = [] p_ = [0]*26 s_ = [0]*26 for c in p: p_[ord(c) - ord('a')] += 1 l = len(p) for i in range(len(s)): if i >= l: s_[ord(s[i-l]) - ord('a')] -= 1 s_[ord(s[i]) - ord('a')] += 1 if s_ == p_: ans.append(i+1-l) return ans
e2dd1db8713085342d4526e5283070e02abac650
pyhari/pyraspberry
/fibonacci_naive.py
465
3.71875
4
import time #Fibonacci series without recursion def fib_naive(n): fib_prev=1; fib_prev_before=1; for i in range(1,n+1): if(i==1 or i==2): print(1) else: fib=fib_prev+fib_prev_before fib_prev_before=fib_prev fib_prev=fib print(fib) i=i+1 start = time.time() input_length=1500 fib_naive(input_length) end = time.time() print("Elapsed time",end - start)
c192843964f007023a8f0f75932d5e72f642aca7
benktesh/algorithm_dasgupta
/Six_11_Longest_common_subsequence.py
1,973
3.609375
4
##Author: Benktesh #benktesh1@gmail.com #1/3/2017 import numpy as np ''' DPV 6.11 Given two strings x = x1x2    xn and y = y1y2    ym, we wish to nd the length of their longest common subsequence, that is, the largest k for which there are indices i1 < i2 <    < ik and j1 < j2 <    < jk with xi1xi2    xik = yj1yj2    yjk . Show how to do this in time O(mn). Solution Approach: A subsequence is a sequence that appears in the same relative order, and the sequence may not necessarily be contiguous. For example, OBAMA and OMBAMT are two strings. The LCS in this case is OBAM. Optimal Substructure: Let the input strings be X[0..m-1] and Y[0..n-1] of lengths m and n respectively. Let LCS(X, Y) be a function that returns the LCS. If the last characters of both X, Y are same, then LCS(..) = 1 + LCS(X[0...m-2], Y[0..n-1]) If the last character do not match, then LCS(...) we can either compare the strinng by next X or next Y which ever is bigger. Thus, LCS(...) = MAX ( L(X[0..m-2], Y[0..n-1]), L(X[0..m-1], Y[0..n-2]) ''' def LongestCommonSubsequence(X,Y): m = len(X) n = len(Y) M = np.array([[None for x in range(n+1)] for x in range(m+1)]) for i in range(m+1): for j in range(n+1): if(i == 0 or 0 == j): M[i,j] = 0 elif(X[i-1] == Y[j-1]): M[i,j] = 1 + M[i-1, j-1] else: M[i,j] = max(M[i, j-1], M[i-1, j]) #print "(i, j) = ({},{}) X[i-1], Y[j-1] = {}, {}\n{}".format(i,j, X[i-1], Y[j-1], M) #print M return M[m,n] def main(): x = "OBAMA" y = "BATM" print LongestCommonSubsequence(x,y) if __name__ == '__main__': import sys sys.exit(int(main() or 0)) ''' Referece: http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/ https://www.youtube.com/watch?v=RhpTF26LyEc '''
512c2780389fa2653dd12bc29fad59a754d889c2
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/3 week(math-strings-slice)/3.1(float)/2.py
206
3.9375
4
""" По данному числу n вычислите сумму (1 / 1²)+(1 / 2²)+(1 / 3²)+...+(1 / n²). """ num = float(input()) i = 1 s = 0 while i <= num: s += (1 / i**2) i += 1 print(s)
b2574653a78fa6cc577db5421b69a595e974bd8b
Kali98/file_parser
/test_file_parser.py
2,866
3.578125
4
import unittest from file_parser import Fileparser class TestFileParser(unittest.TestCase) : #Testing providing all parameterss def test_get_argv_all_attr_given(self) : fp = Fileparser() input_param = ['-f', 'tabs', '-r-', '-t', '1'] exp_result = ['tabs', True, '1'] result = fp.get_args(input_param) self.assertEqual(result, exp_result) #Testing providing everything but no -r- def test_get_argv_no_r_given(self) : fp = Fileparser() input_param = ['-f', 'tabs', '-t', '5'] exp_result = ['tabs', False, '5'] result = fp.get_args(input_param) self.assertEqual(result, exp_result) #Testing Providing everything but no -f def test_get_argv_no_f_given(self) : fp = Fileparser() input_param = ['-r-' '-t', '1'] exp_result = ['', True, ''] result = fp.get_args(input_param) self.assertEqual(result, exp_result) #Testing replacing from tabs to 2 spaces def test_from_given_tabs_to_spaces(self): fp = Fileparser() from_atr_val = 'tabs' tab_chars_atr_val = '2' poem_atr_val = 'To\tbe,\tor\tnot\tto\tbe,\tthat\tis\tthe\tquestion:' result = fp.from_given(from_atr_val, tab_chars_atr_val, poem_atr_val) self.assertEqual(result, "To be, or not to be, that is the question:") #Testing replacing 1 or more spaces to tabs def test_from_given_spaces_to_tabs(self): fp = Fileparser() from_atr_val = 'spaces' tab_chars_atr_val = '' poem_atr_val = 'To be, or not to be, that is the question:' result = fp.from_given(from_atr_val, tab_chars_atr_val, poem_atr_val) self.assertEqual(result, "To\tbe,\tor\tnot\tto\tbe,\tthat\tis\tthe\tquestion:") #Testing replacing tabs tp spaces with no -t given def test_from_given_some_tabs_to_spaces_default_tab_chars(self): fp = Fileparser() from_atr_val = 'tabs' tab_chars_atr_val = '' poem_atr_val = 'To be, or\tnot to\tbe, that\tis the\tquestion:' result = fp.from_given(from_atr_val, tab_chars_atr_val, poem_atr_val) self.assertEqual(result, "To be, or not to be, that is the question:") #Testing output with no f given where poem is 'tab seprerated' def test_from_not_given_tab_file(self): fp = Fileparser() poem_atr_val = 'To\tbe,\tor\tnot\tto\tbe,\tthat\tis\tthe\tquestion:' result = fp.from_not_given(poem_atr_val) self.assertEqual(result, [0,9]) #Testing output with no f given where poem is 'space seperated' def test_from_not_given_space_file(self): fp = Fileparser() poem_atr_val = 'To be, or not to be, that is the question:' result = fp.from_not_given(poem_atr_val) self.assertEqual(result, [9,0])
dfb002c9191f5bd4776d4e50373561eb96a027b1
samprasgit/leetcodebook
/python/20_validParentheses.py
683
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/2/28 3:55 PM # @Author : huxiaoman # @File : 20_validParentheses.py # @Package : LeetCode # @E-mail : charlotte77_hu@sina.com class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ pars = [None] #这个字典建立的顺序也很重要 parmap = {')':'(','}':'{',']':'['} for c in s: if c in parmap: if parmap[c] !=pars.pop(): return False else: pars.append(c) return len(pars) == 1 if __name__=='__main__': s = Solution() print s.isValid(")(")