blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d1583c0619f60029e1209a8cd1ff1d0224675e1b
jcafiero/Courses
/CS110/Homework/Homework6.py
914
3.5625
4
#Author: Jennifer Cafiero #I pledge my honor that I have abided by the Stevens Honor System. def replace(x,y,lst): if lst == []: return [] elif lst[0] == x: return [y] + replace(x,y,lst[1:]) else: return [lst[0]] + replace(x,y,lst[1:]) def replaceFirstTwo(x,y,lst): xoccur= lst.count(x) if xoccur <= 2: return replace(x,y,lst) else: first = lst.index(x) second = len(lst[0:first+1]) + lst[first+1:].index(x) return replace(x,y,lst[0:second+1]) + lst[second+1:] return lst def findBlack(guess, code, colors): found = [0] * colors score = ["dummy"] * len(code) if guess == []: return 0 elif guess[0] == code[0]: score[0] = "black" return [score, found+1] + findBlack(guess+1, code, colors) else: return [score, found] + findBlack(guess+1, code, colors)
6b3e412f9c109acaf2f5b457f8d4076e9d06b29b
GhimpuLucianEduard/CodingChallenges
/challenges/leetcode/jump_game.py
2,334
4.0625
4
""" Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example 1: Input: nums = [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: nums = [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. Constraints: 1 <= nums.length <= 3 * 10^4 0 <= nums[i][j] <= 10^5 """ from collections import defaultdict import unittest def can_jump_dp(array): if len(array) == 0: return False visited = defaultdict(bool) visited[0] = True for i in range(1, len(array)): for j in range(0, i): if visited[i]: break if visited[j] and j + array[j] >= i: visited[i] = True return visited[len(array) - 1] def can_jump_greedy(array): if len(array) == 0: return False max_index = 0 for i in range(0, len(array) - 1): if i > max_index: break max_index = max(max_index, i + array[i]) return max_index >= len(array) - 1 class TestJumpGame(unittest.TestCase): def test_jump_dp_game_empty(self): self.assertFalse(can_jump_dp([])) def test_jump_dp_game_single_false(self): self.assertTrue(can_jump_dp([4])) def test_jump_dp_game_single_true(self): self.assertTrue(can_jump_dp([0])) def test_jump_dp_game_single_leetcode1(self): self.assertTrue(can_jump_dp([2, 3, 1, 1, 4])) def test_jump_dp_game_single_leetcode2(self): self.assertFalse(can_jump_dp([3, 2, 1, 0, 4])) def test_jump_greedy_game_empty(self): self.assertFalse(can_jump_greedy([])) def test_jump_greedy_game_single_false(self): self.assertTrue(can_jump_greedy([4])) def test_jump_greedy_game_single_true(self): self.assertTrue(can_jump_greedy([0])) def test_jump_greedy_game_single_leetcode1(self): self.assertTrue(can_jump_greedy([2, 3, 1, 1, 4])) def test_jump_greedy_game_single_leetcode2(self): self.assertFalse(can_jump_greedy([3, 2, 1, 0, 4]))
449d7ccc7c84423d25e3fc2539a9403f85597e6a
nightqiuhua/xiaoxiang_DataAnaylsis
/chapter4/简单线性回归/gradient_descent_tools.py
1,986
3.890625
4
# -*- coding: utf-8 -*- """ 作者: Robin 版本: 1.0 日期: 2018/05 文件名: gradient_descent_tools.py 功能: 梯度下降算法 """ import numpy as np def get_gradient(theta, x, y): """ 根据当前的参数theta计算梯度及损失值 参数: - theta: 当前使用的参数 - x: 输入的特征 - y: 真实标签 返回: - grad: 每个参数对应的梯度(以向量的形式表示) - cost: 损失值 """ m = x.shape[0] y_estimate = x.dot(theta) error = y_estimate - y grad = 1.0 / m * error.dot(x) cost = 1.0 / (2 * m) * np.sum(error ** 2) return grad, cost def gradient_descent(x, y, max_iter=1500, alpha=0.01): """ 梯度下降算法的实现 参数: - x: 输入的特征 - y: 真实标签 - max_iter: 最大迭代次数,默认为1500 - alpha: 学习率,默认为0.01 返回: - theta: 学习得到的最优参数 """ theta = np.random.randn(2) # 收敛阈值 tolerance = 1e-3 # Perform Gradient Descent iterations = 1 is_converged = False while not is_converged: grad, cost = get_gradient(theta, x, y) new_theta = theta - alpha * grad # Stopping Condition if np.sum(abs(new_theta - theta)) < tolerance: is_converged = True print('参数收敛') # Print error every 50 iterations if iterations % 10 == 0: print('第{}次迭代,损失值 {:.4f}'.format(iterations, cost)) iterations += 1 theta = new_theta if iterations > max_iter: is_converged = True print('已至最大迭代次数{}'.format(max_iter)) return theta
762ea028a485335a63808ca286c5e4bf826d9921
jfmacedo91/curso-em-video
/python/ex035.py
405
3.59375
4
print('\033[7;40;33m{:=^51}\033[m'.format(' Exercício 035 ')) s1 = float(input('Medida do 1º segmento: ')) s2 = float(input('Medida do 2º segmento: ')) s3 = float(input('Medida do 3º segmento: ')) if (s1+s2) > s3 and (s1+s3) > s2 and (s2+s3) > s1: print('\033[33mOs segmentos acima formam um triangulo!\033[m') else: print('\033[33mOs segmentos acima não formam um triangulo!\033[m')
d11bccc38baf8621fd0b578bacdd83da01e2ba4f
YosefSchoen/FunctionalProgramming
/Homework2Assignment3/Assignment3.py
252
3.90625
4
def reverseNum1(n): return int("".join(str(n)[::-1])) def reverseNum2(n): n = list(str(n)) n.reverse() n = "".join(n) return n def main(): n = int(input("Enter a Number")) print(reverseNum1(n)) print(reverseNum2(n))
71fd1acc9a846b8e443f8b4d9e85c95a639dc10a
dfeusse/codeWarsPython
/07_july/28_backToBasics.py
654
4.25
4
''' Create a program that will return whether an intered value is a str, int, float, or bool. Return the name of the value. Ex: Input = 23 --> Output = int Ex: Input = 2.3 --> Output = float Ex: Input = "Hello" --> Output = str Ex: Input = True --> Output = bool ''' def basics(inp): if isinstance(inp, str) == True: return 'str' elif isinstance(inp, int) == True: return 'int' elif isinstance(inp, float) == True: return 'float' else isinstance(inp, bool) == True: return 'bool' #Input = 23 --> Output = int Ex: Input = 2.3 --> Output = float print basics("Hello") # --> Output = str Ex: Input = print basics(True) # --> Output = bool
ec724093c7251098ec40b7ef9afc5d57fa2fa60f
simranjmodi/cracking-the-coding-interview-in-python
/chapter-02/exercise-2.4.2.py
838
4.15625
4
""" 2.4 Partition Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x. The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions. Solution 2: Not a "stable" approach """ class Node: def __init__(self,data): self.data = data self.next = None def partition(node,x): head = node tail = node while node is not None: next = node.next if node.data < x: node.next = head head = node else: tail.next = node tail = node node = next tail.next = None return head
dbac024c042c2c0c67f2add621878907eda683f7
rizzak/esp_bb
/blink.py
635
3.609375
4
import time import machine class Blink: """For blinking led""" def __init__(self, pin): self.led = machine.Pin(pin, machine.Pin.OUT) self.led.off() def blink(self, count, interval): """ Помигать светодиодом count: Количество раз interval: Интервал в секундах """ for i in range(count): # Зажигаю светодиод self.led.on() time.sleep(interval) # Гашу светодиод self.led.off() time.sleep(interval)
a3042b76fe5d36f4c37052c11a3632ad7a8f4ecc
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4330/codes/1764_674.py
466
3.6875
4
from numpy import* v=array(eval(input("insira o valor do vetor: "))) #quantidadede elementos do vetor print(size(v)) # ou len(v) #primeiro elemento do vetor print(v[0]) #ultimo elemento do vetor print(v[-1]) #maior elemento do vetor print(max(v)) #menor elemento do vetor print(min(v)) #soma dos elementos do vetor print(sum(v)) #media aritmética dos elementos do vetor, com até duas casas decimais de precisão. print(round(mean(v),2)) # ou ( sum(v) / size(v))
20048c6d618474824ef6caa9afb80f01c3733d02
Sumitha7/Rithanya
/countdigits.py
93
3.59375
4
a = int(input(" ")) Count = 0 while(a > 0): a=a // 10 Count = Count + 1 print(Count)
3eab4897c9e8295391fc94ebaf0c3657c8aa34a9
basanta79/udacity_P1
/Task3.py
3,420
4.15625
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixed line telephones in Bangalore. Fixed line numbers include parentheses, so Bangalore numbers have the form (080)xxxxxxx.) Part A: Find all of the area codes and mobile prefixes called by people in Bangalore. - Fixed lines start with an area code enclosed in brackets. The area codes vary in length but always begin with 0. - Mobile numbers have no parentheses, but have a space in the middle of the number to help readability. The prefix of a mobile number is its first four digits, and they always start with 7, 8 or 9. - Telemarketers' numbers have no parentheses or space, but they start with the area code 140. Print the answer as part of a message: "The numbers called by people in Bangalore have codes:" <list of codes> The list of codes should be print out one per line in lexicographic order with no duplicates. Part B: What percentage of calls from fixed lines in Bangalore are made to fixed lines also in Bangalore? In other words, of all the calls made from a number starting with "(080)", what percentage of these calls were made to a number also starting with "(080)"? Print the answer as a part of a message:: "<percentage> percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore." The percentage should have 2 decimal digits """ def task4(calls): area_mobile_codes = {} area_marketing_codes = {} area_fixed_codes = {} total_calls = 0 total_calls_to_bangalore = 0 for call in calls: total_calls +=1 if '(080)' in call[0]: if call[1].find('(', 0, 1) >= 0: start=call[1].find('(') + 1 end=call[1].find(')') code = call[1][start:end] occurrences = area_mobile_codes.get(code) or 0 area_mobile_codes[code] = occurrences + 1 elif call[1].find('140', 0, 3) >= 0: occurrences = area_marketing_codes.get('140') or 0 area_marketing_codes['140'] = occurrences + 1 else: area_code = call[1].split() occurrences = area_fixed_codes.get(area_code[0]) or 0 area_fixed_codes[area_code[0]] = occurrences + 1 total_calls_to_bangalore = area_mobile_codes['080'] percentage = round((float(total_calls_to_bangalore)/float(total_calls))*100, 2) mobile_codes = printTuple(tuple(area_mobile_codes), True) marketing_codes = printTuple(tuple(area_marketing_codes), False) fixed_codes = printTuple(tuple(area_fixed_codes), False) print("The numbers called by people in Bangalore have codes:" + mobile_codes + marketing_codes + fixed_codes ) print('{0} percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore.').format(percentage) def printTuple(tuple_to_print, with_brackets): string_result = '' for element in tuple_to_print: if with_brackets: string_result = string_result + '\n' + '(' + str(element) + ')' else: string_result = string_result + '\n' + str(element) return string_result task4(calls)
048be9eccd05861a336ed94fac87f1e025dffed5
PhillipLeeHub/python-algorithm-and-data-structure
/leetcode/21_Merge_Two_Sorted_Lists.py
1,259
4.1875
4
''' 21. Merge Two Sorted Lists Easy You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. Example 1: Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4] Example 2: Input: list1 = [], list2 = [] Output: [] Example 3: Input: list1 = [], list2 = [0] Output: [0] Constraints: The number of nodes in both lists is in the range [0, 50]. -100 <= Node.val <= 100 Both list1 and list2 are sorted in non-decreasing order. ''' class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: dummy_node = cur = ListNode() while list1 and list2: if list1.val < list2.val: cur.next = list1 cur = list1 list1 = list1.next else: cur.next = list2 cur = list2 list2 = list2.next if list1 or list2: if list1: cur.next = list1 else: cur.next = list2 return dummy_node.next
9482a4e1afa9ec65b4e426ad622ccb5070f24cc6
Eisthra/Python_ornekleri
/test_uygulaması/test_uyg.py
669
3.65625
4
import time import sys print("MATEMATİK TESTİNE HOŞGELDİNİZ....") time.sleep(2) print("Teste başlamak için bekleyiniz...") time.sleep(2) print("soru:1-)Aşağıdakilerden hangisi asaldır?") time.sleep(2) print("a)4 b)5 c)6 d)8 e)10") time.sleep(2) c=int(input("Cevabınız=......")) print("cevabınız değerlendiriliyor") for i in range(5,0,-1): time.sleep(1) # print(str(i),end=" ") #sıra sıra ekrana kalan zamanı yazar sys.stdout.write(str(i)+' ') # sadece str tipinde verileri ekrana yazar sys.stdout.flush() #print ve ya write içerisinde zamana bağlı veri biriktirilmesi engeller if c==5: print("DOĞRU") else: print("YANLIŞ")
29ea2e8a89c20ad01e3901cb32a0ea88f0f27afe
luizomf/basicalgorithmsanddatastructures
/recursion/recursive_function.py
1,368
4.15625
4
""" Recursive functions You may use for for better performance. Read more about it in: http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html """ from typing import List class Box: """A box that can or cannot have a key""" def __init__(self, name: str, has_key=False) -> None: self.name = name self.has_key = has_key def __repr__(self) -> str: return f'Box(name={self.name}, has_key={self.has_key})' def open_boxes(list_of_boxes: List[Box], index: int = 0) -> Box: """A recursive function Args: list_of_boxes (List[Box]): A list of boxes index (int, optional): Actual index. Defaults to 0. Returns: Box: A box that has_key or a new empty Box """ if index >= len(list_of_boxes): return Box('Empty box') box = list_of_boxes[index] print(f'Checking box of index {index} -> {box}') if list_of_boxes[index].has_key: print(f'Returning index box index {index} -> {box}') return box else: index += 1 return open_boxes(list_of_boxes, index) if __name__ == "__main__": boxes: List[Box] = [ Box(name='Product Box'), Box(name='Clothing box'), Box(name='Items box', has_key=True), Box(name='Books Box'), Box(name='Paper box'), Box(name='Tool box') ] print(open_boxes(boxes))
06b50d15fdfe6dc87eef78919ca9b8aeece3c8fd
IronE-G-G/algorithm
/leetcode/前100题/29divideTwoIntegers.py
873
3.96875
4
""" 29 两数相除(中等) 给定两个整数,被除数 dividend 和除数 divisor。将两数相除, 要求不使用乘法、除法和 mod 运算符。 思路:找出尽可能大的n: 被除数/2^n>=除数 """ class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if divisor == 0: return None MINVALUE = -2 ** 31 if dividend == MINVALUE and divisor == -1: return -(MINVALUE + 1) negative = dividend ^ divisor < 0 total = 0 dividend = abs(dividend) divisor = abs(divisor) for i in range(31, -1, -1): if dividend >> i >= divisor: total += 1 << i dividend -= divisor << i return -total if negative else total
dd993fc87278fbef59ee0d3911f46028d452763d
SamoryJ/Final-Project17
/finalproject.py
8,836
4.09375
4
import sys import time #This creates the sword and torch as variables seen later on in the game. sword = False torch = False #This creates a varaible for the magical scroll and diamond sword in the game magical_scroll = False diamond_sword = False #Class for the protagonist for the story, which contains health points and gold currency class Protagonist(object): def __init__(self, name, health,): self.name= name self.health = health self.gold= 0 class finalboss(object): def __init__(self, health,): self.health = 150 #Title Screen print(f'Dungeon Quest ver. 2.36 \n Type any key to start: ') start = input() player = Protagonist(input('Enter name here: '), 100) print(player.name) #Describes the game for player print(f'Welcome {player.name}; this game takes place in a mytholigical dungeon during the medival times. \n The dungeon contains numerous monsters and traps, so your survival will rely on the choices you make. ') #While loop that creates the option to enter the dungeon or to not. #If the second option is chosen the player will automatically win. #Else statment just incase player chooses differnt option than chosen. while True: Enter_choice =input("You arrive at the entrance of a menacing dungeon. You have a choice to either enter or go back to your mother. ").lower() if Enter_choice in ["enter", "enter the dungeon",]: print("You make the idiotic choice of entering a dangerous dungeon with no supplies. Good Luck") break elif Enter_choice=="go back to my mother": print("Smart Choice. Game Over. You Win") time.sleep(10) sys.exit() else: print("That was not an option given, choose either Enter or go back home to my mother") #While loop that creates the option to fight or run #The protagonist class is used to to show damage given by enemies. while True: Fight_choice=input("After exploring the dungeon for while. You run into a skeleton monster. Fight it or Run away. ").lower() if Fight_choice in ['fight it', 'fight', 'fight skeleton', 'fight skeleton monster']: player.health = player.health - 20 print('You somehow beat the skeleton monster and gained a sword and torch from it. You however suffer some damage.') print(f'Your health has decreased by 20 points. It is now {player.health} points.') sword = True torch = True if sword == True and torch == True: break elif Fight_choice in ['run', 'run away']: print("You successfully escape, but miss out on the oppurtunity to loot the skelton of its sword and torch. \n Now you are more vunerable to stronger monsters.") break else: print("That was not an option given, choose either fight or run away") #While loop that creates the option to enter or ignore the room #If you obtained the sword and torch from the last choice. You will be able to enter the room without taking damage. And obtain direction on which path to take. #If you did not obtain the torch and sword and enter you will die. #If you chose to ignore the room you would you would have to guess on the next option while True: Room_choice=input("You explore deeper into the the dungeon and you find a dark room. Enter the room or ingore the room? ") if Room_choice in ["enter","enter room", "enter the room"]: print("You enter the room and since you have a sword and torch you catch the monsters off guard and kill them without taking damage. \n These monsters drop a map to the treasure of dungeon. The treasure map shows that the main treasure of the dungeon is on the right") break elif torch != True and sword != True: player.health = player.health - 80 print("You enter the dark and mysterious room without any weapon or torch. The goblins in the room use the darkness to ambush you. \n You suffer a devasting amount of damage.") print(f'Your health has decreased by 80 points. It is now {player.health} points.') print("Game Over. You Lose.") time.sleep(10) sys.exit() elif Room_choice in ["ignore", "ignore the room", "ignore room"]: print("You choose to ignore the room... wuss.") else: print("That was not an option given, choose either Enter or ignore") #While loop that creates the option to go right or left. #Going right will continue the game and left will result in death while True: Path_choice=input(" You find yourself in the middle of two paths of the dungeon do you go right or left? ") if Path_choice in ["go right","right", "go to the right"]: print("The path to the right leads you to a mound of treasure but is guarded by the dungeon's mini boss,a giant cyclops. \n The entrance to the room shuts behind you, so the only way to survive is to kill the cylops.") break elif Path_choice in ["go left","left", "go to the left"]: print("Turns out that was a trap which you fall into and get impaled by multiple spikes.\n Game Over") time.sleep(10) sys.exit() else: print("That was not an option given choose either left or right") #While loop that creates the option to fight or wait. #Fighting will result in death and waiting will continue the story and give the player gold coins while True: FightClarence_choice=input("Attack the cyclops first or wait for the cyclops to make a move ") if FightClarence_choice in ["attack","attack cyclops", "attack the cyclops"]: print("You chose to fight a giant cyclops head on... ok. Well to keep it short the cyclops crushes your skull and you die. \n Game Over") time.sleep(10) sys.exit() break elif FightClarence_choice in ["wait", "wait for the cyclops to make a move", "wait for cyclops"]: print("To your suprise the cyclops actually a pretty chill dude named Clarence.\n Clarence lets you take some of the treasure and lets you go deeper into the dungeon.") player.gold = +50 print(f'You have recived {player.gold} gold coins!.') break else: print("That was not an option given choose either fight or wait") #While loop that creates the option to choose the item of choice #Buying sword will eventually result in death because it is cursed #Buying scroll may result in victory while True: Shop_choice=input("Beyond the lair of the cyclops is a shop ran by a ghost. The shop is selling magic scroll and a diamond sword for 50 coins. \n Buy the sword or scroll " ) if Shop_choice in ["magic scroll", "buy scroll", "buy magic scroll", "scroll"]: player.gold = player.gold -50 print(f'You now have {player.gold} gold coins.') print("You purchased the mystical scroll with no idea of it's abilities, but it looks useful.") magical_scroll = True break elif Shop_choice in ["diamond sword","buy diamond sword", "sword"]: player.gold =player.gold -50 print(f'You now have {player.gold} gold coins.') print("You purchased the dangerous looking sword") diamond_sword=True break else: print("That was not an option given choose either sword or scroll") #Player not given choice. Story continues automatically Finalroom_choice=input("Now that you have bought your item of choice you are now ready to fight the dungeon boss. Are you ready? Yes or no") print("It really doesnt matter if you're ready. You have no choice") #While loop that creates the options based on the weapon chosen #Players will die either way if they have the sword #Players can only win if they pick fireball spell. while True: if diamond_sword == True: print("You are face to face with the boss of the dungeon, an orge who kind of resembles shrek") attack_choice= input("Attack with your sword or defend?" ) if attack_choice in ["attack", "attack with sword", "attack orge", "defend", "defend with sword"]: print("You died... I forgot to mention that sword was cursed. \n Game Over.") break elif magical_scroll== True: print("You are face to face with the boss of the dungeon, an orge who kind of resembles shrek.") spell_choice= input("The magical scroll is now glowing and gives you the option to use a fire ball spell or lightining spell. ") if spell_choice in ["lightining", "lightining spell"]: print("The lighting spell worked and struck the area you casted it in, causing you to die by lightining strike. \n Game Over.") break elif spell_choice in ["fire spell", "fire ball spell", "fire ball", "fire"]: print('The fire ball spell incinerated the giant orgre. You survied the dungeon and beat the game... congrats I guess. \n You Win!') break
e7d885d47e84176327af29fa4bc8bbc602c3feb0
nadiavdleer/prograil
/code/classes/timetable.py
966
3.515625
4
class Timetable: def __init__(self, trajectories): """ this class is used to calculate the quality of our solution """ self.trajectories = trajectories self.score = 0 self.traveled_connections = [] def quality(self, connections): """ execute target function and return K as the quality of generated trajectories """ used_connections = [] T = 0 Min = 0 for trajectory in self.trajectories: T += 1 Min += trajectory.total_time for connection in trajectory.connections: used_connections.append(connection) p = 0 total_connections = 0 for connection in connections: total_connections += 1 if connection in used_connections: p += 1 p = p / total_connections K = p*10000 - (T*100 + Min) return K
c00e8a3a28d8bfb76ca9f269088f12c87dc378ed
ferhatsirin/Algorithm-Design-and-Analysis
/hw4/161044080/part1.py
1,463
3.890625
4
from collections import defaultdict def optimalPath (hotelList) : hotelList.insert(0,0) optPenalty =[0] optPath =defaultdict(list) optPath[0] =[] for i in range(1,len(hotelList)) : min = optPenalty[0]+(200-(hotelList[i]-hotelList[0]))**2 index =0 for j in range(1,i) : value = optPenalty[j]+(200-(hotelList[i]-hotelList[j]))**2 if value < min : min = value index =j optPenalty.append(min) optPath[i] =optPath[index].copy() optPath[i].append(i) result =[] result.append(optPath[len(hotelList)-1]) result.append(optPenalty[len(hotelList)-1]) return result def takeList() : print("How many hotel do you want to enter : ",end="") size =int(input()) list =[] for i in range(0,size) : print("Enter %d. hotel distance from start point :" %(i+1) ,end="") list.append(int(input())) return list if __name__ == "__main__" : hotelList =[190,220,410,580,640,770,950,1100,1350] print("Default hotel distance list : ",hotelList) print("Will you use the default list (yes) or enter a new list (no) : ", end="") str =input() if str[0].lower() =="n" : hotelList =takeList() print("Hotel distance List : ",hotelList) result =optimalPath(hotelList) print("Optimal path for this list :", result[0]) print("Total penalty for this path is : ",result[1])
dbb8c80e425257d7ab57f5fec2cc404b136e525b
RCNOverwatcher/Python-Challenges
/Sources/Challenges/018.py
131
3.921875
4
num = int(input("Enter a number")) if num < 10: print("Too low") elif num > 20: print("Too High") else: print("YAY")
3c66a6bc74275b781230ce1e911ec00b9728386e
Mykola-L/PythonBaseITEA
/Lesson4/3_8.py
2,293
3.703125
4
from collections import Counter import random #array = ["Bob", "Alex", "Bob", "John"] #array = [1, 9, 1, 2, 2, 3, 2, 2, 2, 4, 4, 4, 6, 5] #array = [1, 9, 1, 2, 2, 3, 2, 2, 4, 4, 4, 6, 5, 5, 5, 5, 4] array = [] # створюю список # Цикл while викликає функцію багато разів i = 0 n = 10 while i < n: # розмір списку array.append((random.randint(1, n))) # додаємо випадкові числа (від 1 до 1000) в список i += 1 # i = i + 1 print(array) c = Counter(array) # словник в кортежі, рахує кількість елементів в словнику print(f'Виводимо кількість елементів які повторюються {c}') start_dict = dict(c) # переводимо кортеж в словник # start_dict = Counter(array) # c # Counter({'Bob': 2, 'Alex': 1, 'John': 1}) # # c['Bob'] # 2 # # c['Unknown'] # 0 print(f'Переводимо кортеж в словник, виводимо словник {start_dict}') #a = max(c) max_value = max(start_dict.values()) # шукаємо максимальне значення в словнику final_dict = {k: v for k, v in start_dict.items() if v == max_value} #c = final_dict.values() # елемент фінального словника d = list(final_dict.keys()) # елемент фінального словника print(f'Максимальне значення в словнику {max_value}') print(f'Словник з максимальними значеннями {final_dict}') #my_dict = {'key': 'value'} my_dict_length = len(final_dict) # Довжина словника з максимальними значеннями print(f'Довжина словника з максимальними значеннями {my_dict_length}') if my_dict_length > 1: a = max(final_dict.keys()) # Максимальне число ключ в словника з максимальними значеннями print(f'Елемент який повторюється найчастіше, і одночасно найбільший {a}') else: print(f'Елемент який повторюється найчастіше, і одночасно найбільший {d}')
607457b18139453d0714395a52145e7c7b0457a8
rrosatti/python
/machine learning/sentiment_neural_net.py
3,300
3.78125
4
''' input > weight > hidden layer 1 (activation function) > weights > hidden layer 2 (activation function) > weights > output layer compare output to intended output > cost function (cross entropy) optimization function (optimizer) > minimize cost (AdamOptmizer ... SGD, AdaGrad) backpropagation feed forward + backprop = epoch ''' import tensorflow as tf from create_sentiment_feature_sets import create_feature_sets_and_labels import numpy as np train_x, train_y, test_x, test_y = create_feature_sets_and_labels('pos.txt', 'neg.txt', test_size=0.1) n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 n_classes = 2 batch_size = 100 # define placeholders and variables # height x width x = tf.placeholder('float', [None, len(train_x[0])]) y = tf.placeholder('float') def neural_network_model(data): # it will create a tensor ("array") of data using random numbers # ... (input data * weights) + biases # Advantage of using a biases: it will be useful in cases where the input is 0. hidden_1_layer = {'weights': tf.Variable(tf.random_normal([len(train_x[0]), n_nodes_hl1])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))} hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))} hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))} output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])), 'biases':tf.Variable(tf.random_normal([n_classes]))} # (input data * weights) + biases l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases']) # activation function l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases']) l3 = tf.nn.relu(l3) output = tf.matmul(l3, output_layer['weights']) + output_layer['biases'] return output def train_neural_network(x): # 'One-Hot' format prediction = neural_network_model(x) # it will calculate the difference between the prediction we got to the no label that we have cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(prediction,y)) # learning_rate = 0.001 (default) optmizer = tf.train.AdamOptimizer().minimize(cost) # cycles feed forward + backprop hm_epochs = 10 with tf.Session() as sess: sess.run(tf.initialize_all_variables()) # training the network for epoch in range(hm_epochs): epoch_loss = 0 # here we change the code in order to use it for our sentiment data set i = 0 while i < len(train_x): start = i end = i + batch_size batch_x = np.array(train_x[start:end]) batch_y = np.array(train_y[start:end]) # optimize the cost passing the xs and ys _, c = sess.run([optmizer, cost], feed_dict={x: batch_x, y: batch_y}) epoch_loss += c i += batch_size print('Epoch', epoch+1, 'completed out of', hm_epochs, 'loss:', epoch_loss) correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) print('Accuracy:', accuracy.eval({x: test_x, y: test_y})) train_neural_network(x)
60b1548ca27bdb9be62743c75f1409683a9e5e19
vishwanath79/PythonMisc
/Py201/29Lock.py
534
3.53125
4
from multiprocessing import Process, Lock def printer(item,lock): """ Prints out the item that was passed in """ lock.acquire() print('process') try: print(item) finally: lock.release() if __name__ == '__main__': lock = Lock() items = ['tango', 'foxtrot', 10] # Loop over list and create a process for each item. Next process in line will wait for the lock to release before proceeding for item in items: p = Process(target=printer, args=(item,lock)) p.start()
0cec38abb00f705296f52446ccdfc66952b24d04
balta2ar/scratchpad
/myleetcode/024_swap_nodes_in_pairs/24.swap-nodes-in-pairs.py
2,963
3.8125
4
# # @lc app=leetcode id=24 lang=python3 # # [24] Swap Nodes in Pairs # # https://leetcode.com/problems/swap-nodes-in-pairs/description/ # # algorithms # Medium (42.63%) # Total Accepted: 288.8K # Total Submissions: 663.9K # Testcase Example: '[1,2,3,4]' # # Given a linked list, swap every two adjacent nodes and return its head. # # You may not modify the values in the list's nodes, only nodes itself may be # changed. # # # # Example: # # # Given 1->2->3->4, you should return the list as 2->1->4->3. # # # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class ListNode: def __init__(self, x): self.val = x self.next = None def to_list(python_list): if not python_list: return None tail = head = None for val in python_list: if head is None: tail = head = ListNode(val) else: tail.next = ListNode(val) tail = tail.next return head def from_list(list_node): if list_node is None: return [] python_list = [] while list_node: python_list.append(list_node.val) list_node = list_node.next return python_list class Solution: def swapPairs(self, head: ListNode) -> ListNode: return self.reverseKGroup(head, 2) def reverseKGroup(self, head: ListNode, k: int) -> ListNode: def insert(list_, node): if list_ is None: return node node.next = list_ return node def rev_only_k(head, k): if head is None: # is that so? return True, None, None, None nh, nt = None, head for i in range(k): # early exit, there is no 'next' if head is None: return False, nh, nt, None next = head.next nh = insert(nh, head) head = next return True, nh, nt, head if head is None: return None ok, nh, nt, next = rev_only_k(head, k) if not ok: # we've reached the end of the list # revert the action and return # make sure the tail is a dead end nt.next = None _ok, nh, nt, _next = rev_only_k(nh, k) # make sure the tail is a dead end nt.next = None return nh nh2 = self.reverseKGroup(next, k) nt.next = nh2 return nh def assert_eq(actual, expected): if actual != expected: raise AssertionError('expected: %s, actual: %s' % (expected, actual)) def test(input_, output): list_ = to_list(input_) assert_eq(from_list(Solution().swapPairs(list_)), output) if __name__ == '__main__': test([1, 2, 3, 4, 5], [2, 1, 4, 3, 5]) test([1, 2, 3, 4], [2, 1, 4, 3]) test([1], [1]) test([1, 2], [2, 1])
622901959296d8289dc729ba079d8c0db2ac43eb
369-einer/trabajo__progra
/diccionarios.py
27,083
3.5
4
print("###############################################################CREACION...1-10 ") #creacion d=dict() d1=dict() d2={} d3={} d4=dict(y=80) d5={1:"terricola",2:"mundo",3:"perdido"} d6={"c":"plan a","a":"original","w":"salir de inmediato"} d7=dict({"hola":"peruano"}) d8=dict({1:"preguntar"}) p=["estrella","planeta"] q=[1,2,3,6] print(p,q) d9=dict(zip(p,q)) print(d,d1,d2,d3,d4,d5,d6,d7,d8,d9) print("###############################################################PERTENENCIA...2 ") #pertenencia print("#####################2.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} diccionario1={1:"pago",2:"salir",3:"lanzar",123:"parada"} print(diccionario,diccionario1) print("#####################2.2") saludo={2:"buenos dias",1:"buenos dias"} saludo={2:"buenos dias",1:"buenos dias"} print(saludo,saludo) print("#####################2.3") vuelo={4:"trujillo",58:"lima"} nombre={4:"luis",58:"carlos"} print(vuelo,nombre) print("#####################2.4") nota={"erica":00,"pedro":12,"carlos":14} cursos={"mate":4,"algebra":4,"analisis":3} print(nota,cursos) print("#####################2.5") cuentas={"marco":25,"alonso":869,"alfredo":570} lugar={1:"cutervo",2:"chota"} print(cuentas,lugar) print("#####################2.6") ms={12:"hola",25:"venir ya"} hora={1:"almorzar",12:"dormir"} print(ms,hora) print("#####################2.7") errores={123:"lista1",2:"lista13"} calificacion={15:"andres",13:"tocas"} print(errores,calificacion) print("#####################2.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} edad={20:"jose",23:"jorge",18:"pedro"} print(canciones,edad) print("#####################2.9") alumnos={145:"eduardo",589:"marcos"} profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(alumnos,profesor) print("#####################2.10") candidatos={8:"toledo",17:"maria",61:"maria"} conocidos=dict(einer=0) print(candidatos,conocidos) print("###############################################################COMPARACION...3 ") #COMPARACION print("#####################3.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} diccionario1={1:"pago",2:"salir",3:"lanzar",123:"parada"} print(diccionario,diccionario1) print(diccionario==diccionario1) print("#####################3.2") saludo={2:"buenos dias",1:"buenos dias"} saludo={2:"buenos dias",1:"buenos dias"} print(saludo,saludo) print(saludo==saludo) print("#####################3.3") vuelo={4:"trujillo",58:"lima"} nombre={4:"luis",58:"carlos"} print(vuelo,nombre) print(vuelo!=nombre) print("#####################3.4") nota={"erica":00,"pedro":12,"carlos":14} cursos={"mate":4,"algebra":4,"analisis":3} print(nota,cursos) print(nota==cursos) print("#####################3.5") cuentas={"marco":25,"alonso":869,"alfredo":570} lugar={1:"cutervo",2:"chota"} print(cuentas,lugar) print(cuentas!=lugar) print("#####################3.6") ms={12:"hola",25:"venir ya"} hora={1:"almorzar",12:"dormir"} print(ms,hora) print(ms!=hora) print("#####################3.7") errores={123:"lista1",2:"lista13"} calificacion={15:"andres",13:"tocas"} print(errores,calificacion) print(errores==calificacion) print("#####################3.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} edad={20:"jose",23:"jorge",18:"pedro"} print(canciones,edad) print(candidatos==edad) print("#####################3.9") alumnos={145:"eduardo",589:"marcos"} profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(alumnos,profesor) print(alumnos==profesor) print("#####################3.10") candidatos={8:"toledo",17:"maria",61:"maria"} conocidos=dict(einer=0) print(candidatos,conocidos) print(candidatos!=conocidos) print("############################################################### INDEXACION...5 ") #INDEXACION print("#####################5.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} diccionario1={1:"pago",2:"salir",3:"lanzar",123:"parada"} print(diccionario,diccionario1) print(diccionario["mundo"]) print(diccionario1[3]) print("#####################5.2") saludo={2:"buenos dias",1:"buenos dias"} saludo={2:"buenos dias",1:"buenos dias"} print(saludo,saludo) print(saludo[1]) print("#####################5.3") vuelo={4:"trujillo",58:"lima"} nombre={4:"luis",58:"carlos"} print(vuelo,nombre) print(vuelo[4]) print(nombre[58]) print("#####################5.4") nota={"erica":00,"pedro":12,"carlos":14} cursos={"mate":4,"algebra":4,"analisis":3} print(nota,cursos) print(nota["erica"]) print(cursos["mate"]) print("#####################5.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) print(cuentas["marco"]) print("#####################5.6") ms={12:"hola",25:"venir ya"} hora={1:"almorzar",12:"dormir"} print(ms,hora) print(ms[12]) print(hora[12]) print("#####################5.7") errores={123:"lista1",2:"lista13"} calificacion={15:"andres",13:"tocas"} print(errores,calificacion) print(errores[123]) print(calificacion[15]) print("#####################5.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} edad={20:"jose",23:"jorge",18:"pedro"} print(canciones,edad) print(canciones[389]) print(edad[23]) print("#####################5.9") alumnos={145:"eduardo",589:"marcos"} profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(alumnos,profesor) print(alumnos[589]) print(profesor["ingles"]) print("#####################5.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos,conocidos) print(candidatos[8]) print("############################################################### LONGITUD...7 ") #LONGITUD print("#####################7.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} diccionario1={1:"pago",2:"salir",3:"lanzar",123:"parada"} print(diccionario,diccionario1) print(len(diccionario)) print(len(diccionario1[3])) print("#####################7.2") saludo={2:"buenos dias",1:"buenos dias"} saludo={2:"buenos dias",1:"buenos dias"} print(saludo,saludo) print(len(saludo)) print("#####################7.3") vuelo={4:"trujillo",58:"lima"} nombre={4:"luis",58:"carlos"} print(vuelo,nombre) print(len(vuelo)) print(len(nombre)) print("#####################7.4") nota={"erica":00,"pedro":12,"carlos":14} cursos={"mate":4,"algebra":4,"analisis":3} print(nota,cursos) print(len(nota)) print(len(cursos)) print("#####################7.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) print(len(cuentas)) print("#####################7.6") ms={12:"hola",25:"venir ya"} hora={1:"almorzar",12:"dormir"} print(ms,hora) print(len(ms)) print(len(hora)) print("#####################7.7") errores={123:"lista1",2:"lista13"} calificacion={15:"andres",13:"tocas"} print(errores,calificacion) print(len(errores)) print(len(calificacion)) print("#####################7.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} edad={20:"jose",23:"jorge",18:"pedro"} print(canciones,edad) print(len(canciones)) print(len(edad)) print("#####################7.9") alumnos={145:"eduardo",589:"marcos"} profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(alumnos,profesor) print(len(alumnos)) print(len(profesor)) print("#####################7.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos,conocidos) print(len(candidatos)) print("############################################################### LONGITUD...7 ") #LONGITUD print("#####################7.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} diccionario1={1:"pago",2:"salir",3:"lanzar",123:"parada"} print(diccionario,diccionario1) print(len(diccionario)) print(len(diccionario1[3])) print("#####################7.2") saludo={2:"buenos dias",1:"buenos dias"} saludo={2:"buenos dias",1:"buenos dias"} print(saludo,saludo) print(len(saludo)) print("#####################7.3") vuelo={4:"trujillo",58:"lima"} nombre={4:"luis",58:"carlos"} print(vuelo,nombre) print(len(vuelo)) print(len(nombre)) print("#####################7.4") nota={"erica":00,"pedro":12,"carlos":14} cursos={"mate":4,"algebra":4,"analisis":3} print(nota,cursos) print(len(nota)) print(len(cursos)) print("#####################7.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) print(len(cuentas)) print("#####################7.6") ms={12:"hola",25:"venir ya"} hora={1:"almorzar",12:"dormir"} print(ms,hora) print(len(ms)) print(len(hora)) print("#####################7.7") errores={123:"lista1",2:"lista13"} calificacion={15:"andres",13:"tocas"} print(errores,calificacion) print(len(errores)) print(len(calificacion)) print("#####################7.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} edad={20:"jose",23:"jorge",18:"pedro"} print(canciones,edad) print(len(canciones)) print(len(edad)) print("#####################7.9") alumnos={145:"eduardo",589:"marcos"} profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(alumnos,profesor) print(len(alumnos)) print(len(profesor)) print("#####################7.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) print(len(candidatos)) print("############################################################### ITERACION...8 ") #ITERACION print("#####################8.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} print(diccionario,diccionario1) for key in diccionario: print(diccionario[key]) print("#####################8.2") saludo={2:"buenos dias",1:"buenos dias"} print(saludo) for key in saludo: print(saludo[key]) print("#####################8.3") nombre={4:"luis",58:"carlos"} print(nombre) for k in nombre: print(nombre[k]) print("#####################8.4") nota={"erica":00,"pedro":12,"carlos":14} cursos={"mate":4,"algebra":4,"analisis":3} print(nota,cursos) for i in cursos: print(cursos[i]) for k in nota: print(nota[k]) print("#####################8.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) for key,value in cuentas.items(): print(key,value) print("#####################8.6") ms={12:"hola",25:"venir ya"} print(ms) for k,v in ms.items(): print(k,v) print("#####################8.7") calificacion={15:"andres",13:"tocas"} print(calificacion) for k,v in calificacion.items(): print(k,v) print("#####################8.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} print(canciones) for k,v in canciones.items(): print(k,v) print("#####################8.9") alumnos={145:"eduardo",589:"marcos"} profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(alumnos,profesor) for k,v in profesor.items(): print(k,v) for i in alumnos: print(alumnos[i]) print("#####################8.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos,conocidos) for y in candidatos: print(candidatos[y]) print("###############################################################BUSQUEDA...9 ") #BUSQUEDA print("#####################9.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} print(diccionario) print(diccionario.get(616)) print("#####################9.2") saludo={2:"buenos dias",1:"buenos dias"} saludo={2:"buenos dias",1:"buenos dias"} print(saludo,saludo) print(saludo.get(2)) print("#####################9.3") nombre={4:"luis",58:"carlos"} print(nombre) print(nombre.get(4)) print("#####################9.4") cursos={"mate":4,"algebra":4,"analisis":3} print(cursos) print(cursos.get("mate")) print("#####################9.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) print(cuentas.get("marco")) print("#####################9.6") hora={1:"almorzar",12:"dormir"} print(hora) print(hora.get(12)) print("#####################9.7") calificacion={15:"andres",13:"tocas"} print(errores,calificacion) print(calificacion.get(15)) print("#####################9.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} print(canciones) print(canciones.get(389)) print("#####################9.9") profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(profesor) print(profesor.get("analisis")) print("#####################9.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) print(candidatos.get(17)) print("###############################################################ELIMINACION...13") #ELIMINACION print("#####################13.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} print(diccionario) del diccionario print("#####################13.2") saludo={2:"buenos dias",1:"buenos dias"} saludo={2:"buenos dias",1:"buenos dias"} print(saludo,saludo) del saludo print("#####################13.3") nombre={4:"luis",58:"carlos"} print(nombre) del nombre print("#####################13.4") cursos={"mate":4,"algebra":4,"analisis":3} print(cursos) del cursos print("#####################13.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) del cuentas print("#####################13.6") hora={1:"almorzar",12:"dormir"} print(hora) del hora print("#####################13.7") calificacion={15:"andres",13:"tocas"} print(calificacion) del calificacion print("#####################13.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} print(canciones) del canciones print("#####################13.9") profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(profesor) del profesor print("#####################13.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) del candidatos print("###############################################################BUSQUEDA...14 ") #BUSQUEDA print("#####################14.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} print(diccionario) diccionario["hola peru"]=6 print(diccionario) print("#####################14.2") saludo={2:"buenos dias",1:"buenos dias"} print(saludo) saludo[67]="buenas noches" print(saludo) print("#####################14.3") nombre={4:"luis",58:"carlos"} print(nombre) nombre[55]="juliana" print(nombre) print("#####################14.4") cursos={"mate":4,"algebra":4,"analisis":3} print(cursos) cursos["fisica"]=3 print(cursos) print("#####################14.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) cuentas["cesar"]=657 print(cuentas) print("#####################14.6") hora={1:"almorzar",12:"dormir"} print(hora) hora[8]="salir" print(hora) print("#####################14.7") calificacion={15:"andres",13:"tocas"} print(calificacion) calificacion[18]="einer" print(calificacion) print("#####################14.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} print(canciones) canciones[87]="sanjuanera" print(canciones) print("#####################14.9") profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(profesor) profesor["circuitos"]="llecys" print(profesor) print("#####################14.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) candidatos[7]="parker" print(candidatos) print("###############################################################AGREGADO....15 ") #AGREGADO print("#####################15.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} print(diccionario) diccionario.setdefault(1,"peruanos de corazon") print(diccionario) print("#####################15.2") saludo={2:"buenos dias",1:"buenos dias"} saludo={2:"buenos dias",1:"buenos dias"} print(saludo,saludo) saludo.setdefault(2,"todos saludamos") print(saludo) print("#####################15.3") nombre={4:"luis",58:"carlos"} print(nombre) nombre.setdefault("azul",96) print(nombre) print("#####################15.4") cursos={"mate":4,"algebra":4,"analisis":3} print(cursos) cursos.setdefault(25,"sistemas digitrales") print(cursos) print("#####################15.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) cuentas.setdefault("german",629) print(cuentas) print("#####################15.6") hora={1:"almorzar",12:"dormir"} print(hora) hora.setdefault(98,"despertar") print(hora) print("#####################15.7") calificacion={15:"andres",13:"tocas"} print(calificacion) calificacion.setdefault(16,"rosa") print(calificacion) print("#####################15.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} print(canciones) canciones.setdefault(798,"rock") print(canciones) print("#####################15.9") profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(profesor) profesor.setdefault("identidad","floress") print(profesor) print("#####################15.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) candidatos.setdefault(15,"rubi") print(candidatos) print("############################################################### ANULACION...16 ") #ANULACION print("#####################16.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} diccionario1={1:"pago",2:"salir",3:"lanzar",123:"parada"} print(diccionario,diccionario1) diccionario.clear() diccionario1.clear() print(diccionario) print(diccionario1) print("#####################16.2") saludo={2:"buenos dias",1:"buenos dias"} saludo={2:"buenos dias",1:"buenos dias"} print(saludo,saludo) saludo.clear() print(saludo) print("#####################16.3") vuelo={4:"trujillo",58:"lima"} nombre={4:"luis",58:"carlos"} print(vuelo,nombre) vuelo.clear() nombre .clear() print(vuelo) print(nombre) print("#####################16.4") nota={"erica":00,"pedro":12,"carlos":14} cursos={"mate":4,"algebra":4,"analisis":3} print(nota,cursos) nota.clear() cursos.clear() print(nota) print(cursos) print("#####################16.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) cuentas.clear() print(cuentas) print("#####################16.6") ms={12:"hola",25:"venir ya"} hora={1:"almorzar",12:"dormir"} print(ms,hora) ms.clear() hora.clear() print(ms) print(hora) print("#####################16.7") errores={123:"lista1",2:"lista13"} calificacion={15:"andres",13:"tocas"} print(errores,calificacion) errores.clear() calificacion.clear() print(errores) print(calificacion) print("#####################16.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} edad={20:"jose",23:"jorge",18:"pedro"} print(canciones,edad) canciones.clear() edad.clear() print(canciones) print(edad) print("#####################16.9") alumnos={145:"eduardo",589:"marcos"} profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(alumnos,profesor) alumnos.clear() profesor.clear() print(alumnos) print(profesor) print("#####################16.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) candidatos.clear() print(candidatos) print("###########################################################clonado...17") ############## print("#############17.1") utiles1={128:"goma",111:"tijera",77:"folder"} x=utiles1.copy() print(utiles1) print(x) print("#############17.2") vegetales={"a":"lechuga","b":"rabanito","c":"coliflor"} y=vegetales.copy() print(vegetales) print(y) print("###############17.3") galletas={"rojo":"soda","amarillo":"vainilla","chocolate":"rellenita"} rico=galletas.copy() print(galletas) print(rico) print("###############17.4") frutas={"p":"piña","f":"fresa","per":"pera","n":"naranja"} i=frutas.copy() print(frutas) print(i) print("###############17.5") region={"2300msnm":"quechua",1523:"yunga",478:"chala"} o=region.copy() print(region) print(o) print("###############17.6") listasss={1:"atender","ganar":"dos",33:"oro"} i=listasss.copy() print(listasss) print(i) print("###############17.7") li={1111:"hola",22:"llegas temprano",3:"tarde",4:"no deviste venir"} y=li.copy() print(li) print(y) print("###############17.8") prom={15:"yeri",19:"jose",12:"jan",18:"einer 2",16:"inga"} promedio= prom.copy() print(prom) print(promedio) print("###############17.9") numeros={145:25,12:25,56:48,89:96,10:387,20:6972} i=numeros.copy() print(numeros) print(i) print("###############17.10") lisa={"r":"roolo","e":"elefante","w":"wuilder","u":"vaca"} t=lisa.copy() print(lisa) print(t) print("###############################################################INSERCION...19 ") #INSERCION print("#####################19.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} print(diccionario) diccionario["hola peru"]=6 print(diccionario) print("#####################19.2") saludo={2:"buenos dias",1:"buenos dias"} print(saludo) saludo[67]="hasta pronto" print(saludo) print("#####################19.3") nombre={4:"luis",58:"carlos"} print(nombre) nombre[55]="yulissa" print(nombre) print("#####################19.4") cursos={"mate":4,"algebra":4,"analisis":3} print(cursos) cursos["fisica"]=6 print(cursos) print("#####################19.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) cuentas["cesar"]=8967 print(cuentas) print("#####################19.6") hora={1:"almorzar",12:"dormir"} print(hora) hora[8]="correr" print(hora) print("#####################19.7") calificacion={15:"andres",13:"tocas"} print(calificacion) calificacion[18]="julian" print(calificacion) print("#####################19.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} print(canciones) canciones[87]="baladas" print(canciones) print("#####################19.9") profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(profesor) profesor["circuitos"]="gastulo" print(profesor) print("#####################19.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) candidatos[7]="herrera" print(candidatos) print("###############################################################EXTRACCION...20 ") #EXTRACCION print("#####################20.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} print(diccionario) x=diccionario.pop("mundo") print(diccionario) print(x) print("#####################20.2") saludo={2:"buenos dias",1:"buenos dias"} print(saludo) x=saludo.pop(2) print(saludo) print(x) print("#####################20.3") nombre={4:"luis",58:"carlos"} print(nombre) x=nombre.pop(4) print(nombre) print(x) print("#####################20.4") cursos={"mate":4,"algebra":4,"analisis":3} print(cursos) x=cursos.pop("mate") print(cursos) print(x) print("#####################20.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) x=cuentas.pop("marco") print(cuentas) print(x) print("#####################20.6") hora={1:"almorzar",12:"dormir"} print(hora) x=hora.pop(1) print(hora) print(x) print("#####################20.7") calificacion={15:"andres",13:"tocas"} print(calificacion) x=calificacion.pop(13) print(calificacion) print(x) print("#####################20.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} print(canciones) x=canciones.pop(59) print(canciones) print(x) print("#####################20.9") profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(profesor) x=profesor.pop("ingles") print(profesor) print(x) print("#####################20.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) x=candidatos.pop(8) print(candidatos) print(x) print("###############################################################VER CLAVES...24 ") #VER CLAVES print("#####################24.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} print(diccionario) print(diccionario.keys()) print("#####################24.2") saludo={2:"buenos dias",1:"buenos dias"} print(saludo) print(saludo.keys()) print("#####################24.3") nombre={4:"luis",58:"carlos"} print(nombre) print(nombre.keys()) print("#####################24.4") cursos={"mate":4,"algebra":4,"analisis":3} print(cursos) print(cursos.keys()) print("#####################24.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) print(cuentas.keys()) print("#####################24.6") hora={1:"almorzar",12:"dormir"} print(hora) print(hora.keys()) print("#####################24.7") calificacion={15:"andres",13:"tocas"} print(calificacion) print(calificacion.keys()) print("#####################24.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} print(canciones) print(canciones.keys()) print("#####################24.9") profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(profesor) print(profesor.keys()) print("#####################24.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) print(candidatos.keys()) print("###############################################################VER CLAVES...25 ") #VER CLAVES print("#####################25.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} print(diccionario) print(diccionario.values()) print("#####################25.2") saludo={2:"buenos dias",1:"buenos dias"} print(saludo) print(saludo.values()) print("#####################25.3") nombre={4:"luis",58:"carlos"} print(nombre) print(nombre.values()) print("#####################25.4") cursos={"mate":4,"algebra":4,"analisis":3} print(cursos) print(cursos.values()) print("#####################25.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) print(cuentas.values()) print("#####################25.6") hora={1:"almorzar",12:"dormir"} print(hora) print(hora.values()) print("#####################25.7") calificacion={15:"andres",13:"tocas"} print(calificacion) print(calificacion.values()) print("#####################25.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} print(canciones) print(canciones.values()) print("#####################25.9") profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(profesor) print(profesor.values()) print("#####################25.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) print(candidatos.values()) print("###############################################################VER CONVERSION...26 ") #CONVERSION print("#####################26.1") diccionario={"mundo":"terricolas",123:"parada",616:"horda"} print(diccionario) l=list(diccionario) print(diccionario) print(l) print("#####################26.2") saludo={2:"buenos dias",1:"buenos dias"} print(saludo) l=list(saludo) print(saludo) print(l) print("#####################26.3") nombre={4:"luis",58:"carlos"} print(nombre) t=tuple(nombre) print(nombre) print(t) print("#####################26.4") cursos={"mate":4,"algebra":4,"analisis":3} print(cursos) t=tuple(cuentas) print(cursos) print(t) print("#####################26.5") cuentas={"marco":25,"alonso":869,"alfredo":570} print(cuentas) s=set(cuentas) print(cuentas) print(s) print("#####################26.6") hora={1:"almorzar",12:"dormir"} print(hora) s=set(hora) print(hora) print(s) print("#####################26.7") calificacion={15:"andres",13:"tocas"} print(calificacion) l=list(calificacion.values()) print(calificacion) print(l) print("#####################26.8") canciones={8:"guayno",59:"regueton",389:"tomorrowland"} print(canciones) t=tuple(canciones.values()) print(canciones) print(t) print("#####################26.9") profesor={"ingles":"clarita","mate":"alejandra","analisis":"doris"} print(profesor) s=set(profesor.values()) print(profesor) print(s) print("#####################26.10") candidatos={8:"toledo",17:"maria",61:"maria"} print(candidatos) t=tuple(candidatos.values()) print(candidatos) print(t)
545ea73f067794646b7ca6c43e68fa059adac3d5
aisomon/python-Pattern
/Pattern using Python/numberPyramid.py
287
3.875
4
""" 1 222 33333 4444444 """ n = int(input("Enter your number : ")) n = n + 1 for i in range(1,n): #for space for j in range(n-i): print(" ", end="") #for * print for k in range((2*i)-1): print(i, end="") print()
ee6a17675806e5dda3df5b4afbf3dc06dd28ece7
MauricioFBL/computational_thinking_python
/007_rangos.py
280
3.875
4
# RANGOS # Secuencia de enteros # Son inmutables # Eficientes en memoria # range(comienzo,fin, pasos) a = range(2,10,3) print(type(a)) print(a) for i in a: print(i) id(range) for num in range(0,100,3): print(num) for num in range(1,100,2): print(num)
40da5f514259eeee363f5d14d3d747048f62f58b
wafa-b/python-programs
/if-statement2.py
166
3.625
4
name = 'Wafa' if name != 'Techcampus': if name == 'Wafa': print('Name is Wafa') else: print('Name is ') else: print('Name is Techcampus')
a1d1ee47bb9211b0c8b38efbeaca7bd97570fa59
SnehuD/Python-Programs
/Operators/BitwiseOp.py
360
3.828125
4
n1 = 10 n2 = 20 print('\n-----------------------BITWISE OPERATIONS-------------------------\n') print('Number1\t\t : ', n1) print('Number2\t\t : ', n2) print('\nn1 & n2\t\t : ', n1 & n2) print('n1 | n2\t\t : ', n1 | n2) print('n1 ^ n2\t\t : ', n1 ^ n2) print('n1 >> n2\t : ', n1 >> n2) print('n1 << n2\t : ', n1 << n2) print('~ n1\t\t : ', ~n1)
bb2a0cc7da2e0618d33bf9c1aa6b3086b86311b2
svelezp/ST0245-008
/punto3.py
227
4.09375
4
cadena = str(input("ingrese una cadena para invertir: ")) def reverse(cadena): if len(cadena) == 1: return cadena else: return cadena[-1] + reverse(cadena[:-1]) print(reverse(cadena))
a806a0bd76dfc353bb84b8d27a44e5d038e8b9b1
hingu-parth/Data_Structures-Python
/Tree/589. N-ary Tree Preorder Traversal.py
787
3.703125
4
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def preorder(self, root: 'Node') -> List[int]: # Solution 1: Iterative if not root: return [] traversal = [] stack = [root] while stack: cur = stack.pop() traversal.append(cur.val) a=reversed(cur.children) stack.extend(a) return traversal # Solution 2: Recursive stack=[] if not root: return [] else: stack.append(root.val) for i in root.children: stack+=self.preorder(i) return stack
80dfbc05032294226328cda914278f987271f94f
eldenis/PythonG_ex
/ejemplos/118.py
585
3.5625
4
#Un programa que desglose una cantidad entera de euros #en billetes de 500,200,100,50,20,10,5 y monedas de 1 y 2 #usando ciclos for-in n=0 #input de n while (n<=0): n=int(raw_input("Introduzca una cantidad entera de euros: ")) #declaracion de Denominaciones billetes=[500,200,100,50,20,10,5] monedas=[2,1] print "\nBilletes" print "--------" for i in billetes: if int(n/i)>0: print i," =",int(n/i) n=n-((int(n/i))*i) if n>0: print "\n\nMonedas" print "-------" for i in monedas: if int(n/i)>0: print i," =",int(n/i) n=n-((int(n/i))*i)
b679ee03497ae9d6cf88711645c3c204ff86bfc0
GauravPatel89/EPAi2_capstone
/certificate_mailer_app.py
2,974
3.953125
4
import argparse import certificate_mailer def main(args): """ This function implements certificate mailing application using certificate_mailer package Parameters: args(argparse obj): argparse object containing arguments passed by the user. Returns: None """ try: if args.verbose: print('Arguments passed',args) # Call create_n_mail_certificates function with proper arguments if certificate_mailer.create_n_mail_certificates( csv_file_name = args.csv_file,course_name = args.course_name, sign_name = args.sign_name, total_marks = args.total_marks, sender_email = args.sender_email, mail_interval = args.interval, certi_template = args.certi_template, certi_dir = args.certi_dir, out_format = args.out_format,overwrite = args.overwrite, create_certi_only = args.create_certificates_only,verbose = args.verbose): print('-'*30) print('Success!!!') else: print('-'*30) print('Failed!!!') except Exception as e: print(e) print('-'*30) print('Failed!!!') if __name__ == "__main__": """ This is executed when run from the command line """ parser = argparse.ArgumentParser() # Required positional argument parser.add_argument("csv_file",type=str, help="csv file containing the student data") parser.add_argument("course_name",type=str, help="Name of the course") parser.add_argument("sign_name",type=str, help="Signature name to be printed on certificate") parser.add_argument("total_marks",type=float, help="Total marks in the course") parser.add_argument("sender_email",type=str, help="Email id of sender. Password will be asked later") parser.add_argument("-t","--certi_template",type=str,default='./certificate_mailer/data/certi_template.jpg',help="Path where created certificates will be saved. (Default: %(default)r)") parser.add_argument("-d","--certi_dir",type=str,default='./certificates',help="Directory where created certificates will be saved. (Default: %(default)r)") parser.add_argument("-f","--out_format",type=str,default='jpg',help=".Output format ['jpg','png','bmp','pdf'] (Default: %(default)r)") parser.add_argument("-i","--interval",type=float,default=2,help="Time interval(seconds) between consecutive mails. (Default: %(default)r)") parser.add_argument("-o","--overwrite",action="store_true",default=False,help="Whether to overwrite generated certificates if already exist. (Default: %(default)r)") parser.add_argument("-c","--create_certificates_only",action="store_true",default=False,help="Only create certificates don't send. (Default: %(default)r)") parser.add_argument("-v", "--verbose", action="store_true", default=False,help= "Whether vebose message are required. (Default: %(default)r)") args = parser.parse_args() main(args)
80bc120f9c1b824c0af9129cbd574f6baa255b8a
Haoran1227/LSTM-Neural-Network
/Layers/LSTM.py
14,046
3.703125
4
import numpy as np import copy from Layers.Base import base_layer from Layers.TanH import TanH from Layers.Sigmoid import Sigmoid class LSTM_cell: """ This class defines one LSTM-cell which is used to build a LSTM layer. It includes the realization of forward and backward propagation algorithm Attributes: W_xh, W_hh, B_h, W_hy, B_y: trainable parameters of LSTM-cell. Because LSTM layer shares weights in sequential LSTM cells, we need to make all LSTM cells in the same layer have the same weights and the update of weights needs to be implemented after calculating all gradients of cells. sigmoid: store sigmoid activation functions so that the variables can be transferred from forward pass to backward pass tanh: store tanh activation functions cache: store the variables in forward pass for the gradient calculation in backward pass. """ def __init__(self, W_xh, W_hh, B_h, W_hy, B_y): # W_xh = [W_xf W_xi W_xc W_xo].T shape:(4H, J) each W:(H, J) # W_hh = [W_hf W_hi W_hc W_ho].T shape:(4H, H) # B_h = [B_xf B_xi B_xc B_xo] shape:(1, 4H) each B:(1, H) # W_hy shape:(K, H) # B_y shape:(1, K) self.W_xh, self.W_hh, self.B_h, self.W_hy, self.B_y = W_xh, W_hh, B_h, W_hy, B_y # Variables which are stored in forward pass for backward pass self.sigmoid = None # store sigmoid activation functions self.tanh = None # store tanh activation functions self.cache = None # store variables used in calculating gradients in backward pass def forward(self, input_tensor, hidden_state, cell_state): """ This function realize the forward propagation of one LSTM-cell Args: input_tensor: x_t, input tensor of current slot. hidden_state: h_t-1, hidden state of previous LSTM-cell (time slot) cell_state: c_t-1, cell state of previous LSTM-cell (time slot) Returns: ndarray, output_tensor: y_t, output tensor of current slot. ndarray, next_h: h_t, hidden state of previous LSTM-cell, which will be transferred to next cell ndarray, next_c: c_t, cell state of previous LSTM-cell, which will be transferred to next cell """ # Data preparation. x = input_tensor.reshape(1, -1) # shape: (1,J) prev_h = hidden_state # shape: (1,H) prev_c = cell_state # shape: (1,H) _, H = hidden_state.shape # hidden size # initialize tanh and sigmoid functions self.sigmoid = [Sigmoid() for _ in range(4)] self.tanh = [TanH() for _ in range(2)] # forward propagation in LSTM-cell embedding = np.dot(x, self.W_xh.T) + np.dot(prev_h, self.W_hh.T) + self.B_h # (1,4H) f = self.sigmoid[0].forward(embedding[:, :H]) i = self.sigmoid[1].forward(embedding[:, H:2*H]) c_hat = self.tanh[0].forward(embedding[:, 2*H:3*H]) o = self.sigmoid[2].forward(embedding[:, 3*H:]) # calculation of new cell_state next_c = prev_c * f + i * c_hat # calculation of new hidden_state tanh_output = self.tanh[1].forward(next_c) next_h = o * tanh_output # calculation of output output_tensor = self.sigmoid[3].forward(np.dot(next_h, self.W_hy.T) + self.B_y) # return the variables which are needed in backward propagation self.cache = [f, i, c_hat, o, x, prev_h, prev_c, tanh_output, next_h, next_c] return output_tensor, next_h, next_c def backward(self, error_tensor, dnext_c, dnext_h): """ This function realize the backward propagation of one LSTM-cell Args: error_tensor: e_t, input error tensor of current LSTM-cell dnext_c: input cell_state error, input error tensor refer to cell state from next LSTM-cell dnext_h: input hidden_state error, input error tensor refer to hidden state from next LSTM-cell Returns: dx, dprev_c, dprev_h, dW_xh, dW_hh, dB_h, dW_hy, dB_y # the derivatives of output to previous LSTM-cell and previous layer and trainable parameters """ # load stored variables in forward pass. f, i, c_hat, o, x, prev_h, prev_c, tanh_output, next_h, next_c = self.cache # calculation of gradients of W_hy and B_y error_tensor = self.sigmoid[3].backward(error_tensor) dW_hy = np.dot(error_tensor.reshape(-1, 1), next_h.reshape(1, -1)) # shape: (K, H) dB_y = error_tensor # shape: (1, K) # backward propagation of error error_tensor = np.dot(error_tensor, self.W_hy) dnext_h += error_tensor do = self.sigmoid[2].backward(dnext_h * tanh_output) dnext_c += self.tanh[1].backward(dnext_h * o) dprev_c = dnext_c * f df = self.sigmoid[0].backward(dnext_c * prev_c) dc_hat = self.tanh[0].backward(dnext_c * i) di = self.sigmoid[1].backward(dnext_c * c_hat) # calculation of gradients dmix = np.concatenate((df, di, dc_hat, do), axis=1) #(1, 4H) dx = np.dot(dmix, self.W_xh) dprev_h = np.dot(dmix, self.W_hh) dW_xh = np.dot(dmix.reshape(-1, 1), x.reshape(1, -1)) dW_hh = np.dot(dmix.reshape(-1, 1), prev_h.reshape(1, -1)) dB_h = dmix return dx, dprev_c, dprev_h, dW_xh, dW_hh, dB_h, dW_hy, dB_y class LSTM(base_layer): """ This class build LSTM layer based on LSTM-cell class. """ def __init__(self, input_size, hidden_size, output_size): super().__init__() self.J, self.H, self.K = input_size, hidden_size, output_size # initialize trainable parameters self.W_xh = np.random.rand(4*self.H, self.J) # W_xh = [W_xf W_xi W_xc W_xo].T shape:(4H, J) W-(H, J) self.W_hh = np.random.rand(4*self.H, self.H) # W_hh = [W_hf W_hi W_hc W_ho].T shape:(4H, H) self.B_h = np.random.rand(1, 4*self.H) # B_h = [B_xf B_xi B_xc B_xo] shape:(1, 4H) B-(1, H) self.W_hy = np.random.rand(self.K, self.H) # W_hy shape:(K, H) self.B_y = np.random.rand(1, self.K) # B_y shape:(1, K) self._memory = False # indicates whether subsequent batch sequence has relation with the last one # initialize the hidden_state and cell_state for time slot 0. self.hidden_state = np.zeros((1, self.H)) self.cell_state = np.zeros((1, self.H)) # initialize gradients self.grad_weights = None # initialize optimizers self._optimizer = None self.W_xh_optimizer, self.W_hh_optimizer, self.W_hy_optimizer, \ self.B_y_optimizer, self.B_h_optimizer= None, None, None, None, None # bulid LSTM layer using LSTM-cells self.layer = [] def forward(self, input_tensor): """ This function implement forward propagation of LSTM layer with help of the forward propagation function of LSTM-cell Args: input_tensor: input tensor of LSTM layers, its shape should be (batch_size, input_size) Returns: output_tensor: output tensor of LSTM layers, its shape is (batch_size, output_size) """ batch_size = input_tensor.shape[0] # batch size: input_tensor.shape[0] output_tensor = np.zeros((batch_size, self.K)) # determine whether sequential batches have relation. If memory is true, the hidden_state # and cell_state of last cell will be transferred to the next cell if not self._memory: # if the next batch(time batch) has no relation with the previous batch self.hidden_state = np.zeros((1, self.H)) # initialize hidden_state as 0 self.cell_state = np.zeros((1, self.H)) # initialize cell_state as 0 # build LSTM layer based on LSTM cells for t in range(batch_size): cell = LSTM_cell(self.W_xh, self.W_hh, self.B_h, self.W_hy, self.B_y) output_tensor[t, :], self.hidden_state, self.cell_state = \ cell.forward(input_tensor[t, :], self.hidden_state, self.cell_state) self.layer.append(cell) return output_tensor def backward(self, error_tensor): """ This function implement backward propagation of LSTM layer with help of the backward propagation function of LSTM-cell Args: error_tensor: error of LSTM layers which is transferred from next layer, shape should be (B,K) Returns: output_error: output error transferred from LSTM layers to last layer, shape is (batch_size, output_size) """ # initialization # initialize output_error batch_size = error_tensor.shape[0] output_error = np.zeros((batch_size, self.J)) # initialize hidden_error tensor and cellstate_error for last layer dnext_c, dnext_h = np.zeros((1, self.H)), np.zeros((1, self.H)) # initialization of gradients # W_xh:(4H, J) W_hh:(4H, H) B_h:(1, 4H) W_hy:(K, H) B_y:(1, K) grad_W_xh, grad_W_hh, grad_W_hy, grad_B_h, grad_B_y = \ np.zeros_like(self.W_xh), np.zeros_like(self.W_hh), np.zeros_like(self.W_hy), np.zeros_like(self.B_h), np.zeros_like(self.B_y) # calculation of hidden_error and output error for t in reversed(range(batch_size)): output_error[t, :], dnext_c, dnext_h, dW_xh, dW_hh, dB_h, dW_hy, dB_y =\ self.layer[t].backward(error_tensor[t, :], dnext_c, dnext_h) # accumulation of gradients of LSTM-cells grad_W_xh += dW_xh grad_W_hh += dW_hh grad_B_h += dB_h grad_W_hy += dW_hy grad_B_y += dB_y # stores gradients of hidden units for Unitest self.grad_weights = np.concatenate((grad_W_xh, grad_W_hh, grad_B_h.reshape(-1, 1)), axis=1) # update weights and biases if self._optimizer is not None: self.W_xh = self.W_xh_optimizer.calculate_update(self.W_xh, grad_W_xh) self.W_hh = self.W_hh_optimizer.calculate_update(self.W_hh, grad_W_hh) self.W_hy = self.W_hy_optimizer.calculate_update(self.W_hy, grad_W_hy) self.B_h = self.B_h_optimizer.calculate_update(self.B_h, grad_B_h) self.B_y = self.B_y_optimizer.calculate_update(self.B_y, grad_B_y) # After one propagation process, the memory flag will be re-initialized. self._memory = False return output_error # initialization of weights and biases def initialize(self, weights_initializer, bias_initializer): #fucntion which can reinitialize weights and bias # for W_xh, B_h: fan_in = input_size fan_out=hidden_size self.W_xh = weights_initializer.initialize(self.W_xh.shape, self.J, self.H) self.B_h = bias_initializer.initialize(self.B_h.shape, self.J, self.H) # for W_hh: fan_in = hidden_size fan_out=hidden_size self.W_hh = weights_initializer.initialize(self.W_hh.shape, self.H, self.H) # for W_hy, B_y: fan_in = hidden_size fan_out=output_size self.W_hy = weights_initializer.initialize(self.W_hy.shape, self.H, self.K) self.B_y = bias_initializer.initialize(self.B_y.shape, self.H, self.K) @property def memorize(self): return self._memory @memorize.setter def memorize(self, mem): self._memory = mem # property of weights, which is used to make LSTM compatible with other layers @property def weights(self): # weights only include W_xh, W_hh, B_h. It means the parameters needed for calculation of hidden state. # weights must be [W_xh, W_hh, B_h.T] in order to correspond to Unitest. # In Helpers.py, use "print(it.multi_index) print(analytical_derivative - numerical_derivative)" to check order of weights weights_hidden = np.concatenate((self.W_xh, self.W_hh, self.B_h.T), axis=1) return weights_hidden @weights.setter def weights(self, weights_hidden): # Because the base layer has weights attribute and initialized as None. # We need to determine whether weights is None, otherwise the initialization of RNN has fault. # W_xh: (4H, J) W_hh: (4H, H) B_h: (1, 4H) if weights_hidden is not None: self.W_xh = weights_hidden[:, :self.J] self.W_hh = weights_hidden[:, self.J:-1] self.B_h = weights_hidden[:, -1].reshape(1, 4*self.H) else: self.W_xh = None self.W_hh = None self.B_h = None # property to get gradients @property def gradient_weights(self): return self.grad_weights # property to get and set optimizers @property def optimizer(self): return self._optimizer @optimizer.setter def optimizer(self,opt): self._optimizer = opt self.W_xh_optimizer = copy.deepcopy(self._optimizer) self.W_hh_optimizer = copy.deepcopy(self._optimizer) self.W_hy_optimizer = copy.deepcopy(self._optimizer) self.B_h_optimizer = copy.deepcopy(self._optimizer) self.B_y_optimizer = copy.deepcopy(self._optimizer) # Bias should not participate in regularization self.B_h_optimizer.regularizer = None self.B_y_optimizer.regularizer = None @property def regularization_loss(self): loss = 0 if self._optimizer is not None: # if weights_optimizer is defined if self._optimizer.regularizer is not None: #if weights_optimizer has regularizer # calculate regularization_loss loss = self.W_xh_optimizer.regularizer.norm(self.W_xh) + \ self.W_hh_optimizer.regularizer.norm(self.W_hh) + \ self.W_hy_optimizer.regularizer.norm(self.W_hy) return loss
9b8597da4c2dfd80434a86efac198f6659629ed5
ShiJingChao/Python-
/PythonStart/Blackhorse/HM_Class/388封装案例身份运算符.py
517
3.984375
4
# 身份运算符用于比较两个对象的内存地址是否一致————是否对同一个对象的引用 # 在Python中针对None比较时,建议使用is判断 # is 与 == 区别 # is 用于判断两个变量引用对象是否为同一个 # ==用于判断引用的变量的值是否相等 a = [1, 2, 3] b = [1, 2, 3] c = 1 print(id(a[0])) # print(id(a[1])) print(id(b[0])) # print(id(b[1])) print(id(c)) print(b[0] is a[0]) # True print(id(c) is id(b[0])) # False print(id(a[0]) is id(b[0])) # False
30f5fc1312ef746f8c09be1ff4b5606c00bbef4c
Jonathan-aguilar/DAS_Sistemas
/Ago-Dic-2019/Luis Llanes/Practica1/ejercicio4-1.py
176
3.640625
4
pizzas = ["triple carne", "extra queso", "suprema"] for i in range(0, len(pizzas)): print("Me gusta la pizza", pizzas[i]) print("La verdad si me gusta mucho la pizza XD")
f54f4ec5e8e4f5c2e130521718690e57c267d65a
lienero/-2019
/prime number/실습1.py
528
3.578125
4
while True: input_number=int(input(" 소수들을 알고 싶나요. 그럼 입력해보세요?")) count_num=0 prime_check=0 print("입력된 수는 %d" %input_number) for i in range(1, input_number+1): prime_check = 0 for j in range(1, i+1): if(i % j == 0): prime_check += 1 if (prime_check == 2): print("소수=%d \n" %i) count_num += 1 print("총 소수의 개수는= %d개 입니다. " %count_num)
7e780a746060b85adb5c63923705ca8e291c6557
araviii/python-programming
/beginner level/alphebet or not.py
93
3.71875
4
astring =input(" ") if astring in ('a'to'z'); print "alpthebet" else: print "non alphebet"
4b2c5c1d4bf88535d808dab14e8b67ba601ae5db
barack98/Python-Practice
/maths_functions.py
1,042
3.78125
4
import math #Access methods by referencing the module print("ceil(4.5) = ", math.ceil(4.5)) print("floor(4.4) = ", math.floor(4.4)) print("fabs(-4.4) = ", math.fabs(-4.4)) # factorial = 1*2*3*4 print("factorial(4) = ", math.factorial(4)) #return remainder of division print("fmod(5,4) = ", math.fmod(5,4)) #receiving a float and returning an int print("trunc(4.2) = ", math.trunc(4.2)) #return x^y (power) print("pow(2,2) = ", math.pow(2,2)) #return the square root print("sqrt(4) = ", math.sqrt(4)) #special values print("math.e = ", math.e) print("math.pi = ", math.pi) #return e^x print("exp(4) = ", math.exp(4)) #return the natural logarithm e * e * e ~= 20 so log(20) tells #you that e^3 ~= 20 print("log(20) = ", math.log(20)) #you can define the base of 10^3 + 1000 print("log(1000,10) = ", math.log(1000, 10)) #You can also use base 10 like this print("log10(1000) = ", math.log10(1000)) #Convert radian to degree and vice versa print("degrees(1.5708) = ", math.degrees(1.5708)) print("radians(90) = ", math.radians(90))
438570094a9b58bb2c7ab1faf39a6a43d197c08b
givewgun/python_misc_year1_CU
/grader/chap2 selection/ด้านของสามเหลี่ยม (3 sides).py
123
3.765625
4
#triangle side rule a,b,c = [int(i) for i in input().split()] if a+b>c and a+c>b and b+c>a: print('YES') else: print('NO')
aeffea1c6fac6a3301e1405f543a13703736a82c
Thijsvs/Mastermind
/TheGame.py
11,683
3.609375
4
from tkinter import * import random import itertools import bot class mastermind: def __init__(self): return # handmatig de code invullen def manualcode(self): self.colourcode = [] colours = ['red', 'pink', 'yellow', 'green', 'orange','blue'] print('red,', 'pink', ' yellow,', ' green,', ' orange,',' blue') self.color1 = input('Vul uw 1e kleur in: ') self.color2 = input('Vul uw 2e kleur in: ') self.color3 = input('Vul uw 3e kleur in: ') self.color4 = input('Vul uw 4e kleur in: ') if self.color1 not in colours or self.color2 not in colours or self.color3 not in colours or self.color4 not in colours: print('probeer het opnieuw') mastermind.manualcode(self) else: self.colourcode = [self.color1, self.color2, self.color3, self.color4] print(self.colourcode) # de bot maakt de code def AIcode(self): colours = ['red', 'pink', 'yellow', 'green', 'orange','blue'] self.colourcode = [] for value in range(0, 4): self.colourcode.append(random.choice(colours)) # houdt het aantal pogingen bij, als de grens wordt overscheden wordt het spel stop gezet def pogingen(self): self.attempts += 1 if self.attempts > 9: self.helaasFrame = Frame(self.gameFrame, bg='green') self.helaasFrame.place(y=70, x=100, height=450, width=200) self.helaasLabel = Label(self.helaasFrame, bg='green', fg='red', text='Helaas!\n U heeft verloren', font=('ariel', 16, 'bold')) self.helaasLabel.place(y=0, x=0) self.returnButton = Button(self.helaasFrame, command=lambda: mastermind.Afsluiten(self), text='Afsluiten', bg='pink', fg='blue', font=('ariel', 8, 'bold')) self.returnButton.place(y=150, x=60) else: mastermind.manualguess(self) # handmatig de code van de bot oplossen def manualguess(self): self.correct = 0 self.wrongplace = 0 self.colours1 = ['red', 'pink', 'yellow', 'green', 'orange', 'blue'] self.colours2 = ['red', 'pink', 'yellow', 'green', 'orange', 'blue'] self.colours3 = ['red', 'pink', 'yellow', 'green', 'orange', 'blue'] self.colours4 = ['red', 'pink', 'yellow', 'green', 'orange', 'blue'] valueY = 480 - (self.attempts - 1) * 50 self.raadFrame = Frame(self.mastermindFrame, bg='black', highlightbackground='white', highlightthickness=3) self.raadFrame.place(x=0, y=valueY, height=50, width=450) self.guessingButton1 = Button(self.raadFrame, text='[X]', command = lambda: mastermind.colourguess(self, 1), bg='black', fg='white', font=('ariel', 12, 'bold'), width=10, borderwidth = 0) self.guessingButton1.place(x=30, y=10) self.guessingButton2 = Button(self.raadFrame, text='[X]', command=lambda: mastermind.colourguess(self, 2), bg='black', fg='white', font=('ariel', 12, 'bold'), width=10, borderwidth = 0) self.guessingButton2.place(x=130, y=10) self.guessingButton3 = Button(self.raadFrame, text='[X]', command=lambda: mastermind.colourguess(self, 3), bg='black', fg='white', font=('ariel', 12, 'bold'), width=10, borderwidth = 0) self.guessingButton3.place(x=230, y=10) self.guessingButton4 = Button(self.raadFrame, text='[X]', command=lambda: mastermind.colourguess(self, 4), bg='black', fg='white', font=('ariel', 12, 'bold'), width=10, borderwidth = 0) self.guessingButton4.place(x=330, y=10) # buttons voor het handmatig raden def colourguess(self, guess): if guess == 1: self.guessingButton1.config(text = self.colours1[0], fg = self.colours1[0]) self.selectedcolour1 = self.colours1[0] self.colours1.append(self.colours1[0]) self.colours1.pop(0) elif guess == 2: self.guessingButton2.config(text=self.colours2[0], fg=self.colours2[0]) self.selectedcolour2 = self.colours2[0] self.colours2.append(self.colours2[0]) self.colours2.pop(0) elif guess == 3: self.guessingButton3.config(text=self.colours3[0], fg=self.colours3[0]) self.selectedcolour3 = self.colours3[0] self.colours3.append(self.colours3[0]) self.colours3.pop(0) elif guess == 4: self.guessingButton4.config(text = self.colours4[0], fg = self.colours4[0]) self.selectedcolour4 = self.colours4[0] self.colours4.append(self.colours4[0]) self.colours4.pop(0) # controle of de door de persoon opgegeven antwoorden kloppen def checkAwnsers(self): colours = ['red', 'pink', 'yellow', 'green', 'orange', 'blue'] self.wrongplacecolours = [] self.almost = 0 self.rightplace = 0 print(self.colourcode) valueY = 480 - (self.attempts - 1) * 50 scorevak = Frame(self.mastermindFrame, bg='black', highlightbackground='green', highlightthickness=1.5) scorevak.place(x=500, y=valueY, height=50, width=50) try: self.selectedcolour1 if self.selectedcolour1 in self.colourcode: if self.selectedcolour1 == self.colourcode[0]: if self.colourcode.count(self.selectedcolour1) == 1: self.wrongplacecolours.append(self.selectedcolour1) self.correct += 1 self.rightplace += 1 self.score1 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score1.place(x=26, y=26) elif self.colourcode.count(self.selectedcolour1) > 1: self.correct += 1 self.rightplace += 1 self.score1 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score1.place(x=26, y=26) else: if self.selectedcolour1 not in self.wrongplacecolours: self.wrongplacecolours.append(self.selectedcolour1) self.wrongplace += 1 self.almost += 1 self.wrongscore1 = Label(scorevak, text='X', bg='white', fg='white', font=('ariel', 8, 'bold'), width=2) self.wrongscore1.place(x=26, y=26) except: print('hi') try: if self.selectedcolour2 in self.colourcode: if self.selectedcolour2 == self.colourcode[1]: if self.colourcode.count(self.selectedcolour2) == 1: self.wrongplacecolours.append(self.selectedcolour2) self.correct += 1 self.rightplace +=1 self.score2 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score2.place(x=0, y=0) elif self.colourcode.count(self.selectedcolour2) > 1: self.correct += 1 self.rightplace += 1 self.score2 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score2.place(x=0, y=0) else: if self.selectedcolour2 not in self.wrongplacecolours: self.wrongplacecolours.append(self.selectedcolour2) self.wrongplace += 1 self.almost += 1 self.wrongscore2 = Label(scorevak, text='X', bg='white', fg='white', font=('ariel', 8, 'bold'), width=2) self.wrongscore2.place(x=0, y=0) except: print('hi') try: if self.selectedcolour3 in self.colourcode: if self.selectedcolour3 == self.colourcode[2]: if self.colourcode.count(self.selectedcolour3) == 1: self.wrongplacecolours.append(self.selectedcolour3) self.correct += 1 self.rightplace += 1 self.score3 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score3.place(x=0, y=26) elif self.colourcode.count(self.selectedcolour3) > 1: self.correct += 1 self.rightplace += 1 self.score3 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score3.place(x=0, y=26) else: if self.selectedcolour3 not in self.wrongplacecolours: self.wrongplacecolours.append(self.selectedcolour3) self.wrongplace += 1 self.almost += 1 self.wrongscore3 = Label(scorevak, text='X', bg='white', fg='white', font=('ariel', 8, 'bold'), width=2) self.wrongscore3.place(x=0, y=26) except: print('hi') try: if self.selectedcolour4 in self.colourcode: if self.selectedcolour4 == self.colourcode[3]: if self.colourcode.count(self.selectedcolour4) == 1: self.wrongplacecolours.append(self.selectedcolour4) self.correct += 1 self.rightplace += 1 self.score4 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score4.place(x=26, y=0) elif self.colourcode.count(self.selectedcolour4) > 1: self.correct += 1 self.rightplace += 1 self.score4 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score4.place(x=26, y=0) else: if self.selectedcolour4 not in self.wrongplacecolours: self.wrongplacecolours.append(self.selectedcolour4) self.wrongplace += 1 self.almost += 1 self.wrongscore4 = Label(scorevak, text='X', bg='white', fg='white', font=('ariel', 8, 'bold'), width=2) self.wrongscore4.place(x=26, y=0) except: print('hi') if self.correct == 4: mastermind.Finish(self) # als de speler de code goed heeft ingeleverd krijgt de speler dit te zien def Finish(self): self.gefeliciteerdFrame = Frame(self.gameFrame, bg = 'green') self.gefeliciteerdFrame.place(y = 70, x = 100, height = 450, width= 200) self.gefeliciteerdLabel = Label(self.gefeliciteerdFrame, bg = 'green', fg = 'red', text = 'Gefeliciteerd!\n U heeft gewonnen', font=('ariel', 16, 'bold')) self.gefeliciteerdLabel.place(y = 0, x = 0) self.afsluitButton = Button(self.gefeliciteerdFrame, command = lambda: mastermind.Afsluiten(self) ,text = 'Afsluiten', bg = 'pink', fg = 'blue', font=('ariel', 8, 'bold')) self.afsluitButton.place(y = 150, x = 60) def Afsluiten(self): self.parent.destroy()
de7a7afd0629331f2a13b7d06c64184f0d05d232
SummitStudiosDev/ViTasl
/src/functions/cosine_similarity.py
2,000
3.890625
4
#----------------------------------------------------------------------------------------------------------- #| credit: https://stackoverflow.com/questions/15173225/calculate-cosine-similarity-given-2-sentence-strings| #------------------------------------------------------------------------------------------------------------ def cosine(text1, text2): import math import re from collections import Counter WORD = re.compile(r"\w+") def get_cosine(vec1, vec2): intersection = set(vec1.keys()) & set(vec2.keys()) numerator = sum([vec1[x] * vec2[x] for x in intersection]) sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())]) sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())]) denominator = math.sqrt(sum1) * math.sqrt(sum2) if not denominator: return 0.0 else: return float(numerator) / denominator def text_to_vector(text): words = WORD.findall(text) return Counter(words) #text1 = "This is a foo bar sentence ." #text2 = "This sentence is similar to a foo bar sentence ." vector1 = text_to_vector(text1) vector2 = text_to_vector(text2) cosine = get_cosine(vector1, vector2) return cosine #print("Cosine:", cosine) def maxcosine(data): maxcosine = '-1.000' maxlink = '' maxdef = '' for x, y in data.items(): definition = x yraw = y.split(',') cosine= (yraw[1]) link = (yraw[0]) #print(definition," : ", link, " : ",cosine) if(float(cosine) > float(maxcosine)): maxcosine = cosine maxlink = link maxdef = definition #print("max: ",maxdef," : ", maxlink, " : ",maxcosine) num = 1; for x,y in data.items(): if(num == 1): firstlink = (y.split(','))[0] if(num != 1): link = (y.split(','))[0] if(link == firstlink): pass else: #print("look at max, not all links are the same") return maxlink num += 1 #print("all links r the same") #print(firstlink) return firstlink
eff4bd0d96ebe0cfea660477e3b85d66707897de
pradeep-528/pradeep
/slicing.py
223
3.9375
4
#!/usr/bin/python # slicing l = [1,2,3,4,5,6,7] print l print "lst element:",l[0] print "last elemen:",l[-1] print "1 to 3:",l[0:3] print "reverse:",l[::-1] s='pradeep' print s print "reverse of a string:",s[::-1]
a2c5cf65609ee90148d49c6f4e9110e0a3ca571c
sowmiyaa12/sowmiyapgm
/24.py
163
3.703125
4
def sortir(arr,n): for i in range(n): arr[i]=i+1 if__name__=='__main__'; arr=[10,2,3,45,6,7,89,90] n=len(arr) sortit(arr,n) for i in range(n) print(arr[i],end='')
0382214adba37ec79ad5938799b0615995e37f6f
lazyxu/pythonvm
/tests/op_overload4.py
319
3.640625
4
class A(object): def __getitem__(self, key): if key == "hello": return "hi" elif key == "how are you": return "fine" def __setitem__(self, key, value): print self print key print value a = A() print a["hello"] print a["how are you"] a["one"] = 1
fb3428d23ac0eeb82c786961ff5b2d52f29dabbe
JoseAVallejo12/holbertonschool-web_back_end
/0x00-python_variable_annotations/1-concat.py
268
4.25
4
#!/usr/bin/env python3 """Write a function concat two string""" def concat(str1: str, str2: str) -> str: """Return a plus b Args: str1 (str): number one str2 (str): number two Returns: str: return """ return str1 + str2
c2bd8806a004a039c49b90a3e2b7c10c712bc92a
realpython/materials
/binary-search/search/random.py
972
4.09375
4
""" The random search algorithm. """ import random from typing import Optional, Set, Sequence from search import T, S, Key, identity def find_index( elements: Sequence[T], value: S, key: Key = identity ) -> Optional[int]: """Return the index of value in elements or None.""" visited: Set[int] = set() while len(visited) < len(elements): random_index = random.randint(0, len(elements) - 1) visited.add(random_index) if key(elements[random_index]) == value: return random_index return None def find(elements: Sequence[T], value: S, key: Key = identity) -> Optional[T]: """Return an element with matching key or None.""" index = find_index(elements, value, key) return None if index is None else elements[index] def contains(elements: Sequence[T], value: S, key: Key = identity) -> bool: """Return True if value is present in elements.""" return find_index(elements, value, key) is not None
f88899e8b0a9a67c803a2dd610e746433a8916e6
ramumenon/olympics-data-analysis
/code.py
2,892
3.734375
4
# -------------- #Importing header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #Path of the file is stored in the variable path #Code starts here # Data Loading data = pd.read_csv(path) data.rename(columns = {'Total': 'Total_Medals'}, inplace = True) data.head(10) data.tail(10) data.drop(index = 146, axis = 0, inplace = True) # Summer or Winter data["Better_Event"] = np.where(data['Total_Summer'] >= data['Total_Winter'], 'Summer', np.where(data["Total_Summer"] < data['Total_Winter'], 'Winter', 'Both')) #remove last row wchich is a table total # Top 10 better_event = data.Better_Event.value_counts().nlargest(1).index[0] # Plotting top 10 def top_ten (df, col) : return df.nlargest(10, col)['Country_Name'].tolist() # Top Performing Countries top_10_summer = top_ten(data, 'Total_Summer') top_10_winter = top_ten(data, 'Total_Winter') top_10 = top_ten(data, 'Total_Medals') # Best in the world common = list(set(top_10).intersection(top_10_summer, top_10_winter)) print(common) summer_df = data[data.Country_Name.isin (top_10_summer)] winter_df = data[data.Country_Name.isin (top_10_winter)] top_df =data[data.Country_Name.isin (top_10)] # Plotting the best def plot_medals (df, season, colour) : plt.figure (figsize = (15,10)) plt.barh('Country_Name', 'Total_Medals', data = df.sort_values('Total_Medals', ascending = True) , color = colour, edgecolor = 'k' ,linewidth = 1) plt.title ('Top 10 ' + season + ' games medal Tally') plt.xlabel ('Country') plt.ylabel('Number of Medals') plt.show() plot_medals (summer_df, 'Summer', 'r') plot_medals (winter_df, 'Winter', 'b') plot_medals (top_df, 'Overall', 'y') summer_df["Golden_Ratio"] = summer_df['Gold_Summer']/summer_df['Total_Summer'] summer_country_gold, summer_max_ratio = (summer_df.loc[summer_df.Golden_Ratio == max(summer_df.Golden_Ratio)]).iloc[0][['Country_Name','Golden_Ratio']] winter_df["Golden_Ratio"] = winter_df['Gold_Winter']/winter_df['Total_Winter'] winter_country_gold, winter_max_ratio = (winter_df.loc[winter_df.Golden_Ratio == max(winter_df.Golden_Ratio)]).iloc[0][['Country_Name','Golden_Ratio']] top_df["Golden_Ratio"] = top_df['Gold_Total']/top_df['Total_Medals'] top_country_gold, top_max_ratio = (top_df.loc[top_df.Golden_Ratio == max(top_df.Golden_Ratio)]).iloc[0][['Country_Name','Golden_Ratio']] data1 = data.copy() data1['Total_Points'] = (data1['Gold_Total'] * 3 + data1['Silver_Total'] * 2 + data1['Bronze_Total']) most_points, best_country = (data1.loc[data1.Total_Points == max(data1.Total_Points)]).iloc[0][['Total_Points', 'Country_Name']] best = data.loc[data['Country_Name'] == best_country][['Gold_Total','Silver_Total','Bronze_Total']] best.plot.bar(stacked = True, figsize = (15,10)) plt.xlabel (best_country) plt.ylabel ('Medal Tally - Stacked') plt.xticks (rotation = 45) plt.show()
6a47c8db7ff3f3f349d6a8be5fe5dc5166d561a6
yoontaepark/python
/3.1.py
167
4.03125
4
hrs = input("Enter Hours:") h = float(hrs) rate = input("Enter the Rate:") r = float(rate) if h <= 40: print( h * x) elif h > 40: print(40* r + (h-40)*1.5*r)
74ee28c7e2e36ea03cddb4c6df591cfaadc37332
piotrbrendan/Exercises-python
/bubble_sort.py
368
3.75
4
def bub_sort(l1): for i in range(len(l1)-1): ifChanged = False for j in range(len(l1)-1-i): if l1[j] > l1[j+1]: l1[j], l1[j+1] = l1[j+1], l1[j] ifChanged = True if ifChanged == False: break return l1 if __name__=='__main__': l1=[1,4,3,10,2,5,0,7] print(bub_sort(l1))
086a7bf2683529b366788aa8ef04f150d3153464
The-AFK-JFK/Rabbit-Multiplication
/rabbits.py
348
3.515625
4
def rabbits(r): if r<0: raise RabbitOutOfRangeError if r<5: return[1,1,2,3,5][r] else: return rabbits(r-1) + rabbits(r-2) - rabbits(r-5) class RabbitOutOfRangeError(ValueError): pass #s = "" #for i in range(1,20): # s = s + str(rabbits(i)) + " " #print(s) #>>> 1 1 2 3 5 7 11 16 24 35 5
4da5666a73a64bfd7123b8af0821c75bb7100a90
pforciol/AirBnB_clone
/models/place.py
1,040
3.625
4
#!/usr/bin/python3 """This is the Place Model module. Contains the Place class that inherits from BaseModel. """ from models.base_model import BaseModel class Place(BaseModel): """This class defines an Place. Attributes: city_id (str): the place's city id. user_id (str): the place's user id. name (str): the place's name. description (str): the place's description. number_rooms (int): the place's number of rooms. number_bathrooms (int): the place's number of bathrooms. max_guest (int): the place's maximum number of guests. price_by_night (int): the place's price by night. latitude (float): the place's latitude. longitude (float): the place's longitude. amenity_ids (list): the place's list of amenities ids. """ city_id = "" user_id = "" name = "" description = "" number_rooms = 0 number_bathrooms = 0 max_guest = 0 price_by_night = 0 latitude = 0.0 longitude = 0.0 amenity_ids = []
91c31190369f9043317b8bddc62beca693f8f740
SnehalThakur/PythonTutorial
/Comprehensions/Comprehension_Dictionary.py
527
4.40625
4
# Dictionary Comprehension # Create a dictionary of State and Capital state = ["Maharashtra", "MP", "Rajastan"] capital = ["Mumbai", "Bhopal", "Jaipur"] dict1 = zip(state, capital) stateCapitalDict = {} for (key, value) in dict1: stateCapitalDict[key] = value print("stateCapitalDict =>", stateCapitalDict) print("=================================") # Using Dictionary Comprehension stateCapitalDict1 = {key : value for (key, value) in zip(state, capital)} print("stateCapitalDict1 =>", stateCapitalDict1)
25dd17b81b919c5d3733287c6e0005883cc7ddf9
mathsprog/basics
/calculator.py
2,703
4.09375
4
# مشروع لتنفيذ وادخال عددين كليين وإجراء العمليات الحسابية عليهما # الخوارزمية تخص الاعداد الكلية فقط حالياً # يمكن تطوير المشروع بتعديل الخوارزمية وتطويرها لتشمل كل صيغ الاعداد الممكنة def calc(x, y): # تعريف الدالة print(':', 'النتيجة ') print(x, '+', y, '=', x + y) # ناتج الجمع print(x, '-', y, '=', x - y) # ناتج الطرح print(x, '*', y, '=', x * y) # ناتج الضرب # -----ناتج القسمة-------- if y !=0 : print(x, '/', y, '=', x / y) else : print('القسمة على صفر كمية غير معرفة') # -------نهاية القسمة------ print("مربع العدد",x,'=',x**2)#الاسس او القوى نستخدم دائماً نجمتين للتعبير عنها print("الجذر التربيعي للعدد",y, '=', round(y ** 0.5,3))#تم استخدام دالة round لتقريب العدد الناتج لأقرب جزء من ألف def enter_number_and_check(x):#دالة ادخال العددين وتحمل قيمة الأول أو الثاني اشارة الى ترتيب العدد number=0 ok=False wrong=False while not ok: #يستمر loop حتى يدخل المستخدم عدد صحيحاً if not wrong: print('ادخل العدد', x) # نطلب من المستخدم ادخال اول عدد else: print('اعد ادخال العدد',x,'بشكل صحيح') try: number=int(input('')) # يدخل المستخدم العدد الأول ok = True #عندما يدخل المستخدم عدد تتحول القيمة هنا لtrue وبذلك ينتهي ال loop except ValueError: wrong=True # عند الفيمة true تظهر للمستخدم رسالة اعادة ادخال العدد continue # استمرار ال loop حتى يتم تصحيح ادخال المستخدم لعدد صحيح return number # قمة ارجاع الدالة وهي العدد المدخل بشكل صحيح print('----Start App-----') # للإعلان عن بداية تنفذ الكود x=enter_number_and_check("الأول") #ادخال العدد الأول والتحقق منه y=enter_number_and_check("الثاني")#ادخال العدد الثاني والتحقق منه calc(x,y)#بعد نجاح تنفيذ السطرين السابقين يتم تنفيذ دالة العمليات الحسابية print('---- End App -----') # للإعلان عن الانتهاء من تنفيذ الكود
1a5ad4c51f692b14779d060f7996f25f2690106b
midhunraaj008/Simple-Python-Programs
/number triangle pattern.py
289
3.8125
4
n=int(input("Enter no of Rows : ")) for i in range (1,n+1): k=i while(n-k)!=0: print(end=' ') k=k+1 for j in range (1,(2*i)): if(j<=i): print(i+j-1,end=' ') if(j>i): print((j-i+1),end=' ') print("\n")
43d5d0d4910e3875cacf221759362830f08d811c
grahamhoyes/utek-programming-team15
/solution/Part1.py
2,603
3.8125
4
## Part 1. Simple, Block, and Permutation Encryption/Decryption ## ##Part 1A def SimpleEncrypt(k, message): ciphertext = '' #Ensure message is all uppercase letters, should be redundant message = message.upper() for i in range(0, len(message)): #Converts letter into unicode char = ord(message[i]) #Capital letters are from 65 to 90 if char < 65 or char > 90: #Ignore if not capital letter ciphertext = ciphertext + chr(char) continue #setting A --> 0 for mod purposes #A -> 0, B -> 1, etc.. char = char - 65 char = (char + k)%26 char = char + 65 ciphertext = ciphertext + chr(char) return ciphertext def SimpleDecrypt(k, ciphertext): #Reverse operation of the SimpleEncript return SimpleEncrypt(-k, ciphertext) ##Part 1B def BlockEncrypt(k, text): ciphertext = '' count = 0 #Work through each character of the text for n in range(len(text)): #Skip if there is a space (no need to encrypt space) if ord(text[n]) < 65 or ord(text[n]) > 90: ciphertext += text[n] #Use simple step encryption to encrypt each individual alphabetic character else: simpK = k[count%len(k)] ciphertext += SimpleEncrypt(simpK, text[n]) count += 1 return ciphertext def BlockDecrypt(k, text): #Reverse the operation of BlockEncrypt for n in range(len(k)): k[n] = -k[n] return BlockEncrypt(k, text) ##Part 1C def PermutationEncrypt(permutation, message): dict = {} ciphertext = '' #Create a dictionary with #A->permutation[0] #B->permutation[1] #etc... for i in range(0, len(permutation)): dict.update({chr(65 + i):permutation[i]}) for i in range(0, len(message)): char = message[i] char = dict.get(char, char) ciphertext = ciphertext + char return ciphertext def PermutationDecrypt(permutation, ciphertext): dict = {} message = '' #Create a dictionary with #permutation[0]-> A #permutation[1]-> B #etc... #reverse of above for i in range(0, len(permutation)): dict.update({permutation[i]:chr(65 + i)}) for i in range(0, len(ciphertext)): char = ciphertext[i] char = dict.get(char, char) message = message + char return message
8698f9976d2040b81abbc43a52f4e53e1e37c28b
DorcasWanjiku/news-20-20
/test/test_article.py
1,115
3.625
4
import unittest from app.models import Article class TestArticle(unittest.TestCase): """ Test Class to test the behaviour of the Movie class """ def setUp(self): """ Set up method that will run before every Test """ self.new_article = Article("Ally", "Random Title", "Short","random.com","random.jpg","12/12/12", "None") def test_instance(self): """ Tests if instance of the Article class """ self.assertTrue(isinstance(self.new_article,Article)) def test_init(self): """ Tests for proper instantiation """ self.assertEqual(self.new_article.author, "Ally") self.assertEqual(self.new_article.title, "Random Title") self.assertEqual(self.new_article.description, "Short") self.assertEqual(self.new_article.url, "random.com") self.assertEqual(self.new_article.img, "random.jpg") self.assertEqual(self.new_article.date, "12/12/12") self.assertEqual(self.new_article.content, "None") if __name__ == "__main__": unittest.main()
9d599fb3b5e47eac3aa8c95a591d574ba373bcb0
trex013/python-programs
/tkinter2.py
455
3.765625
4
import tkinter def open_file(): "this creates a new file" file1 = open("file1.txt","a") file1.write("happy") file1.close return window = tkinter.Tk() button = tkinter.Button(window, text = "One Love", command = open_file) canvas = tkinter.Canvas(window, height=200, width=250) coord = 5,5,150,150 arc = canvas.create_arc(coord,start = 30,extent = 300 ,fill = "black") canvas.pack() button.pack() window.mainloop()
e9f7aef37c6133ff7bce936a80f058f383c4401d
paetztm/python-playground
/python-next-level/uniquelist.py
353
3.796875
4
class UniqueList: def __init__(self, items): self.items = [] for item in items: self.append(item) def append(self, item): if item not in self.items: self.items.append(item) def __getitem__(self, index): return self.items[index] u = UniqueList([3, 7, 2, 9, 3, 4, 2]) print(u[2: 4])
f9b5ec4c86b979d1c6895fe81c59d5ac869ee8e1
mlburgos/concept-practice
/code_challanges/interview_cake/number_11.py
2,411
3.640625
4
# given a url, store it in a trie # {d: {o: {n: {u: { t: {} # } # }, # g: {o: {} # .: {c: {o: {m: [*, {/: *}]}} # o: {r: {g: *}} # } # } # } # } # } # url_storage = {} # def store_string(string): # # find the starting point # current_dict = url_storage # for i, letter in enumerate(string): # if letter in current_dict: # current_dict = current_dict[letter] # i = 0 # while True: # letter = string[i] # if letter in current_dict: # i += 1 # continue # break # current_dict # _store_string(string, url_storage) # def _store_string(remaining_str, current_dict): # if len(remaining_str) == 1: # return {current_dict[remaining_str[0]]: '*'} ################################################################################ # my version class Trie_mb(object): def __init__(self): self.root_dict = {} def check_and_add(self, word): current_dict = self.root_dict for char in word: # if char not in current_dict # current_dict[char] = {} # current_dict = current_dict[char] current_dict[char] = current_dict.get(char, {}) current_dict = current_dict[char] current_dict['End of word'] = current_dict.get('End of word', {}) ################################################################################ # Parker's version class Trie: def __init__(self): self.root_node = {} def check_present_and_add(self, word): current_node = self.root_node is_new_word = False # Work downwards through the trie, adding nodes # as needed, and keeping track of whether we add # any nodes. for char in word: if char not in current_node: is_new_word = True current_node[char] = {} current_node = current_node[char] # Explicitly mark the end of a word. # Otherwise, we might say a word is # present if it is a prefix of a different, # longer word that was added earlier. if "End Of Word" not in current_node: is_new_word = True current_node["End Of Word"] = {} return is_new_word
d2cfad800e86ee88089323c6dbddc4baf6184ba1
udayt-7/Python-Assignments
/Assignment_3_Python/a3p13.py
375
4.15625
4
#Write a function unique to find all the unique elements of a list. def unique(l1): l3 =[] for i in range(len(l1)): if l1[i] not in l1[i+1:] and l1[i] not in l1[:i] and l1[i] not in l3: l3.append(l1[i]) print(l3) a = int(input("enter the range of list 1: ")) l1 = [] for ch in range(a): a2 = int(input("enter the list 1: ")) l1.append(a2) unique(l1)
cf56dbb84f9759397f3e320090eb1d8e080a6413
sunkanggao/Algorithm
/course/03_DivisionAndRecursion/towerOfHanoi.py
1,638
4.09375
4
# -*- coding:utf-8 -*- """ n个盘子看做前n-1个盘子和最后一个盘子组成。 将前n-1个盘子移动到aux柱上: 2^(n-1)-1 将最大的盘子移动到t柱上: 1 将前n-1个盘子移动到t柱上: 2^(n-1)-1 """ def moveOne(f, t): print f, '->', t def move(f, t, aux, n): """ :param f: 起始柱 :param t: 目标柱 :param aux: 辅助柱 :param n: 汉诺塔层数 :return: """ if n == 1: moveOne(f, t) return move(f, aux, t, n - 1) moveOne(f, t) move(aux, t, f, n - 1) def calc(s, size, f, t, aux): """ 给定从小到大的n个盘子,它们散乱的位于A、B、C柱上, 问这一状态是否是将这n个盘子从A借助B移动到C的必经状态? 如果是,返回是第几个状态,如果不是,返回-1。 :param s: 盘子状态序列 :param size: 当前盘子状态序列长度 :param f: 起始柱 :param t: 目标柱 :param aux: 辅助柱 :return: 状态的序号 """ if size == 0: return 0 # 情况一:最大盘子位于辅助柱,为不可能情况 if s[size - 1] == aux: return -1 # 情况二:最大盘子位于目标柱,返回2^(n-1)-1+1+n if s[size - 1] == t: n = calc(s, size - 1, aux, t, f) if n == -1: return -1 return 1 << (size - 1) + n # 情况三:最大盘子位于起始柱,返回n return calc(s, size - 1, f, aux, t) if __name__ == '__main__': n = 3 move('A', 'C', 'B', n) s = 'ABC' print calc(s, 3, 'A', 'C', 'B') s = 'AAC' print calc(s, 3, 'A', 'C', 'B')
01704fe2329b27984f585fef90bfcd03fc60b7e5
chenxuhl/Leetcode
/腾讯精选50题/41Reverse_Integer/reverse.py
1,560
3.625
4
#7.整数反转 """ 题目描述: 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 示例1: 输入: 123 输出: 321 示例2: 输入: -123 输出: -321 示例3: 输入: 120 输出: 21 """ #解题思路 """ 这题的关键在于取值范围:-2147483648~2147483647,如:2147483647 反转后:7463847412超出取值范围 注意: python取余时:print(-123%10), 输出为7 分析:-123%10 = -123 - 10 * (-123 // 10) = -123 - 10 * (-13) = 7, 取余时会向下取整 """ #python #- * - coding: utf-8 - * - #Author:JoeyChen """ 执行时间:16ms,战胜97.54%python提交记录 内存消耗:11.8MB, """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ res = 0 if x >= 0: #由于x为负数时python取余数值不好操作,故正负分离操作 while x != 0: if res > 214748364: #由于x取值的限制,翻转之后的res最后一位只能是1或2 return 0 #所以res只能是2147483641 或 2147483642而它们对应的x res = res * 10 + x % 10 #为1463847412 和 2463847412(超出数值范围) x //= 10 #res等于214748364时,x只能为1463847412 return res else: x = abs(x) while x != 0: if res > 214748364: return 0 res = res * 10 + x % 10 x /= 10 return -res
534d2e042e1f9e22effeb5720c2cb5ac411122b3
BingKui/PythonLearn
/笨办法学Python/37.复习各种符号.py
2,072
3.625
4
# 复习 python 关键字和各种符号 # 关键字 # and # del # form # not # while # as # elif # global # or # with # assert # else # if # pass # yield # break # except # import # print # class # exec # in # raise # continue # finally # is # return # def # for # lambda # try # 数据类型 # True # False # None # strings # numbers # floats # lists # 字符串转移序列 # \\ ===> \ # \' ===> ' # \" ===> " # \a ===> 响铃 # \b ===> 退格 # \f ===> 换页 # \n ===> 换行 # \r ===> 回车 # \t ===> 水平制表符 # \v ===> 垂直制表符 # 字符串格式化 # %d ===> 有符号整数(十进制) # %i ===> 十进制整数 # %o ===> 无符号整数(八进制) # %u ===> 无符号整数(十进制) # %x ===> 无符号整数(十六进制) # %X ===> 无符号整数(十六进制大写字符) # %e ===> 浮点数字(科学计数法) # %E ===> 浮点数字(科学计数法,用E代替e) # %g ===> 浮点数字(根据值得大小采用%e或%f) # %G ===> 浮点数字(类似于%g) # %c ===> 字符及其ASCII码 # %f ===> 浮点数字 # %F ===> 浮点数字(类似于%f) # %r ===> 原格式输出 # %s ===> 字符串 # %% ===> 百分号标记 # 操作符号 # + --> 加 # - --> 减 # * --> 乘 # ** --> 幂 # / --> 除 # // --> 取整除 # % --> 取余 # < --> 小于 # > --> 大于 # <= --> 小于等于 # >= --> 大于等于 # == --> 等于 # != --> 不等于 # <> --> 不等于 # ( ) --> 小括号,元组 # [ ] --> 中括号,列表 # { } --> 大括号,字典 # @ --> 函数修饰符 # , --> 分割前后两部分 # : --> 函数、代码块后的语法,不可缺少 # . --> 子集运算符 # = --> 简单赋值运算符 # ; --> 语句结尾 可有 可无 # += --> 加法赋值 # -= --> 减法赋值 # /= --> 除法赋值 # //= --> 取整除赋值 # %= --> 取余赋值 # **= --> 幂赋值 # & --> 按位与运算符 # | --> 按位或运算符 # ^ --> 按位异或运算符 # ~ --> 取反运算符 # >> --> 左移动运算符 # << --> 右移动运算符
dcc2319be5462984b25a24bcaad916dd4936f4d8
loki04/picire
/picire/config_splitters.py
1,529
3.921875
4
# Copyright (c) 2016-2019 Renata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. def zeller(config, n): """ Splits up the input config into n pieces as used by Zeller in the original reference implementation. The approach works iteratively in n steps, first slicing off a chunk sized 1/n-th of the original config, then slicing off 1/(n-1)-th of the remainder, and so on, until the last piece is halved (always using integers division). :param config: The configuration to split. :param n: The number of sets the configuration will be split up to. :return: List of the split sets. """ subsets = [] start = 0 for i in range(n): subset = config[start:start + (len(config) - start) // (n - i)] subsets.append(subset) start += len(subset) return subsets def balanced(config, n): """ Slightly different version of Zeller's split. This version keeps the split balanced by distributing the residuals of the integer division among all chunks. This way, the size of the chunks in the resulting split is not monotonous. :param config: The configuration to split. :param n: The number of sets the configuration will be split up to. :return: List of the split sets. """ return [config[len(config) * i // n: len(config) * (i + 1) // n] for i in range(n)]
ae1627f80edbb81b683a235087aa0bf2522c928f
IvanSivchev/Homeworks
/guess number.py
866
3.59375
4
import random mistakes_allowed = 5 def rand_number(): return random.randint(1,10) def usr_input(): return input('Please, input your number between 1 and 10: ') def check(end,random, number): if number == random: print('You win!') return True else: print('Wrong number!') return False def game_over(end, mistakes_counter, mistakes_allowed): if end == 1: return True if mistakes_counter >= mistakes_allowed: print('You lose!') return True else: return False def GAME(): mistakes_counter = 0 random = rand_number() end = 0 while not game_over(end, mistakes_counter, mistakes_allowed): number = int(usr_input()) chk = check(end, random, number) if not chk: mistakes_counter +=1 else: end += 1 GAME()
2fa2542be0f35c2629159f3741b06c0c1a89677f
SumitVashist/100patterns
/89.py
659
3.765625
4
""" Enter a number : 10 * *** ***** ******* ********* *********** ************* *************** ***************** ******************* ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** """ n = int(input("Enter a number : ")) for i in range(n): for j in range(i + 1, n): print(' ', end = '') for j in range(0, 2 * i + 1): print('*', end = '') print() for i in range(n//2): for j in range(n//2): print('*', end = '') for j in range(2 * n - 2 *(n//2) -1): print(' ', end = '') for j in range(n//2): print('*', end = '') print()
2e6fef5da58d64a7520c2775579c51d49eb758ec
daniel-reich/ubiquitous-fiesta
/sfqudQHQ3HPpd7dZb_12.py
481
3.78125
4
def rps(p1, p2): if p1 == p2: return "It's a draw" elif p1 == "Rock": if p2 == "Paper": winner = "p2" else: winner = "p1" ​ elif p1 == "Paper": if p2 == "Scissors": winner = "p2" else: winner = "p1" ​ elif p1 == "Scissors": if p2 == "Rock": winner = "p2" else: winner = "p1" return "The winner is " + winner
69a454d98aac943e44e3888036b0149b58762434
aryakk04/python-training
/functions/sum.py
980
4.6875
5
def sum_arguments (arg1,arg2): """ Prints the sum of passed two argument Two arguments should be either integer or string data type. If both arguments are either integer or string return the sum of the arguments else return -1. Args: input1: Argument 1 sould be either integer or string. input2: Argument 2 should be either integer or string. Two arguments should be either string or integer data type. Returns: If two arguments are either integer or string return value is sum of two arguments else return value is -1. """ if (type(arg1) != type(arg2)): # Since types of arguments are not same return -1 else: sumarg = arg1+arg2 return sumarg input1 = input("Enter input1 : ") input2 = input("Enter input2 : ") return_val = sum_arguments (input1, input2) # Function calling to find the sum of arguments if (return_val == -1) : print ("Both inputs should have the same data type") else: print "sum of two argument", return_val
17f86a15b06eda94d807d89764b9e793a570b57d
amruta2007/Python
/sum_items.py
173
3.734375
4
''' Created on Apr 23, 2019 @author: facebook ''' s=0 l = [1,2,3,4] for i in range(0, len(l)): s= s + l[i] print("Sum of all elements in given list: ", s)
da0d36022bda38456bf0c8784c6b3d597cd5436a
LuyandaGitHub/intro_python
/Week_8/acronym/acro.py
670
4.34375
4
def get_acronym() : # SO WE GET THE USERS INPUT BUT ALSO GET RID OF THE COMMA ignore_list = input('Please input the words to ignore, separated by a comma(the, for, and)\n').lower().replace(' ', '').split(',') title_list = input('Enter a title to generate its acronym').split() result = '' # FIRST, WE LOOP THROUGH THE title_list TO ACCESS EACH word INSIDE for word in title_list: # IF THE word ISN'T IN THE ignore_list, THEN... if word not in ignore_list: # WE CAPITALISE THE FIRST LETTER AND ADD IT TO THE result STRING result = result + word[0].upper() print(result) get_acronym()
3fe14d6eeaecb80c200da0eb33862a4380b67206
KushagrJ/PY-00
/27 (#)/27.py
637
3.90625
4
# -*- coding: utf-8 -*- # Python 3.8.6 m = int(input()) n = int(input()) if m > n: a = n else: a = m # To make a the greatest common divisor of m and n. while m%a != 0 or n%a != 0: a = a-1 print(a) # /* Trivia - 27.py # # * In general, a+=b is the same as a = a+b (for numbers, immutable # sequences, etc.). But, for lists (a mutable sequence), a+=b is not the # same as a = a+b. # [Similarly for -, *, /, //, **, %, etc. for numerical data types] # * For numerical data types, a//b is similar to floor of a/b. # * For numerical data types, a**b means a raised to the power of b. # # * End of Trivia */
358bc95e1531dba2af189301ab35f3a448912419
SuperMartinYang/learning_algorithm
/leetcode/hard/word_search2.py
1,713
3.53125
4
class Solution(object): def findWords(self, board, words): """ :type board: List[List[str]] :type words: List[str] :rtype: List[str] """ if not board or not words: return [] m = len(board) n = len(board[0]) used = [[False for _ in range(n)] for _ in range(m)] res = [] words = set(words) # form trie root = {} for word in words: cur = root for ch in word: if ch not in cur: cur[ch] = {} cur = cur[ch] cur['#'] = '#' def dfs(i, j, word, node, path): if '#' in node: res.append(word) words.remove(word) cur = node del cur['#'] if not cur: while path and not cur: cur, curl = path.pop() del cur[curl] return if not words: return used[i][j] = True for x, y in ((i + 1, j), (i, j + 1), (i - 1, j), (i, j - 1)): if -1 < x < m and -1 < y < n and not used[x][y] and board[x][y] in node: dfs(x, y, word + board[x][y], node[board[x][y]], path + [[node, board[x][y]]]) used[i][j] = False for i in range(m): for j in range(n): if board[i][j] in root: dfs(i, j, board[i][j], root[board[i][j]], [[root, board[i][j]]]) return res Solution().findWords([["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], ["oath","pea","eat","rain"])
2f6313114fc992e867a6117f32c9cc6cdc643d85
Cisco89/get_country_code
/get_country_code.py
852
3.578125
4
def get_country_codes(prices): #for each comma sep value make a list #for each remove the comma #for each separate by "$" symbol #for each remove the number, maybe isalpha() #return list as a string comma sep each value countries_with_number = prices.split() country_list = [] for country in countries_with_number: country_list.append(country[:2]) return ", ".join(country_list) # your code here print(get_country_codes("ca$199, ba$101")) # some tests to check your work. You shouldn't modify these. #from test import testEqual #testEqual(get_country_codes("NZ$300, KR$1200, DK$5"), "NZ, KR, DK") #testEqual(get_country_codes("US$40, AU$89, JP$200"), "US, AU, JP") #testEqual(get_country_codes("AU$23, NG$900, MX$200, BG$790, ES$2"), "AU, NG, MX, BG, ES") #testEqual(get_country_codes("CA$40"), "CA")
2f362731f714af34d9fbf51fe26202166c55ef9a
ramo/competitive-programming-solutions
/python/hackerearth/HashTable/kk_and_crush.py
1,065
3.90625
4
""" https://www.hackerearth.com/practice/data-structures/hash-tables/basics-of-hash-tables/practice-problems/algorithm/exists/ """ from sys import stdin from collections import deque # we are using this way of getting the data, as the input in the test cases are not dynamic programming # language friendly. One instance they are giving the array as space separated integers and next they are giving it as # line separated integers, to tackle this input we buffer the whole input and take individual integers as required data = stdin.read() buff = deque(data.split()) def get_int(): global buff return int(buff.popleft()) def my_hash(n): return n + 100000 def main(): t = get_int() for _ in range(t): n = get_int() lookup = [False] * 200002 for _ in range(n): lookup[my_hash(get_int())] = True q = get_int() for _ in range(q): if lookup[my_hash(get_int())]: print('Yes') else: print('No') if __name__ == '__main__': main()
32686988ed02fd741a1d0ad88f4fdd8af3557da6
sionide21/python-speak7330
/speak7330.py
4,868
3.578125
4
#!/usr/bin/env python from pprint import pprint import re import argparse class Phrase(object): def __init__(self, s=""): super(Phrase, self).__init__() self.p = s.lower().split() def append(self, a): self.p.append(a) def pop(self): return self.p.pop() def num_words(self): return len(self.p) def __len__(self): return len(self.p) def __str__(self): return ' '.join(self.p) def __hash__(self): return hash(str(self)) def __repr__(self): return str(self) def __cmp__(self,other): return cmp(str(self), str(other)) expando_words = re.compile('^[ankw].*[0-9][a-z]{1,3}$|^[0-9]{2,}$') class Words(object): def __init__(self, str): super(Words, self).__init__() self.string = str.lower().split() self.__words = [] def __iter__(self): self.__words = [x for x in self.string] return self def next(self): if self.__words: x = self.pop(0) if expando_words.match(x): self.push_letters(x) x = self.pop(0) return x else: raise StopIteration def push_letters(self, word): for i in word[::-1]: self.push(i) def push(self,v): self.__words.insert(0, v) def pop(self,v): return self.__words.pop(0) def __len__(self): return len(self.__words) def substrings(self): for i in range(len(self.string)-1): yield ' '.join(self.string[:i+1]) class Emitter(object): def __init__(self): super(Emitter, self).__init__() self.output = [] def emit(self, s): self.output.append(s) def send(self): print " ".join(self.output) class Application(object): def __init__(self): self.args = self.parse_args() self.terminals = {} self.nonterminals = set() def speak(self, q): phrase = Phrase() output = Emitter() words = Words(q) for word in words: phrase.append(word) if phrase in self.nonterminals and len(words) > 0: continue else: try: tok = self.terminals[phrase] output.emit(tok) if self.args.verbose: print ' Found:', tok, phrase except: # walk back popping one token at a time from built up phrase if len(phrase) > 1: while len(phrase) > 1: words.push(phrase.pop()) try: tok = self.terminals[phrase] output.emit(tok) if self.args.verbose: print " Found:", tok, phrase break except KeyError: pass else: # we should never get here because at the very least the first token was valid raise Exception("Parse walkback failed") else: if self.args.verbose: print "Not Found: ", phrase phrase = Phrase() return output def parse_args(self): parser = argparse.ArgumentParser(description="Generate speech codes for 7330 repeater") parser.add_argument('-v', dest='verbose', action='store_true', help='Print parsing detail') parser.add_argument('-e', dest='expression', nargs='?', metavar="PHRASE", help='speak PHRASE') return parser.parse_args() def main(self): with open('spoken_words.csv', 'r') as f: for l in f: code, string = l.strip().lower().split(',') self.terminals[Phrase(string)] = code for p in Words(string).substrings(): self.nonterminals.add(Phrase(p)) if False: pprint(sorted(self.terminals)) pprint(self.nonterminals) return if self.args.expression: self.speak(self.args.expression).send() else: while True: try: q = raw_input("Enter phrase: ").strip().lower() if q == "": return except: print break output = self.speak(q) if self.args.verbose: print "Result String:" output.send() if __name__ == '__main__': Application().main()
d80c7bba93ec2e1fd962386e3dfa1cc5b9f2716f
mdacoca/jet_brains_projects
/study-projects/tic-tac-toe-light.py
2,455
4.0625
4
import string playing_grid = [["_", "_", "_"], ["_", "_", "_"], ["_", "_", "_"]] turn_counter = 1 def game_complete(): if "_" not in [symbol for row in playing_grid for symbol in row]: return True else: return False def print_grid(): print("---------") print("| " + " ".join(playing_grid[0]) + " |") print("| " + " ".join(playing_grid[1]) + " |") print("| " + " ".join(playing_grid[2]) + " |") print("---------") def win_condition(line): if set(line) == {"X"}: return "X" if set(line) == {"O"}: return "O" else: return False print_grid() while True: input_coord = input("Enter the coordinates: ").split() int_coord = [int(coord) for coord in input_coord] matrix_index = [-1 * (int_coord[1] - 3), int_coord[0] - 1] # Converting inputted coordinates into matrix indexes # Coordinate input validation if any(coord not in string.digits for coord in input_coord): print("You should enter numbers!") continue if len(input_coord) != 2: print("Only enter two coordinates!") continue if any(coord < 1 or coord > 3 for coord in int_coord): print("Coordinates should be from 1 to 3!") continue if playing_grid[matrix_index[0]][matrix_index[1]] != "_": print("This cell is occupied! Choose another one!") continue # Symbol replacment if turn_counter % 2 == 0: playing_grid[matrix_index[0]][matrix_index[1]] = "X" # "X" plays on even turns turn_counter += 1 else: playing_grid[matrix_index[0]][matrix_index[1]] = "O" # "O" plays on odd turn_counter += 1 print_grid() # Defining non-row winning lines column_0 = [row[0] for row in playing_grid] column_1 = [row[1] for row in playing_grid] column_2 = [row[2] for row in playing_grid] diagonal_0 = [row[count] for count, row in enumerate(playing_grid)] diagonal_1 = [row[count + (count - 1) * -2] for count, row in enumerate(playing_grid)] # Win condition check winning_lines = [playing_grid[0], playing_grid[1], playing_grid[2], column_0, column_1, column_2, diagonal_0, diagonal_1] win_check = [win_condition(line) for line in winning_lines] if "X" in win_check: print("X wins") break elif "O" in win_check: print("O wins") break if game_complete(): print("Draw") break
f895d535bbb767294abbcd4a685a83a78acf0e75
tomas-barros/python-learning
/basic-programs/primos.py
294
3.703125
4
def esPrimo(n): if n<2: return False for x in range(2,n): if n%x == 0: return False return True while True: inp = int(input('Type the number: ')) if (esPrimo(inp)): print(f"{inp} es primo.") else: print(f'{inp} no es primo.')
af1599ea433187c517f2b02dbaaa7ef6120e3611
younheeJang/pythonPractice
/for_loop/multiplication_table.py
204
3.90625
4
for i in range(1, 10): print(i) numbers = [] numbers = list(range(1,10)) print(numbers) for n in numbers: for nn in numbers: print( str(n) + " * " + str(nn) + " = " + str(n*nn))
f67749254eb2fcc9bc5921b578581e3397e88fa2
dedekinds/pyleetcode
/554_Brick Wall_Medium.py
877
3.65625
4
'''554. Brick Wall 2017.6.10 未通过超时 ''' class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ ans=99999999 minres=0 for x in range(1,sum(wall[0])): #print('wall=',wall) #print('ans=',ans) for y in range(len(wall)): if wall[y][0]==1: wall[y]=wall[y][1:] else: minres+=1 wall[y][0]-=1 if minres<ans: ans=minres minres=0 return ans wall=[[100000000],[100000000],[100000000]] temp=Solution() print(temp.leastBricks(wall)) #print(binsearch(nums,target)) #wall=[[100000000],[100000000],[100000000]]
b27e3cc3b5fe13adbcfd826e27cc9dfe2e10ad84
oliviastats/sandbox_github
/python_coding_problems/matrix_multiplication.py
284
3.703125
4
def matrix_multiplication(A: list, B: list): result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] for i in range(len(A)): for j in range(len(B[0])): for k in range(len(B)): result[i][j] += A[i][k] * B[k][j] return result
a7c6e2ac9593be8e49a7b3addad8118fb96a4fad
Alexandr-Bessonov/python_basic
/Lesson_06/practical_task_02_6.py
449
3.59375
4
class Road: def __init__(self, __length, __width): self.length = __length self.width = __width def mas(self): massa = (int(self.length) * int(self.width) * 25 * 5) / 1000 return massa road = Road(input('Введите длину (в метрах): '), input('Введите ширину (в метрах0): ')) print(f'Масса требуемого асфальтобетона: {road.mas()} тонн')
0db2f03f88c9a204ea69962b9780bdfd21ed586c
TayeeChang/algorithm
/树/二叉树的遍历/Binary Tree Preorder Traversal.py
1,623
3.671875
4
# -*- coding: utf-8 -*- # @Time : 2021/6/2 17:09 # @Author : haojie zhang from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # 前序遍历 class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) # 使用栈 class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] stack = [root] res = [] while stack: node = stack.pop() res.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return res # Morris遍历 class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [] curr = root while curr: mostRight = curr.left if mostRight: while mostRight.right and mostRight.right != curr: mostRight = mostRight.right if not mostRight.right: res.append(curr.val) mostRight.right = curr curr = curr.left continue else: mostRight.right = None else: res.append(curr.val) curr = curr.right return res
b616dd089693b8df2de57e31736e68673f04bd01
Kavint9/PreCourse-2
/Exercise_2.py
918
4.1875
4
# Time Complexity : O[n] # Space Complexity : O(1) # Python program for implementation of Quicksort Sort # give you explanation for the approach def partition(arr,low,high): pivot_index = low pivot = arr[pivot_index] while low < high: while low < len(arr) and arr[low] <= pivot: low+=1 while arr[high] > pivot: high-=1 if low < high: arr[low], arr[high] = arr[high], arr[low] arr[high], arr[pivot_index] = arr[pivot_index], arr[high] return high #write your code here # Function to do Quick sort def quickSort(arr,low,high): if low < high: p = partition(arr, low, high) quickSort(arr, low, p - 1) quickSort(arr, p + 1, high) #write your code here # Driver code to test above arr = [10, 7, 8, 9, 1, 5] n = len(arr) quickSort(arr,0,n-1) print ("Sorted array is:") print(arr)
2857bb4d29057e0071320f252ce93ec820865f77
jinsuyun/DataAnalytics
/practice/set.py
689
4.09375
4
'''다음의 값들을 아이템으로 갖는 두 리스트 객체를 생성함  10, 20, 30, 40, 30, 20, 10  100 이하 0 이상의 모든 짝수 정수  두 객체를 집합 자료형으로 변환하여 합집합 , 교집합 객체를 구하고 , 각각을 오름차순 정렬로 출력할 것''' a=[10,20,30,40,30,20,10] b=list(range(0,101,2)) set_a=set(a)#set으로 변환 set_b=set(b) print("set으로 변환") print(set_a) print(set_b) print("합집합") print(set_a.union(set_b)) print("교집합") print(set_a.intersection(set_b))#교집합 print("오름차순으로 정렬") print(list(set_a)) print(sorted((set_a)))#sorted는 원본은 그대로 냅둠 print(set_a)
83db9871d9651a322a0a601ec77aeabff27b1d63
Bat-Turtle/python-101
/11_conditionals-and-loops/11_11_fizzbuzz.py
383
3.765625
4
# You start this journey with a number `n`. # You have to display a string representation of all numbers from 1 to n, # but there are some constraints: # - If the number is divisible by 3, write `Fizz` instead of the number # - If the number is divisible by 5, write `Buzz` instead of the number # - If the number is divisible by both 3 and 5, write `FizzBuzz` instead of the number
aa3356fc146b5095ab2890563e8436a7fd680434
josh-mallett/AlgorithmProblems
/Strings and Arrays/allUniqueCharacters/isUnique.py
695
3.828125
4
# checks if a string contans all unique characters def main(): print('\n' + 'playground: ' + str(isUnique('playground')) + '\n') print('hello: ' + str(isUnique('hello')) + '\n') print('world: ' + str(isUnique('world')) + '\n') print(' : ' + str(isUnique(' ')) + '\n') print(' : ' + str(isUnique(' ')) + '\n') print('supercalifragilisticexpialidocious: ' + str(isUnique('supercalifragilisticexpialidocious')) + '\n') def isUnique(chars): if len(chars) >= 128: return False seen = [] for c in chars: if(c in seen): return False seen.append(c) return True if (__name__ == '__main__'): main()
980ff6bde1ac3f926aece941cede2a62a1f6c3d4
heitorchang/learn-code
/battles/tourneys/20170617_1130.py
849
3.515625
4
def differentValuesInMultiplicationTable2(n, m): vals = set() for i in range(1,n+1): for j in range(1,m+1): vals.add(i*j) return len(vals) from math import sqrt, floor def eratosthenesSieveEnumerateAll(n): # not very efficient, deleted multiples are reused nums = set(range(2, n+1)) for i in range(2, floor(sqrt(n)) + 1): for step in range(2*i, n+1, i): nums.discard(step) return sorted(nums) def eratosthenesSieve(n): lst = list(range(2, n+1)) counter = 0 i = lst[counter] while i <= floor(sqrt(n)): for step in range(2*i, n+1, i): try: lst.remove(step) except ValueError: pass counter += 1 i = lst[counter] return lst def test(): testeql(eratosthenesSieve(9), [2,3,5,7])
b3927b707af3c7ab22563d88779f29811153e214
opendere/ircbook
/util/dateutils.py
778
4
4
import re from datetime import datetime, date def today(): """Obtain a naive date object from the current UTC time.""" now = datetime.utcnow() return date(now.year, now.month, now.day) def to_int(s): try: int(s[0:4]) except E as ex: print(ex) raise ValueError("Not an integer") def parse_iso_date(s): if s is None: raise ValueError("No date provided") if len(s) != 10: raise ValueError("Date must contain ten characters.") pattern = re.compile("[0-9]{4}-(0[0-9]|10|11|12)-[0-9]{2}") if not pattern.fullmatch(s): raise ValueError("Invalid date format: " + s + ". Must use yyyy-mm-dd.") year = int(s[0:4]) month = int(s[5:7]) day = int(s[-2:]) return date(year, month, day)
ff26cd08420f4fc10f7a6677cb9162b84a86daa8
natestrong/ucla-data-science
/module 2/part c/Answers-BeginnerToModerate.py
3,894
4.21875
4
#********************** # Variables in Python #********************** #E1 # Declare a variable (i.e. something that stores a value) and initialize it (i.e. set something to that variable) someVariable = 0 print(someVariable) #E2 # Change the value of that variable (i.e. change what was initialized before), go ahead and try # to reset/declare, that variable a few times, check the variable type, (use type function, i.e. is # it int, string, etc.) # Note: Run each variable declaration separately someVariable = "foobar" someVariable = "foo" someVariable = 111 #(remember run print for each statement separately) print(someVariable) print(type(someVariable)) #E3 # Global vs. local variables in functions def someFunction(): #this variable is LOCAL only someOtherVariable = "def" print(someOtherVariable) someFunction() # you should get 'NameError: name 'someOtherVariable' is not defined' (variable ONLY exists in the function) print(someVariable) # This is the variable we declared earlier (it's GLOBAL) print(someVariable) #E4 # Pass function to a function def someOtherFunc(arg): arg=arg+1 return arg def someFunc(someOtherFunc): arg = someOtherFunc(5) print(arg) #E5 #Now delete all the variables we made del someVariable #********************** # Conditions in Python #********************** #E6 # Write a conditional in Python def compare(): a, b = 10, 100 # conditional flow uses if, elif, else (no case statements in python) if(a < b): result= "a is less than b" elif (a == b): result= "a is same as b" else: result= "a is greater than b" print(result) #********************** # Functions in Python #********************** #E7 # Define a function (i.e. takes inputs, outputs, in this case a function with NO arguments, # NO return values) def someFunction(): print(1+1) #E8 # Define a function (i.e. takes inputs, outputs, in this case a function with arguments) # NO return values) def someFunction(a,b): print(a+b) #E9 # Define a function (i.e. takes inputs, outputs, in this case a function with arguments) # return values) def someFunction(a,b): print(a+b) return (a+b) #E10 ### Advanced # Define a function (i.e. takes inputs, outputs, in this case a function with arguments) # return values, has DEFAULT values and VARIABLE number of arguments) def someFunction(a=1,b=1,*args): total = 0; #Multiple arg's for i in args: total = a + b + i + total return total someFunction(1,1,4,5,3,3) #********************** # Loops in Python #********************** #E11 # Create a while loop def someFunction(): x = 0 # create a while loop while (x < 5): print(x) x = x + 1 # create a for loop for x in range(5,10): print(x) #E12 # Create a for loop def someFunction(): x = 0 # create a for loop for x in range(5,10): print(x) #E13 ### Advanced # loop over a collection, use the enumerate() function to get index, and break and continue (generally) # don't want to 'break' out of loops def someFunction(): # use a for loop over a collection countries = ["Brazil","Turkey","Iran","Canada","Nigeria","England","Vietnam"] for c in countries: print ("Before breaking " + c) if c == "Canada": break if c != "Japan": continue print(c) for i, c in enumerate(countries): print(i, c) ### Advanced #********************** # Classes in Python #********************** #E14 # Declare 2 classes, and instantiate (declare one of each), and manipulate their variables # Classes are the basis as a framework for object oriented programming class someClass(): def method1(self): print ("someClass method1") def method2(self, someString): print ("someClass method2: " + someString) def someFunction(): c = someClass() c.method1() c.method2("Foobar") if __name__ == "__main__": someFunction()
1353121ccae0a23e91d425905b5d6a50af49627d
PedroRgz/Sesiones-Python
/9_whileloop.py
584
3.875
4
import random def run(): number_found = False random_number= random.randint(0,30) #escogerá un número del 0 al 30 al azar while not number_found: #not'FALSE => True ; Not 'TRUE' => False number = int(input('Intenta con un numero: ')) if number == random_number: print('Felicidades! Lo encontraste!') number_found = True elif number > random_number: print('el número es más pequeño') elif number < random_number: print('el número es más grande') if __name__ == '__main__': run()
1baee8c846ac640d8efd94736d55f4243cde8bb1
Purushotamprasai/Python
/Palani_Bishwo_apoorva/002_python_datatypes and functios/001_fundamental.py
206
3.765625
4
# to understand the fundamental datatype and basic built in function var = input("enter some fundamental data :") print "data with in var : ",var print (type(var)) print "memory location :",id(var)
74966f560345545436e67e1af925d103229cba8e
KevinSwiftiOS/MachineLearning
/框架/numpy学习/numpy07.py
367
4.125
4
#分割array import numpy as np; a = np.arange(12).reshape((3,4)); print(a); #从横向分割 对列进行操作 分割成4块 print(np.split(a,4,axis=1)); #从行数分割 print(np.split(a,3,axis=0)); #进行不等量的分割 4列可以分割成3列 print(np.array_split(a,3,axis=1)); #分割函数 横向分 print(np.vsplit(a,3)); #纵向分 print(np.hsplit(a,4));
98facb773e13844f89514fb6db6bfc6becf6d072
horen2018/My-DataStructure-forPython
/LinkedList.py
14,654
3.796875
4
class LinkedListNode(object): ''' # 链表LinkedList类的节点类 ''' def helpText(self): ''' # LinkedListNode类的说明文档 ''' helpDescription = '''\033[1;32;40m--LinkedListNode类的属性列表: \033[1;32;40m--List:记录该节点的父链表对象 \033[1;32;40m--Value:记录该节点储存的值 \033[1;32;40m--Next:记录该节点在链表中的下一个节点 \033[1;32;40m--Previous:记录该节点在链表中的上一个节点\033[0m''' print(helpDescription) def __init__(self, value): ''' # 初始化链表节点类 # value => 链表节点储存的数据 # lis => 链表节点所属于的链表 ''' self.List = None self.Value = value self.Next = None self.Previous = None pass class LinkedList(object): ''' # 双重链接列表数据结构 ''' def helpText(self): ''' # LinkedList类的说明文档 ''' helpDescription = ''' \033[1;32;40m--LinkedList类的属性列表: \033[1;32;40m --First:记录链表的头端节点 \033[1;32;40m --Last:记录链表的尾端节点 \033[1;32;40m --Count:记录链表的节点总数 \033[1;32;40m--LinkedList类的方法列表: \033[1;32;40m --addAfter: 向指定的链表中的节点后一位添加一个新的节点 \033[1;32;40m --addBefore: 向指定的链表中的节点前一位添加一个新的节点 \033[1;32;40m --addFirst: 向链表的头端添加数据,原先的头端数据会被向后一位移动 \033[1;32;40m --addLast: 向链表的末端添加数据 \033[1;32;40m --aggregate: 将链表中所有节点的值进行累加 \033[1;32;40m --allDo: 传入一个仅带有链表节点参数的方法,allDo会遍历链表中所有节点并执行传入的方法 \033[1;32;40m --clear: 清空链表的所有节点 \033[1;32;40m --contains: 检测链表所有节点中是否包含检测的值 \033[1;32;40m --find: 从链表中的头端开始找寻你要检索的值的节点,并且返回该节点,若没有检索到符合查找的值的节点,则返回一个空节点 \033[1;32;40m --findLast: 从链表中的尾端开始找寻你要检索的值的节点,并且返回该节点,若没有检索到符合查找的值的节点,则返回一个空节点 \033[1;32;40m --remove: 移除第一个匹配的节点 \033[1;32;40m --removeFirst: 移除链表的头端节点 \033[1;32;40m --removeLast: 移除链表的末端节点 \033[1;32;40m --reverse: 按照链表中节点的值排序排序节点(从大到小) \033[1;32;40m --sort: 按照链表中节点的值排序排序节点(从小到大) \033[1;32;40m --toArray: 返回链表转化而成的数组\033[0m ''' print(helpDescription) def __init__(self, array = None): ''' # 初始化链表 # array => 可以不输入生成一个空链表;或者输入一个数组使其生成链表 ''' if array != None: if type(array) == list and len(array) > 0: self.First = LinkedListNode(array[0]) # self.__getList(self.First) temp = self.First temp2 = self.First if len(array) > 1: for i in array[1:]: temp.Next = LinkedListNode(i) temp = temp.Next # self.__getList(temp) temp.Previous = temp2 temp2 = temp else: self.First = array self.allDo(self.__getList) self.Count = self.__checkCount() self.Last = self.__checkLast() def __checkLast(self): ''' # 私有方法:检测链表末端变量Last的值 ''' temp = self.First while temp: if temp.Next == None: return temp temp = temp.Next def __checkCount(self): ''' # 私有方法:检测链表长度Count的值 ''' count = 0 if self.First: temp = self.First while temp: temp = temp.Next count += 1 return count def __getList(self, node): ''' # 私有方法:注册链表节点,告知链表内节点它自身是在哪个链表中 ''' if type(node) == LinkedListNode: node.List = self def __removeList(self, node): ''' # 私有方法:移除链表节点后注销它自身的链表 ''' if type(node) == LinkedListNode: node.List = None def __quickSort(self, arr, left, right, r): ''' # 私有方法:快速排序 # r => True:倒序排序;False:正序排序 ''' if left < right: key = arr[left] i = left j = right while i < j: if r: while (i < j) and (arr[j] <= key): j -= 1 else: while (i < j) and (arr[j] >= key): j -= 1 temp = arr[j] arr[j] = arr[i] arr[i] = temp if r: while (i < j) and (arr[i] >= key): i += 1 else: while (i < j) and (arr[i] <= key): i += 1 temp = arr[j] arr[j] = arr[i] arr[i] = temp arr[i] = key self.__quickSort(arr, left, i - 1, r) self.__quickSort(arr, j + 1, right, r) return arr def allDo(self, function): ''' # 传入一个仅带有链表节点参数的方法,allDo会遍历链表中所有节点并执行传入的方法 # function => 传入一个仅带有链表节点参数的方法 ''' if self.First: temp = self.First while temp: function(temp) temp = temp.Next def addFirst(self, value): ''' # 向链表的头端添加数据,原先的头端数据会被向后一位移动 # value => 重载1:插入的数据; 重载2:插入一个LinkedListNode的节点 ''' if self.First == None: if type(value) == LinkedListNode: self.First = value else: self.First = LinkedListNode(value) else: temp = self.First if type(value) == LinkedListNode: self.First = value else: self.First = LinkedListNode(value) self.First.Next = temp temp.Previous = self.First self.allDo(self.__getList) self.Count = self.__checkCount() self.Last = self.__checkLast() pass def addLast(self, value): ''' # 向链表的末端添加数据 # value => 重载1:插入的数据; 重载2:插入一个LinkedListNode的节点 ''' if self.First == None: if type(value) == LinkedListNode: self.First = value else: self.First = LinkedListNode(value) else: temp = None if type(value) == LinkedListNode: temp = value else: temp = LinkedListNode(value) temp2 = self.Last temp2.Next = temp temp.Previous = temp2 self.allDo(self.__getList) self.Last = self.__checkLast() self.Count = self.__checkCount() pass def find(self, value): ''' # 从链表中的头端开始找寻你要检索的值的节点,并且返回该节点,若没有检索到符合查找的值的节点,则返回一个空节点 # value => 检索链表中的值 ''' item = LinkedListNode(value) temp = self.First while temp: if temp.Value == item.Value: return temp temp = temp.Next return item def findLast(self, value): ''' # 从链表中的尾端开始找寻你要检索的值的节点,并且返回该节点,若没有检索到符合查找的值的节点,则返回一个空节点 # value => 检索链表中的值 ''' item = LinkedListNode(value) temp = self.Last while temp: if temp.Value == item.Value: return temp temp = temp.Previous return item def addAfter(self, node, value): ''' # 向指定的链表中的节点后一位添加一个新的节点 # node => 该链表中的节点,node参数的类型必须为LinkedListNode # value => 重载1:插入节点的值; 重载2:插入一个LinkedListNode的节点 ''' if type(node) != LinkedListNode: print('node参数的类型必须为LinkedListNode') exit(1) if node.List != self: print('node节点不为当前链表中的节点,输入的参数node必须是当前链表中的节点') exit(1) if type(value) == LinkedListNode: item = value else: item = LinkedListNode(value) item.Previous = node item.Next = node.Next if node.Next: node.Next.Previous = item node.Next = item self.__getList(item) self.Count = self.__checkCount() self.Last = self.__checkLast() def addBefore(self, node, value): ''' # 向指定的链表中的节点前一位添加一个新的节点 # node => 该链表中的节点,node参数的类型必须为LinkedListNode # value => 重载1:插入节点的值; 重载2:插入一个LinkedListNode的节点 ''' if type(node) != LinkedListNode: print('node参数的类型必须为LinkedListNode') exit(1) if node.List != self: print('node节点不为当前链表中的节点,输入的参数node必须是当前链表中的节点') exit(1) if type(value) == LinkedListNode: item = value else: item = LinkedListNode(value) item.Previous = node.Previous if node.Previous: node.Previous.Next = item item.Next = node node.Previous = item self.__getList(item) self.Count = self.__checkCount() self.Last = self.__checkLast() def remove(self, value): ''' # 移除第一个匹配的节点 # value => 重载1:需要删除的值; 重载2:需要删除的链表节点 ''' temp = self.First while temp: if type(value) == LinkedListNode: if value == temp: temp.Previous.Next = temp.Next temp.Next.Previous = temp.Previous return else: if value == temp.Value: temp.Previous.Next = temp.Next temp.Next.Previous = temp.Previous return temp = temp.Next self.Count = self.__checkCount() self.Last = self.__checkLast() def removeFirst(self): ''' # 移除链表的头端节点 ''' if self.First: temp = self.First.Next if temp: temp.Previous = None self.First = temp else: self.First = None self.Count = self.__checkCount() self.Last = self.__checkLast() def removeLast(self): ''' # 移除链表的末端节点 ''' if self.Last: temp = self.Last.Previous if temp: temp.Next = None else: self.First = None self.Count = self.__checkCount() self.Last = self.__checkLast() def clear(self): ''' # 清空链表的所有节点 ''' if self.First: self.First = None self.Count = self.__checkCount() self.Last = self.__checkLast() def sort(self): ''' # 按照链表中节点的值排序排序节点(从小到大) ''' arr = self.toArray() arr = self.__quickSort(arr, 0, (len(arr) - 1), False) self.clear() self.__init__(arr) def reverse(self): ''' # 按照链表中节点的值排序排序节点(从大到小) ''' arr = self.toArray() arr = self.__quickSort(arr, 0, (len(arr) - 1), True) self.clear() self.__init__(arr) def toArray(self): ''' # 返回链表转化而成的数组 ''' arr = [] temp = self.First while temp: arr.append(temp.Value) temp = temp.Next return arr def contains(self, value): ''' # 检测链表所有节点中是否包含检测的值 # value => 需要检测的值 ''' temp = self.First while temp: if temp.Value == value: return True temp = temp.Next return False def aggregate(self, Type = 0): ''' # 将链表中所有节点的值进行累加 # Tpye => 0:返回一个str类型; 1:返回一个number类型(累加将忽略非number类型) ''' if Type == 0: txt = '' sign = ',' temp = self.First while temp: s = temp.Value if type(s) == int: s = str(s) txt += s temp = temp.Next if temp: txt += sign return txt elif Type == 1: temp = self.First num = 0 while temp: txt = temp.Value if type(txt) == int: num += txt temp = temp.Next return num else: print('Type参数只能传入0或者1') exit(1) pass
6517d96b5a69583a8273349c2fffca0e9a2392ff
mumarkhan999/UdacityPythonCoursePracticeFiles
/5_whileLoop.py
120
3.921875
4
#printing helloworld using while loop i = 0 while(i < 5): print(i) i = i +1 input("Press any key to quit...")
60708d166ab2c387fd4c256ded228825618a2d5b
RichardSaldanha07/Behaviour-of-Europeans-in-Tourism-who-are-part-time-employed
/Python Codes/Correlation.py
1,127
4.09375
4
#Author: Richard Saldanha #Student id : 18183034 # Cource : Master of Science in Data Analytics # Batch: A # Subject: Data Intensive Architecture # Code: To find out the Pearson Correaltion Coefficient in Python and carry out Visualization. import pandas as pd import matplotlib.pyplot as plt df1 = pd.read_csv('D:\\NCI\\practice-labs\\Data Intensive\\AWS\\.ssh\\correlation.csv', header=None) df1 # Handling of missing values missing_values = ["0"] df1 = pd.read_csv('D:\\NCI\\practice-labs\\Data Intensive\\AWS\\.ssh\\correlation.csv',na_values=missing_values, header=None) df1.columns = ["country_year","total_parttime","total_tourism"] df1 = df1.dropna(how='any') df1 # calculating Pearson Coefficient of Correlation correlation = df1.corr(method="pearson") correlation import matplotlib.pyplot as plt import pandas as pd # gca stands for 'get current axis' ax = plt.gca() plt.xlabel('country_year') plt.ylabel('Percentage of Population') df1.plot(kind='line',x='country_year',y='total_parttime',ax=ax, color='red') df1.plot(kind='line',x='country_year',y='total_tourism',ax=ax, color='green') plt.show()
0284c7aec352e69cee4f84dc5cfd17c8224095db
abdul-malik360/python_libraries
/practice.py
1,985
4.28125
4
# Write a program which randomly picks an integer from 1 to 100. # Your program should prompt the user for guesses - if the user guesses incorrectly, # it should print whether the guess is too high or too low. If the user guesses correctly, # the program should print how many guess the user took to guess the right answer. # You can assume that the user will enter valid input. import random number = random.randint(1, 100) tries = 0 name = input("What's your Name? ") name = name.strip() print("Hello " + name + ", I'm looking for a friend.") print("Would you like to play a game with me?") print("1) Yes I would!") print("2) No I'm boring") option = input("Are we going to be friends? ") option = int(option) if option != 1 or 2: pass if option == 1: print("Wow you're already amazing, thank you for saying yes") print("I'm thinking of a number between 1 and 100") print("You have 5 guess") print("Let The Guessing Begin!") guess = input("Your first guess: ") guess = int(guess) tries += 1 if guess > number: print("I can't count that far, go lower") if guess < number: print("I can count a bit more than that, go higher") while guess != number and tries < 5: guess = input("You can go again: ") guess = int(guess) tries += 1 if guess > number: print("Just a bit lower my friend") if guess < number: print("Just a bit higher my friend") if guess == number: print("WELL DONE my friend!!!") print("You only tried: " + str(tries) + " times and completed the challenge") print("THANKS FOR PLAYING WITH ME") else: print("I'm sorry my friend") print("The number was " + str(number)) print("You ran out of guesses") elif option == 2: print("Thanks for speaking to me " + name + (" have a good day!") else: print("The instructions were simple " + name) print("JUST PICK 1 OR 2!")
aff379e6171c8002ac3a0cc9d6990de694fec64a
jay841224/euler
/p48.py
390
3.6875
4
from time import time def square(n): return n**n def main(): ten = 0 a = 10**9 b = 10**10 for x in range(1, 1001): s = square(x) if s//a == 0: ten += s else: ten += s%b if ten//b != 0: ten = ten%b print(ten) stime = time() if __name__ == '__main__': main() etime = time() print(etime - stime)
0e074c0b531f959d98b8364cad8e68cea5c43e09
EricJGriffin/CeeLo
/CeeLo.py
10,543
3.609375
4
# CeeLo.py from random import randrange from graphics import * from dieview2 import DieView from button import Button class Dice: def __init__(self): self.dice = [0]*3 self.rollAll() def rollAll(self): self.roll(range(3)) def roll(self, which): for pos in which: self.dice[pos] = randrange(1,7) def values(self): return self.dice[:] def score(self): counts = [0] * 7 for value in self.dice: counts[value] = counts[value] + 1 # each outcome will have an assigned ranking if 4 in self.dice and 5 in self.dice and 6 in self.dice: return "Automatic Win", 13 elif 1 in self.dice and 2 in self.dice and 3 in self.dice: return "Automatic Loss", 0 elif 3 in counts: if self.dice[0] == 1: return "Trip Ones", 7 elif self.dice[0] == 2: return "Trip Twos", 8 elif self.dice[0] == 3: return "Trip Threes", 9 elif self.dice[0] == 4: return "Trip Fours", 10 elif self.dice[0] == 5: return "Trip Fives", 11 elif self.dice[0] == 6: return "Trip Sixes", 12 elif 2 in counts: firstVal = self.dice[0] if firstVal == self.dice[1]: myNum = self.dice[2] elif firstVal == self.dice[2]: myNum = self.dice[1] else: myNum = self.dice[0] if myNum == 1: return "One", 1 elif myNum == 2: return "Two", 2 elif myNum == 3: return "Three", 3 elif myNum == 4: return "Four", 4 elif myNum == 5: return "Five", 5 elif myNum == 6: return "Six", 6 else: return "Garbage", 0 class Player: def __init__(self): self.money = 100 self.dice = Dice() def values(self): return self.dice.values() def winsPot(self, pot): self.money = self.money + pot def subtract(self, amt): self.money = self.money - amt def getMoney(self): return self.money def playerRoll(self): result = "Garbage" while result == "Garbage": self.dice.rollAll() result, score = self.playerScore() def playerScore(self): result, score = self.dice.score() return result, score class CeeLo: def __init__(self, interface, players): #self.dice = Dice() self.interface = interface self.playerList = [] for i in range(players): self.playerList.append(Player()) def run(self): while self.interface.continuePlaying(): self.playRound() self.interface.close() def playRound(self): self.interface.activePlayers(self.playerList) potCount = 0 for i, player in enumerate(self.playerList): self.interface.displayMoney(i, player.getMoney()) self.interface.currentPlayer(i) if self.interface.roll() and (player.getMoney() >= 10): player.subtract(10) potCount = potCount + 1 player.playerRoll() self.interface.displayResult(i, player) self.interface.displayMoney(i, player.getMoney()) self.interface.resetPlayerColor(i) winner, addedPotCnt = self.determineWinner() potCount = potCount + addedPotCnt self.interface.displayWinner(winner) self.awardWinner(winner, potCount) for i, player in enumerate(self.playerList): self.interface.displayMoney(i, player.getMoney()) def determineWinner(self): # need to handle same scores scoreList = [] copyList= [] for i, player in enumerate(self.playerList): result, score = player.playerScore() scoreList.append(score) copyList = scoreList[:] copyList.sort() highIndex = scoreList.index(copyList[-1]) if scoreList.count(copyList[-1]) == 1: return highIndex, 0 elif scoreList.count(copyList[-1]) > 1: highIndex, addedPotCnt = self.doubleDown(copyList[-1]) return highIndex, addedPotCnt def DDwinner(self, iList): scoreList = [] copyList = [] #print("indexList:", iList) for pIndex in iList: result, score = self.playerList[pIndex].playerScore() scoreList.append(score) copyList = scoreList[:] copyList.sort() scoreListIndex = scoreList.index(copyList[-1]) #print("scoreListIndex", scoreListIndex) highIndex = iList[scoreListIndex] #print(highIndex) return highIndex def awardWinner(self, winner, potCount): award = potCount * 10 self.playerList[winner].winsPot(award) def doubleDown(self, highScore): # the process will be to first look through the playerList and see # which players have the same score as the high score (copyList[-1]) # then to make a list of the indexes within the player list of those # players. Then loop through that list, using each index in the list # to activate the players and make them play self.interface.doubleDown() indexList = [] # this is a list of the player indexes that have high score for i, player in enumerate(self.playerList): result, score = player.playerScore() if score == highScore: indexList.append(i) # temporarily change colors of players in a double down self.interface.doubleColor(indexList)# will change colors of players in DD # cycle through the index list and make the players loose 10 bucks and # increase potCount by 1 potCount = 0 for each in indexList: self.interface.displayMoney(each, self.playerList[each].getMoney()) self.interface.currentPlayer(each) if self.interface.roll() and (self.playerList[each].getMoney() >= 10): self.playerList[each].subtract(10) potCount = potCount + 1 self.playerList[each].playerRoll() self.interface.displayResult(each, self.playerList[each]) self.interface.displayMoney(each, self.playerList[each].getMoney()) self.interface.resetDoubleColor(each) winner = self.DDwinner(indexList) return winner, potCount class GraphicInterface: def __init__(self): self.win = GraphWin("CeeLo", 700, 600) self.win.setCoords(0,0,7,6) self.drawPlayers() self.drawMoneyDisplays() self.drawDice() self.continueButton = Button(self.win, Point(1,1), 1, 0.3, "Play Round") self.rollButton = Button(self.win, Point(6,1), 0.5, 0.4, "Roll!") self.resultDisplay = Text(Point(2, 5.5), "").draw(self.win) self.resultDisplay.setSize(20) self.winnerDisplay = Text(Point(3.5, 0.2), "").draw(self.win) self.winnerDisplay.setSize(20) def drawPlayers(self): circSpecs = [(3.5, 5), (5, 4), (5,2), (3.5, 1), (2,2), (2,4)] self.playerLabels = [] self.playerCircles = [] for i, (x, y) in enumerate(circSpecs): self.playerCircles.append(Circle(Point(x, y), 0.5).draw(self.win)) self.playerLabels.append(Text(Point(x,y), "Player {0}".format(i+1)).draw(self.win)) def drawMoneyDisplays(self): displaySpecs = [(3.5, 5.7), (5, 4.7), (5, 2.7), (3.5, 1.7), (2,2.7), (2, 4.7)] self.moneyDisplays = [] for x, y in displaySpecs: Rectangle(Point(x-0.4, y - 0.12), Point(x + 0.4, y + 0.12)).draw(self.win) self.moneyDisplays.append(Text(Point(x,y), "").draw(self.win)) def drawDice(self): self.dieOne = DieView(self.win, Point(2.9, 3), 0.5) self.dieTwo = DieView(self.win, Point(3.5, 3.6), 0.5) self.dieThree = DieView(self.win, Point(4.1, 3), 0.5) def continuePlaying(self): self.continueButton.activate() while True: try: p = self.win.checkMouse() if self.continueButton.clicked(p): self.continueButton.deactivate() return True except AttributeError as error: pass def activePlayers(self, playerList): self.resultDisplay.setText("") self.winnerDisplay.setText("") for i, player in enumerate(playerList): if player.getMoney() >= 10: self.playerCircles[i].setFill("green") self.playerLabels[i].setStyle("bold") def currentPlayer(self, pIndex): self.playerCircles[pIndex].setFill("orange") def resetPlayerColor(self, pIndex): self.playerCircles[pIndex].setFill("green") def resetDoubleColor(self, pIndex): self.playerCircles[pIndex].setFill("pink") def displayMoney(self, pIndex, money): self.moneyDisplays[pIndex].setText("$ {0}".format(str(money))) def roll(self): self.rollButton.activate() while True: try: p = self.win.checkMouse() if self.rollButton.clicked(p): self.rollButton.deactivate() return True except AttributeError as error: pass def displayResult(self, pIndex, player): # this method has to display the DieView as well as the result/score # of the roll values = player.values() self.dieOne.setValue(values[0]) self.dieTwo.setValue(values[1]) self.dieThree.setValue(values[2]) result, score = player.playerScore() self.resultDisplay.setText("{0}".format(result)) def displayWinner(self, winner): self.winnerDisplay.setText("Player {0} wins!".format(str(winner + 1))) def doubleColor(self, indexList): for pIndex in indexList: self.playerCircles[pIndex].setFill("pink") def doubleDown(self): self.winnerDisplay.setText("Double Down!")
ee3e946625792c6617752e33d2957abf07e5963e
akyare/Python-Students-IoT
/4-classes/2-advanced/ExampleGoodInheritance.py
1,959
4.53125
5
# In this class we will make a good example of inheritance. # We will make a base class for working with streams. # We can read a stream of data from multiple sources and every source is different to read: # File stream # Network stream # Memory stream # They all have behaviour in common: # We can: # Open # Close # Read data # Reading data from our different sources will every time be handled in a different way # In this example we will also write our own Exception class, # this to make sure that we can raise an exception if we try and do an invalid operation with our stream: class InvalidOperationError(Exception): # If writing our own Exception we mostly use the Exception as a base class. pass class Stream: # Our base class, from here we inherited all our wanted default behaviour for our sub classes. def __init__(self): self.opened = False # Flag used to see if our stream is already open, default false. def open(self): if self.opened: raise InvalidOperationError('Stream is already open!') self.opened = True def close(self): if not self.opened: raise InvalidOperationError('Stream is already closed!') self.opened = False class FileStream(Stream): # For simplicity we will only do a printout in our examples def read(self): print('Reading data from a file...') class NetworkStream(Stream): # For simplicity we will only do a printout in our examples def read(self): print('Reading data from a network...') class MemoryStream(Stream): # For simplicity we will only do a printout in our examples def read(self): print('Reading data from memory...') # Like you can see we don't really have multi-level inheritance, you could at max add 1 level more. [for good practices] # We avoided multiple inheritance our classes have only 1 base class, try to avoid multiple inheritance when possible
7f87d1a339bfd75013e81220fe451ee542f476eb
born2trycn/SongManjia
/节日快乐.py
629
3.734375
4
import time import turtle lala=turtle.Pen() lala.forward(100) now = time.gmtime() print(now) day = now.tm_mday month = now.tm_mon print(month) print(day) month = 3 day = 15 if (month == 3): if (day == 15): print('生日快乐') lala.write('生日快乐') if (month == 7): if (day == 27): print('妈妈,生日快乐') if (day == 30): print('爸爸,生日快乐') if (month == 6): if (day == 21): print('父亲节快乐') if (month == 5): if (day == 10): print('母亲节快乐') if (month == 12): if (day == 7): print('大雪') turtle.done()