blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
8aa0c8beace4b17722202a83f10d41f27d33432a
cemathey/aoc_2020
/day6/day6.py
1,047
3.609375
4
from functools import reduce import string from collections import Counter test = """abc a b c ab ac a a a a b""" test = open("/home/emathey/git-repos/input.txt").read() groups = test.split("\n\n") letter_filter = lambda answer: answer in string.ascii_letters group_answers = [ set(filter(letter_filter, person)) for person in groups # Stripping white space ] # Sum of the set lengths part1 = reduce(lambda total, answer: total + len(answer), group_answers, 0) # Count the number of people who said yes to each individual question answer_counters = [Counter(filter(letter_filter, person)) for person in groups] # Count how many individual people are part of each group group_sizes = [len(person.split("\n")) for person in groups] part2 = 0 for counter, group_size in zip(answer_counters, group_sizes): # Count the number of answers that had the same number of responses as people in the group for count in counter.values(): if count == group_size: part2 += 1 print(f"Part 1: {part1} Part 2: {part2}")
edf4bde9c24c4a418c778676954edf3235a9bdf3
cemathey/aoc_2020
/day9/day9.py
2,659
3.9375
4
from itertools import combinations import sys from typing import List, Tuple, Sequence def build_xmas_list(filename: str) -> List[int]: """Read the instructions from the provided file.""" xmas_values = [int(line) for line in open(filename).readlines()] return xmas_values def find_invalid_value(values: Sequence[int], preamble_len: int = 25) -> int: """Return the first value we find that cannot be expressed as the sum of two unique integers in the previous preamble_len numbers""" valid_value: bool = True start_idx: int = 0 chunk_len: int = preamble_len while valid_value: next_value = values[chunk_len] # Use a set to consider only unique number pairs summands = set(values[start_idx:chunk_len]) # Generate all of the potential summand combinations of length 2 potential_combinations = combinations(summands, 2) for x, y in potential_combinations: if next_value == (x + y): break else: # Loop has been exhausted without finding a valid pair of numbers adding up to next_value valid_value = False break start_idx += 1 chunk_len += 1 return next_value def find_encryption_weakness(values: Sequence[int], invalid_value: int) -> int: """Find the encryption weakness given our sequence of values and an already calculated invalid_value""" invalid_value_idx: int = values.index(invalid_value) start_idx: int = -1 not_found: bool = True while not_found: start_idx += 1 cumulative_sum: int = 0 stop_idx: int = invalid_value_idx sliding_region: Sequence[int] = values[start_idx:stop_idx] for (idx_offset, num) in enumerate(sliding_region): cumulative_sum += num if cumulative_sum > invalid_value: break elif cumulative_sum == invalid_value: # our index within our sliding region needs to be adjusted to account for the distance from the start stop_idx = start_idx + idx_offset + 1 not_found = False break target_region: Sequence[int] = values[start_idx:stop_idx] return min(target_region) + max(target_region) if __name__ == "__main__": filename: str = sys.argv[1] preamble_len: int = int(sys.argv[2]) xmas_values: List[int] = build_xmas_list(filename) invalid_value: int = find_invalid_value(xmas_values, preamble_len) weakness: int = find_encryption_weakness(xmas_values, invalid_value) print(f"Part 1: {invalid_value}") print(f"Part 2: {weakness}")
1772778c8aad9a9ecfd52b7cc08471b485c2000c
sajjadzoghi/maktab_hw1_functional_and_basic
/t4.py
393
3.5
4
def comb(n, k): if k == 0 or k == n: return 1 else: return comb(n - 1, k - 1) + comb(n - 1, k) while True: try: n = int(input("enter n: ")) k = int(input("enter k: ")) if n >= 0 and k >= 0: print(comb(n, k)) break else: print('try again!') except ValueError: print("please ineger!")
f69253ab798f381207fd346a3d2e680b7d0661be
SergeiEvsujkov/python-project-lvl1
/brain_games/games/prime.py
1,012
3.5
4
# -*- coding: utf-8 -*- """Function gamePrime.""" from brain_games.cli import welcome_user, welcome_user1 from brain_games.functional import ( finish_game, goodanswer, question, randomnumber, wrong_answer, ) def mainprime(): """Do something interesting. # noqa: DAR101 username """ welcome_user() print('Answer "yes" if given number is prime. Otherwise answer "no".') username = welcome_user1() good = 0 while good < 3: number = randomnumber() if number >= 2: index = 2 res = 'yes' while index < number: if abs(number) % index == 0: res = 'no' index = number else: index += 1 else: res = 'no' answer = question(number) if answer == res: goodanswer() good += 1 else: wrong_answer(username, answer, res) finish_game(username)
9524893f907d8b01bc1943f1e663f156ac280df6
gattibugatti/b5_practice
/Decorator.py
718
3.8125
4
class Timing: def __init__(self,function_to_run): self.num_runs = 100 self.func_to_run = function_to_run def __call__(self,*args,**kwargs): avg = 0 for _ in range(self.num_runs): t0 = time.time() self.func_to_run(*args, **kwargs) t1 = time.time() avg += (t1 - t0) avg /= self.num_runs fn = self.func_to_run.__name__ print( "[Timing] Avg время выполнеия %s за %s запусков: %.5f сек" % (fn, self.num_runs, avg) ) return self.func_to_run(*args, **kwargs) def __enter__(self): self.t0 = time.time() return def __exit__(self, *args): t1 = time.time() avg_time = (t1 - self.t0) print('Разница - {}'.format(avg_time))
e170194cff0409e7a49a4d1d9c20c5e096373cda
vikalp174/Iris-Flower-Species-Case-Study
/distance_formulas.py
162
3.78125
4
import math def euclidean_Distance(l1, l2): dist = 0.0 for i in range(len(l1)-1): dist += (l1[i]-l2[i])**2 return round(math.sqrt(dist), 3)
d7c5f382a813e652f99651753d4fe0dbb2518a9a
Arasy/WordCount
/wordcounting.py
3,567
3.609375
4
#!/usr/bin/env python # encoding: utf-8 """ wordcounting.py Created by Arasy on 2019-01-06. Copyright (c) 2019 ACT. All rights reserved. """ from nltk import * from nltk.util import ngrams import sys global unigram_fd, bigram_fd, trigram_fd def show(): print("unigram list :") for i in unigram_fd: print(i) print("\nbigram list :") for i in bigram_fd: print(i) print("\ntrigram list :") for i in trigram_fd: print(i) menu() def save(): namafile = input("\n\nthe file will be saved as :\n1. <filename>-unigram.txt,\n2. <filename>-bigram.txt, and\n3. <filename>-trigram.txt\nwhat shall the filename be?") hasil1 = open(namafile+"-unigram.txt","w") hasil2 = open(namafile+"-bigram.txt","w") hasil3 = open(namafile+"-trigram.txt","w") for i in unigram_fd: hasil1.write("%s \n" % str(i)) #print(i) for i in bigram_fd: hasil2.write("%s \n" % str(i)) #print(i) for i in trigram_fd: hasil3.write("%s \n" % str(i)) #print(i) hasil1.close() hasil2.close() hasil3.close() menu() def quit(): sys.exit() def menu(): print("\nmenu :\n") print("1. show\n") print("2. save to file!\n") print("3. exit\n") choice = int(input("what is your choice?")) switcher = {1:show, 2:save, 3:quit} if choice in [1,2,3]: return switcher.get(choice,"nothing")() else: menu() def count(filename): artikel = open(filename,"r").read() # tanda baca koma dan titik dihilangkan, stopword the, a dihilangkan for sym in ["\n","\t","(",")","``","/","''","\\",".",",", " the ", " a ", "-"]: artikel = artikel.replace(sym," ") kalimat = sent_tokenize(artikel) token = [] for klm in kalimat: token.append(word_tokenize(klm)) listunigram = [] listbigram = [] listtrigram = [] for tk in token: # unigram = ngrams(tk, 1, pad_right=True, pad_left=True, left_pad_symbol="<s>", right_pad_symbol="</s>") # bigram = ngrams(tk, 2, pad_right=True, pad_left=True, left_pad_symbol="<s>", right_pad_symbol="</s>") # trigram = ngrams(tk, 3, pad_right=True, pad_left=True, left_pad_symbol="<s>", right_pad_symbol="</s>") # tanda baca koma dan titik dihilangkan, tanpa padding unigram = ngrams(tk, 1) bigram = ngrams(tk, 2) trigram = ngrams(tk, 3) for gram in unigram: listunigram.append(gram) for gram in bigram: listbigram.append(gram) for gram in trigram: listtrigram.append(gram) global unigram_fd, bigram_fd, trigram_fd unigram_fd = FreqDist(listunigram) bigram_fd = FreqDist(listbigram) trigram_fd = FreqDist(listtrigram) #sorting unigram_fd = list(unigram_fd.items()) unigram_fd.sort(key=lambda item: item[-1], reverse=True) bigram_fd = list(bigram_fd.items()) bigram_fd.sort(key=lambda item: item[-1], reverse=True) trigram_fd = list(trigram_fd.items()) trigram_fd.sort(key=lambda item: item[-1], reverse=True) print("counting finished!") menu() if __name__ == '__main__': if len(sys.argv)<2: print("please specify a file to count!\nuse this format : python wordcounting.py <filename>") elif len(sys.argv)>2: print("too much argument!\n") else: if os.path.isfile(sys.argv[1]): print("counting file %s begin!\n" % sys.argv[1]) count(sys.argv[1]) else: print("file %s not found!!\n" % sys.argv[1])
ad4c834017d20c8d793aa317a850336aa0a9ab95
Gabriel91-kr/lecture_4
/circle_instance_var.py
390
3.75
4
import math class Circle: def __init__(self , name , radius , PI): self.name =name self.radius = radius self.PI = PI def area(self): return self.PI * self.radius**2 def __del__(self): pass c1 = Circle('원', 10 ,math.pi ) c1.area() c2 = Circle('원', 200 ,math.pi ) # print('c1의 면적은 {}'.format(c2.area())) print(c1.__dict__)
1080934e6b1797d3f768f8fb991348c613932739
akshathamanju/Problems
/Trees/5.BinaryTreeZigZagLevelOrderTraversal.py
4,416
4.40625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right '''In this problem we need to traverse binary tree level by level. When we see levels in binary tree, we need to think about bfs, because it is its logic: it first traverse all neighbors, before we go deeper. Here we also need to change direction on each level as well. So, algorithm is the following: We create queue, where we first put our root. result is to keep final result and direction, equal to 1 or -1 is direction of traverse. Then we start to traverse level by level: if we have k elements in queue currently, we remove them all and put their children instead. We continue to do this until our queue is empty. Meanwile we form level list and then add it to result, using correct direction and change direction after. Complexity: time complexity is O(n), where n is number of nodes in our binary tree. Space complexity is also O(n), because our result has this size in the end. If we do not count output as additional space, then it will be O(w), where w is width of tree. It can be reduces to O(1) I think if we traverse levels in different order directly, but it is just not worth it.''' from collections import deque # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right '''In this problem we need to traverse binary tree level by level. When we see levels in binary tree, we need to think about bfs, because it is its logic: it first traverse all neighbors, before we go deeper. Here we also need to change direction on each level as well. So, algorithm is the following: We create queue, where we first put our root. result is to keep final result and direction, equal to 1 or -1 is direction of traverse. Then we start to traverse level by level: if we have k elements in queue currently, we remove them all and put their children instead. We continue to do this until our queue is empty. Meanwile we form level list and then add it to result, using correct direction and change direction after. Complexity: time complexity is O(n), where n is number of nodes in our binary tree. Space complexity is also O(n), because our result has this size in the end. If we do not count output as additional space, then it will be O(w), where w is width of tree. It can be reduces to O(1) I think if we traverse levels in different order directly, but it is just not worth it.''' from collections import deque class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] queue = deque([root]) result, direction = [], 1 while queue: level = [] # local list to keep track of each nodes for i in range(len(queue)): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(level[::direction]) direction *= (-1) # we are setting direction for each level return result ''' Time Complexity: O(N), where N is the number of nodes in the tree. We visit each node once and only once. In addition, the insertion operation on either end of the deque takes a constant time, rather than using the array/list data structure where the inserting at the head could take the O(K) time where K is the length of the list. Space Complexity: O(N) where N is the number of nodes in the tree. The main memory consumption of the algorithm is the node_queue that we use for the loop, apart from the array that we use to keep the final output. As one can see, at any given moment, the node_queue would hold the nodes that are at most across two levels. Therefore, at most, the size of the queue would be no more than 2 \cdot L2⋅L, assuming LL is the maximum number of nodes that might reside on the same level. Since we have a binary tree, the level that contains the most nodes could occur to consist all the leave nodes in a full binary tree, which is roughly L= 2​N/2 . As a result, we have the space complexity of N/2 =N in the worst case. '''
51f77c3c0425154f2d823017dfb18b39d59a36cd
akshathamanju/Problems
/Strings/groupAnagrams.py
605
3.8125
4
class Solution: def groupAnagrams(self, strs): my_dict = {} for word in strs: sortedWord = "".join(sorted(word)) if sortedWord not in my_dict: my_dict[sortedWord] = [word] else: my_dict[sortedWord].append(word) result = [] for item in my_dict.values(): result.append(item) return result o1 = Solution() in1 = ["eat","tea","tan","ate","nat","bat"] print(o1.groupAnagrams(in1)) in1 = [""] print(o1.groupAnagrams(in1)) in1 = ["a"] print(o1.groupAnagrams(in1))
b5d70ad3775ac8e3990862a912b302dbd33303c5
akshathamanju/Problems
/Graph/grah_implementaton_CB/graph_implementation.py
1,211
4.0625
4
from collections import Deque class GraphNode: # returns the node's neighbors # the implementation depends on graph stucture def get_neighbors(self): pass # source, target are GraphNodes # returns True if there exists a path between source and target. def bfs(graph_traversal_method, source, target): visited_nodes = set() # set of visited nodes so we don't revisit nodes we have already seen # Use a Queue since BFS. Here we use a doublyended Queue nodes_to_visit = Deque() # start from the source Node nodes_to_visit.append(source) while nodes_to_visit.isNotEmpty(): # gets next Node from nodes_to_visit and removes from list current_node = nodes_to_visit.popleft() if current_node is target: return True visited_nodes.add(current_node) # mark current_node as visited # add current_node's neighbors to visit if they haven't already for neighbor in current_node.get_neighbors(): if neighbor not in visited_nodes: nodes_to_visit.add(neighbor) # if we search all the neighbors and do not find the target return False return False
e27a2a74b1ae91f9d1f72f137b761bd2bf9e6411
akshathamanju/Problems
/Graph/find_friends/connections.py
833
3.703125
4
if __name__ == '__main__': love_connections = [("Lysander", "Helena"), ("Hermia", "Lusander"), ("Demetrius", "Hermia"), ("Helena","demetrius"), ("Titania","Oberon"),("Oberon", "TItania"),("Puck", None), ("Lysander", "Puck")] # directed adjacency lsit adj_list = {} #{"Lysander":[Helena, puck]} for source, target in love_connections: if source in adj_list: adj_list[source].append(target) else: adj_list[source] = [target] ''' to print vaues of lysander Brute force approach wil be ''' for source, target in love_connections: if source == "Lysander": print(target) ''' optimal solution will be ''' for neighbour in adj_list["Lysander"]: print(neighbour)
8ca06a949c296bd313996b6d4a842e70fcb4c427
kritika92/search_hash
/prefix_search.py
2,048
3.75
4
import os import re from hash_value import value class prefix_searching: def __init__(self,myprefix): self.__word_hash={} self.__myprefix=myprefix def make_hash(self): for word in self.__myprefix: self.add_key(word) def add_key(self,word): for letter_index in range(0,len(word)): key_list=[] word_hash=self.get_word_hash() if(word_hash.has_key(word[0:letter_index+1])): if(letter_index+1==len(word)): word_hash[word[0:letter_index+1]].set_is_word(True) else: continue else: if(letter_index==0): word_hash[word[0:letter_index+1]]=value(word,letter_index+1) else: word_hash[word[0:letter_index]].set_is_end(False) word_hash[word[0:letter_index]].set_key_list(word[0:letter_index+1]) word_hash[word[0:letter_index+1]]=value(word,letter_index+1) def get_word_hash(self): return self.__word_hash def get_prefix(self,word,prefix): if(self.get_word_hash()[word].get_is_end()==True): print('one of the prefix for '+ prefix+ ' is '+word) else: if(self.get_word_hash()[word].get_is_word()==True): print('one of the prefix for '+ prefix+ ' is '+word) list=[] list=self.get_word_hash()[word].get_key_list() for k in list: self.get_prefix(k,prefix) def search_prefixes(self,prefix_list): temp_list=[] for i in prefix_list: temp_list.append(i.lower()) prefix_list=temp_list for word in prefix_list: if(self.get_word_hash().has_key(word)): self.get_prefix(word, word) else: print(word+' doesnot exists')
96b6d6fde4c10d3e2e0bea2bdef0fc9389837a9e
xikunqu/Python_100_days
/D1-15/Day9/eg4.py
1,609
4
4
class Person(object): ''' 人 ''' def __init__(self,name,age): self._name=name self._age=age @property def name(self): return self._name @property def age(self): return self._age @name.setter def name(self,name): self._name=name @age.setter def age(self,age): self._age=age def play(self): print("%s正在愉快的玩耍。"%self._name) def watch_av(self): if self._age>=18: print("%s正在观看爱情"%self._name) else: print("%s只能观看熊出没"%self._name) class Student(Person): ''' 学生 ''' def __init__(self,name,age,grade): super().__init__(name,age) self._grade=grade @property def grade(self): return self._grade @grade.setter def grade(self,grade): self._grade=grade def study(self,course): print("%s的%s正在学习%s"%(self._grade,self._name,course)) class Teacher(Person): ''' 教师 ''' def __init__(self,name,age,title): super().__init__(name,age) self._title=title @property def title(self): return self._title @title.setter def title(self,title): self._title=title def teach(self,course): print("%s%s正在讲%s"%(self._name,self._title,course)) def main(): stu=Student('王二',15,'初三') stu.study('数学') stu.watch_av() t=Teacher('李三',40,'儿科') t.teach('PYTHon') t.watch_av() if __name__=='__main__': main()
92f04cb2fe1843b96c6d328c5b1ce5ad84baf36e
xikunqu/Python_100_days
/D1-15/Day7/eg9.py
877
3.75
4
def main(): scores={'打开':90,'快点':100,"啥的":93} #通过键可以获取字典中对应的值 print(scores['打开']) print(scores['快点']) #对字典进行遍历(遍历的其实是键,再通过键取对应的值) for elem in scores: print(elem,scores[elem]) #更新字典中的元素 scores['打开']=000 scores['时间']=111 scores.update(冷面=670,放=85) print(scores) if 'jdj ' in scores: print(scores['jdj']) print(scores.get('快点')) #get方法也是通过键获取对应的值但是可以设置默认值 print(scores.get('解决',90)) print(scores) #删除字典中的元素 print(scores.popitem()) print(scores.popitem()) print(scores.pop('时间',100)) #清空字典 scores.clear() print(scores) if __name__=="__main__": main()
34fa3ca34fb36f36c4f302440668cf73ed1be46a
xikunqu/Python_100_days
/D1-15/Day4/sushu.py
269
3.78125
4
""" 输入一个正整数判断它是不是素数 """ sushu=int(input("请输入一个正整数:")) if sushu<=2: print("yes") else: for i in range(2,sushu): if sushu%i==0: print("no") else: continue print("yes")
e6232503779d8a20aa017aeb724f87c1af80af89
xikunqu/Python_100_days
/D16-20/Day16/shunxu.py
541
3.71875
4
# 最基本的查找算法, # 基本原理: # 对于任意一个序列以及一个给定元素,将给定元素与序列中元素依次比较,直到找出与给定关键字相同的数为止 import random Range = 10 Length = 5 flag = 0 pos = -1 list = random.sample(range(Range),Length) goal = random.randint(0,Range) print('search ',goal,', in list:',list) for i in range(Length): if list[i] == goal: flag = 1 pos = i break if flag: print('find in ',pos+1,'th place') else: print('not found')
e099eb53ffbcf76cd851e2c4c02ba8ee6963658b
xikunqu/Python_100_days
/D1-15/Day5/craps.py
846
3.84375
4
''' Craps赌博游戏 规则:玩家掷两个骰子,每个骰子点数为1-6,如果第一次点数和为7或11,则玩家胜;如果点数和为2、3或12,则玩家输庄家胜。 若和为其他点数,则记录第一次的点数和,玩家继续掷骰子,直至点数和等于第一次掷出的点数和则玩家胜;若掷出的点数和为7则庄家胜。 ''' import random x=random.randint(1,6) y=random.randint(1,6) print(x,y) z=x+y if z==7 or z==11: print("玩家赢") elif z==2 or z==3 or z==12: print("庄家赢") else: while True: x=random.randint(1,6) y=random.randint(1,6) if x+y==z: print(x,y) print("玩家赢") break elif x+y==7: print(x,y) print("庄家赢") break else: continue
036b7df8daa0bb9703c03fc2b2662bfce9600731
sbd2309/PythonScripts
/exception_handling.py
1,106
3.515625
4
class eh1: def __init__(self): pass def texecption(self,l1): try: for i in l1: print (i**2) except: print ('Exception Cached!') else: print ('You provided a Integer list !') finally: print ('I will run at any cost!') def texecption1(self,x,y): try: z=x/y except: print ('Value of y is {}'.format(y)) else: print ('Value of y is {}'.format(y)) finally: print ('We are over now.') def texecption2(self, n): while True: try: print (n**n) except: print ('Entered number must be a digit!') else: print ('Exceuted as the enterted number is a digit') break finally: print ('Another Chance...or may be you are correct!') break i_eh1=eh1() #i_eh1.texecption(['a','b','c']) #i_eh1.texecption1(5,0) i_eh1.texecption2(input('Enter a number'))
529e413dac53477d0313855306ba2406ff20693b
timhowes97/Algorthmic-Trading-Project
/trading/process.py
6,894
3.875
4
# Functions to process transactions. import numpy as np def log_transaction(transaction_type, date, stock, number_of_shares, price, fees, ledger_file): ''' Record a transaction in the file ledger_file. If the file doesn't exist, create it. Input: transaction_type (str): 'buy' or 'sell' date (int): the date of the transaction (nb of days since day 0) stock (int): the stock we buy or sell (the column index in the data array) number_of_shares (int): the number of shares bought or sold price (float): the price of a share at the time of the transaction fees (float): transaction fees (fixed amount per transaction, independent of the number of shares) ledger_file (str): path to the ledger file Output: returns None. Writes one line in the ledger file to record a transaction with the input information. This should also include the total amount of money spent (negative) or earned (positive) in the transaction, including fees, at the end of the line. All amounts should be reported with 2 decimal digits. Example: Log a purchase of 10 shares for stock number 2, on day 5. Share price is 100, fees are 50. Writes the following line in 'ledger.txt': buy,5,2,10,100.00,-1050.00 >>> log_transaction('buy', 5, 2, 10, 100, 50, 'ledger.txt') ''' # log transaction if we buy if transaction_type == 'buy': # how much do we spend amount_spent = - (number_of_shares * price) - fees # first open the ledger_file, if it does not exist we create a new empty file # use 'a' as second argument as we wish to append to the file (creates and append if it doesn't exist) file = open(ledger_file, 'a') # now append the contents to the file file.write(f'{transaction_type}, {date}, {stock}, {number_of_shares}, {price}, {fees}, {amount_spent} \n') #close the file to any more changes file.close() # log transaction if we sell elif transaction_type == 'sell': # if we have 0 stocks to sell we do nothing if number_of_shares > 0: # how much do we earn amount_spent = number_of_shares * price - fees # first open the ledger_file, if it does not exist we create a new empty file # use 'a' as second argument as we wish to append to the file (create and append if it doesn't exist) file = open(ledger_file, 'a') # now append the contents to the file file.write(f'{transaction_type}, {date}, {stock}, {number_of_shares}, {price}, {fees}, {amount_spent} \n') #close the file to any more changes file.close() def buy(date, stock, available_capital, stock_prices, fees, portfolio, ledger_file): ''' Buy shares of a given stock, with a certain amount of money available. Updates portfolio in-place, logs transaction in ledger. Input: date (int): the date of the transaction (nb of days since day 0) stock (int): the stock we want to buy available_capital (float): the total (maximum) amount to spend, this must also cover fees stock_prices (ndarray): the stock price data fees (float): total transaction fees (fixed amount per transaction) portfolio (list): our current portfolio ledger_file (str): path to the ledger file Output: None Example: Spend at most 1000 to buy shares of stock 7 on day 21, with fees 30: >>> buy(21, 7, 1000, sim_data, 30, portfolio) ''' # if the price is NaN we do not buy if np.isnan(stock_prices[date, stock]) == False: # see how many shares we can buy with available amount minus fees available_stock_to_buy = np.floor((available_capital - fees) / stock_prices[date, stock]) # buy this amount and change in portfolio portfolio[stock] += available_stock_to_buy # log in the ledger log_transaction('buy', date, stock, available_stock_to_buy, stock_prices[date, stock], fees, ledger_file) # if price is NaN, set set our shares for this stock to 0 else: portfolio[stock] = 0 def sell(date, stock, stock_prices, fees, portfolio, ledger_file): ''' Sell all shares of a given stock. Updates portfolio in-place, logs transaction in ledger. Input: date (int): the date of the transaction (nb of days since day 0) stock (int): the stock we want to sell stock_prices (ndarray): the stock price data fees (float): transaction fees (fixed amount per transaction) portfolio (list): our current portfolio ledger_file (str): path to the ledger file Output: None Example: To sell all our shares of stock 1 on day 8, with fees 20: >>> sell(8, 1, sim_data, 20, portfolio) ''' # if stock price is NaN we have no stock to sell if np.isnan(stock_prices[date, stock]) == False: # first we log the transaction in the ledger log_transaction('sell', date, stock, portfolio[stock], stock_prices[date, stock], fees, ledger_file) # now we change the portfolio according to what stock we want to sell, selling all of this stock portfolio[stock] = 0 # if price is NaN, set number of shares of this stock to 0 else: portfolio[stock] = 0 def create_portfolio(available_amounts, stock_prices, fees, ledger_file): ''' Create a portfolio by buying a given number of shares of each stock. Input: available_amounts (list): how much money we allocate to the initial purchase for each stock (this should cover fees) stock_prices (ndarray): the stock price data fees (float): transaction fees (fixed amount per transaction) Output: portfolio (list): our initial portfolio Example: Spend 1000 for each stock (including 40 fees for each purchase): >>> N = sim_data.shape[1] >>> portfolio = create_portfolio([1000] * N, sim_data, 40) ''' # convert available_amounts to array available_amounts = np.array(available_amounts) # how many stocks in our portfolio N = stock_prices.shape[1] # we create this portfolio on day 0 start_date = 0 # initialize portfolio portfolio = np.zeros(N) # loop through each stock to buy for stock in range(N): # buy stock using the buy function buy(start_date, stock, available_amounts[stock], stock_prices, fees, portfolio, ledger_file) # return the initial portfolio with integer values return list(map(int, portfolio))
678c18fff74eb1cafff043b97706652f1a7e7bdf
neha-sharmaa/python-practice
/string.py
321
3.546875
4
m1= int(input("Enter the subject marks of 1: ")) m2= int(input("Enter the subject marks of 2: ")) m3= int(input("Enter the subject marks of 3: ")) m4= int(input("Enter the subject marks of 4: ")) m5= int(input("Enter the subject marks of 5: ")) Stud_detail= [m1,m2,m3,m4,m5] Stud_detail.sort() print(Stud_detail)
b6d8425ebaf8a44be56392cd83297a3873b5dfc7
neha-sharmaa/python-practice
/fundefine_recursion.py
266
3.875
4
'''def greet(name): print ("Good day" + name) name = input("enter the name of the person:\n") greet(str(name)) ''' def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n-1) f = factorial(4) print(f)
c62774b8031be5df01913747547aa431a45b053a
neha-sharmaa/python-practice
/p_02probifelse.py
317
3.84375
4
a = int(input("enter three subjects marks by user\n")) b = int(input("enter three subjects marks by user\n")) c = int(input("enter three subjects marks by user\n")) total = a+b+c percentage = (total*100)/300 print(percentage) if(percentage>40): print("promoted to next class") else: print("failed")
77fa7870540d75ec87bb6058f71fdca0e27e2bc6
utahkay/PyHangman
/hangman/hangman.py
1,711
3.65625
4
import random import string import pkg_resources class Hangman: def __init__(self, words=None): self._words = words or self._load_words() self._secret_word = self._pick_word() self._picked = set() self._guess = [None] * len(self._secret_word) def _load_words(self): # filename = 'sowpods.txt' # with open(filename, 'r') as f: with pkg_resources.resource_stream(__name__, 'sowpods.txt') as f: words = [line.strip() for line in f.readlines()] return words def _pick_word(self): return random.choice(self._words) def is_valid_letter(self, letter): return len(letter) == 1 and letter in string.ascii_uppercase def is_already_guessed(self, letter): return letter in self._picked def guess_letter(self, letter): self._picked.add(letter) def discards(self): return ''.join((sorted(letter for letter in self._picked if letter not in self._secret_word))) def current_guess(self): guess = [letter if letter in self._picked else '_' for letter in self._secret_word] return ' '.join(guess) def is_solved(self): return not any(c == '_' for c in self.current_guess()) def main(): h = Hangman() while True: print(h.current_guess()) print(h.discards()) if h.is_solved(): break letter = input("Pick a letter: ") if not h.is_valid_letter(letter) or h.is_already_guessed(letter): print("Pick exactly one new letter please") continue h.guess_letter(letter) if __name__ == '__main__': main()
0f8b93e1bad61202138282fedebaad0476e7a6a6
amtesire/Password-Locker
/password.py
375
3.625
4
import pyperclip class User: ''' Class to create user accounts and save their details ''' def __init__(self,first_name,last_name,password): self.first_name = first_name self.last_name = last_name self.password = password users_list = [] def save_user(self): ''' Method to save a newly created user into users_list. ''' User.users_list.append(self)
c601cf9e1982c41703fd00cc7f4127d558564108
visnutharssini/visnutharssini
/rotation.py
390
3.671875
4
#python code goes here #python version :3 n = int(input("Enter the number of elements :")) k = int(input("Enter No. of rotations : ")) array = [] new_array = [] for i in range(n): array.append(int(input())) while k>0: for i in range(n): new_array.append(array[i-1]) for i in range(n): array[i] = new_array[i] new_array.clear() k=k-1; print(array)
bafb6f774e277613bf3f2724b28b9ef44af83149
visnutharssini/visnutharssini
/happynum.py
404
3.71875
4
num = int(input("Enter the number : ")) k = x = num sum = 0; def split(x): new_array = [] while(x>0): new_array.append(x%10) x = int(x/10) return new_array new_array = split(x); for i in range(len(new_array)): sum += new_array[i]**2 k = sum; if(k == 1): print("%d is a Happy Number" % num); else: print("%d is not a Happy Number"%num);
05d790c3ee830dbfd6c149e3b74977ffe28bd6ec
ldt2g10/Python-Games
/mathgame.py
677
3.859375
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 04 16:02:50 2015 @author: Luke """ print "Welcome to Luke's game" print """This is a numbers game, can you do the math? \n Please enter the correct answer to the following questions when prompted.""" print"----------------------------------------------------------" print "The Game Begins Now:" print "What is 2 + 2:" answer = raw_input(">") if answer == "4": print "You are good at math. Well done asshole!" elif answer == "Window": print "nice one smarty pants! I knew that joke in 5th grade" else: print """Wrong!!!!! HAHAAHAHAHAHA YOU are an idiot... please go back to school """
03b9daaadad152f6241dbea8ef5cb087884bcf8f
GlebKulikov/Echo-Server
/echo client.py
1,451
3.53125
4
import socket, getpass def connect(ip, port): sock = socket.socket() sock.settimeout(1) print("Connecting to the server...") try: sock.connect((ip, port)) except ConnectionRefusedError as err: print(err) return False except TypeError: return False print("Connection accept") while True: try: data = sock.recv(1024) except socket.timeout: break print("Message received") print(data.decode()) while True: msg = input("Typing a message to server >>> ") print("\nSending data...") sock.send(msg.encode()) if msg == "exit": break try: data = sock.recv(1024) except socket.timeout: continue print("Message received") print(data.decode()) sock.close() return True ip = getpass.getpass(prompt = "Write the ip address >>> ") if ip == "": ip = "127.0.0.1" port = getpass.getpass(prompt = "Write the port >>> ") if port == "": port = 12345 else: try: port = int(port) except: print("Incorrect port") logical = False connCount = 0 while not logical and connCount<5: logical = connect(ip, port) if not logical: connCount += 1 else: connCount=0 if connCount==5: print('Server close. Was 5 attempt to connect')
0e984975c0d8fb572a673166385a48c9ed14ae7d
JohnErnestBonanno/Turtles
/TurtleExplo.py
634
4.15625
4
#https://www.youtube.com/watch?v=JQPUS1nv5F8&t=970s #Import Statement import turtle my_turtle = turtle.Turtle() #set speed my_turtle.speed(2) """ distance = 100 #move turtle in a square #def square(distance): for x in range(0,4): my_turtle.fd(distance) my_turtle.rt(90) my_turtle.circle(100) my_turtle.stamp() """ """ #increasing spiral distance = 10 for x in range(0,50): my_turtle.fd(distance) my_turtle.rt(90) distance += 3 """ #fill in the box turtle.title("My Turtle") distance = 50 while distance > 0: my_turtle.fd(distance) my_turtle.rt(50) distance = distance - 1 turtle.exitonclick()
a0b8b2092fcb83df000f9160045f40418c56a327
velzepooz/cs50
/pset6/cash.py
343
3.546875
4
from cs50 import get_float while True: change = get_float("Change owed: ") if change > 0: break coins = round(change * 100) while coins >= 0: quarter = coins/25 dime = (coins % 25)/10 nickel = ((coins % 25) % 10)/5 penny = (((coins % 25) % 10) % 5)/1 break print(f"{int(quarter + nickel + penny + dime)}")
1dd556be8d5d8050183fd752ecd2505991332279
EliadCohen/email_histogram
/email_histogram.py
1,045
3.71875
4
#!/usr/bin/env python import re #generate_froms_array reads a file and picks lines where the word "From" starts the string def generate_froms_array(filename="mbox-short.txt"): email_file=open(filename,"r") all_lines=email_file.readlines() email_file.close() froms=[] for line in all_lines: if line.startswith("From "): froms.append(line) return froms def generate_time_array(froms): times=[] regex=re.compile(r'([01]?[0-9]|2[0-3]):[0-5][0-9]') for entry in froms: match=regex.findall(entry) times.append(match[0]) return times def generate_histogram_list(bins,time_array): hist={} for bin in bins: hist[bin]=time_array.count(bin) return hist filename="mbox-short.txt" froms_list=generate_froms_array(filename) #print(froms_list) time_array=generate_time_array(froms_list) bins=set(time_array) histogram=generate_histogram_list(bins,time_array) histogram_items=histogram.items() histogram_items=sorted(histogram_items) print(histogram_items)
91e6481ba14f1e2aa54b871901e98e602dd97ae8
yixiaoyx/acm_training
/w1/qa1.py
143
3.5
4
#!/usr/bin/env python3.5 import re s = input() r = re.findall(r'\d+', s) r = [int(i) for i in r] r.sort() #print(r) print(int(r[2])-int(r[0]))
8a5a6168e673555b89931f52a2920c133656cc8d
zionapril/01_Recipe_Moderniser
/01_not_blank_checker.py
397
3.828125
4
# Get's recipe name and checks it is not blank # Not Blank Function goes here def not_blank(question): valid = False while not valid: response = input(question) if response == "": continue else: return response # Main Routine goes here recipe_name = not_blank("What is the recipe name? ") print("You are making {}".format(recipe_name))
1fbc2f477a399631e990ce8b6a4c010c5a9477c6
BasileiosKal/TensorGUI
/GraphsUtils.py
3,585
3.859375
4
from math import sin, cos, radians import numpy as np from tkinter import * def sigmoid(x): return 1/(1+np.exp(-x)) def scaling(x, max_size): print("SCALING ERROR ---->> ", x) if int(x) < max_size*(4/5): return int(x)*2 else: return max_size*(4/5) + max_size*(1/5)*sigmoid(int(x)) def paint_rectangle_layer(working_canvas, name, activation, size, scaled_size, x_coordinate, config_window, canvas_colour_config): """paint in the canvas a rectangle that will correspond to a dense or flatten layer. Each rectangle will have text above it with the name and dimension of the layer. """ y_middle = 350 y_start = y_middle - (scaled_size / 2) y_end = y_middle + (scaled_size / 2) Layer_rectangle = working_canvas.create_rectangle(x_coordinate, y_start, x_coordinate + 40, y_end, **canvas_colour_config["rectangle_layer"]) working_canvas.tag_bind(Layer_rectangle, "<Button-1>", config_window) working_canvas.move(Layer_rectangle, 0, 0) # Labels working_canvas.create_text(x_coordinate + 20, y_start - 25, **canvas_colour_config["text"], text="{" + name) working_canvas.create_text(x_coordinate + 20, y_start - 10, **canvas_colour_config["text"], text=" size: " + str(size) + "}") # Arrows working_canvas.create_text(x_coordinate+72, y_middle-10, text=activation, **canvas_colour_config["text"]) working_canvas.create_line(x_coordinate+50, y_middle, x_coordinate+100, y_middle, arrow=LAST, **canvas_colour_config["text"]) return Layer_rectangle def draw_convolution_layer(working_canvas, layer_config, middle, r, theta, alpha, beta, config_window, canvas_colour): rads = radians(theta) rads_2 = radians(90-theta) d = r*sin(rads) d_2 = r*sin(rads_2) t = r*cos(rads) t_2 = r*cos(rads_2) # Points x = middle[0] - t - alpha + d_2 - (r/2)*cos(rads) y = middle[1] - (beta/2) + (r/2)*sin(rads) A = (x+t, y-d) B = (A[0]+alpha, A[1]) G = (B[0], B[1]+beta) D = (G[0]-d_2, G[1]+t_2) F = (D[0], D[1]-beta) Conv2D_colours = canvas_colour["Conv2D"] # the sides of the cube polygon = working_canvas.create_polygon(x, y, *A, *B, *G, *D, *F, fill=Conv2D_colours["side"], outline=Conv2D_colours["lines"]) working_canvas.create_line(*F, *B, fill=Conv2D_colours["lines"]) # the rectangle of the front rectangle = working_canvas.create_rectangle(x, y, *D, fill=Conv2D_colours["front"], outline=Conv2D_colours["lines"]) # Bind the rectangle shape to open the configure window working_canvas.tag_bind(polygon, "<Button-1>", config_window) working_canvas.tag_bind(rectangle, "<Button-1>", config_window) # the arrow in front of the cube P1 = middle arrow_length = 50 dist_from_layer = 40 working_canvas.create_line(P1[0] + dist_from_layer, P1[1], P1[0] + dist_from_layer + arrow_length, P1[1], fill=Conv2D_colours["arrow"], arrow=LAST) shape = layer_config["shape"] # Labels working_canvas.create_text(x + t + 20, y - d - 40, **canvas_colour["text"], text="{" + layer_config["name"]) working_canvas.create_text(x + t + 20, y - d - 20, **canvas_colour["text"], text=" size: " + str(shape) + "}")
a4012048e689d6739943728336d07414c7540b0b
luccaplima/estudandoPython
/variaveis.py
2,488
4.71875
5
#estudando variaveis python """ python não necessita de um comando para declarar a variavel uma variavel é criada no momento que um valor é associado a ela uma variavel não precisa ser declarada como um tipo particular e seu tipo pode ser trocado posteriormente O nome de uma variável em python pode ser curto (como x e y) ou pode ser mais descritivo (como idade, nome, curso) Regras para variáveis em Python: 1- O nome de uma variável pode começar com uma letra ou com o caractere underscore ("_") 2- O nome de uma variável não pode começar com um número 3- O nome de uma variável só pode conter caracteres alfa numéricos e underscores 4- Nomes de variável são case-sensitive(idade é diferente de IDADE que é diferente de Idade) """ x=2136 #x é int x=23.50 #x agora é float y="Lucca" #y é string z=2.50 #z é float k=["Lucca", "João", "Matheus"] #k é list aux=[x, y, z] #criando list com as variáveis criadas anteriormente X = "Teste Case-Sensitive" print(x,X) #nomes de váriaveis em python são case-sensitive A, B, C = 'anel', 'bola', 7 #o python deixa associar valores a multiplas variáveis em apenas uma linha print(A, B, C) print(x) print(y) print(z) print(k) print(aux) """ se é necessário especificar o tipo de dado de uma variável, isto pode ser feito com casting """ x1=str('Exemplo') #definindo x1 como string x2=int(3) #definindo x2 como int x3=float(37.5) #definindo x3 como float x4=list(["Elemento1", "Elemento2", "Elemento3"]) #definindo x4 como lista print(x1, x2, x3, x4) """ o tipo de dados de uma variavel pode ser obtido através da funçao type() """ print(type(x1)) print(type(x2)) print(type(x3)) print(type(x4)) """ Variáveis que são criadas fora de uma função são consideradas váriaveis globais e podem ser utilizadas dentro ou fora de funções Uma variável global pode ser criada dentro de uma função utilizando a palavra-chave global """ var1='Python é' var2='uma linguagem de programação interessante!' #var1 e var2 são variáveis globais def myfunc(): #função que utiliza as variáveis globais print(var1+var2) myfunc() #retornar a função """ Python data-types: texto - str numericos- int, float, complex tipos de sequencia - list, tuple, range tipos mapping - dict tipos set - set, frozenset tipo boolean - bool tipos binarios - bytes, bytearray, memoryview """
2f3e9a3344a445cbb2b8b6f3e5bdfa4e42dbae49
Myoung-heeSeo/SoftwareProject2-KMU-2017
/assignment2.py
416
3.875
4
while (True): num= int(input("Enter a number:")) # 숫자입력받기 if num==-1: #-1을 넣으면 프로그램이 꺼짐 break elif num<0: #음수일 때 예외처리 print("다시 입력하세요") else: fac=1 for i in range(1, num+1): #팩토리얼 계산 루프문 fac=i*fac print(str(num)+"!="+str(fac))
d2e557bedb148396c122c2a0ea3bf859498b533c
kqt717/python
/9.py
180
3.515625
4
#!/usr/bin/python #coding:utf-8 ''' 题目:暂停一秒输出。 ''' import time myD = {1:'a', 2:'b'} for key,value in dict.items(myD): print key, value time.sleep(1)
95521502746c732e4de529c3b7690c0c2c05a217
LamElvis/Guess-Number
/num.py
456
4.03125
4
import random start = input('Please input Start number: ') end = input('Please input End number: ') start = int(start) end = int(end) r = random.randint(start,end) count = 0 while True: count += 1 #count = count + 1 num = input('Please enter a number: ') num = int(num) if num == r: print('You win') break elif num > r: print('Your number is Bigger') elif num < r: print('Your number is Smaller') print('This is your ', count, ' time')
562dabe9c16630b4383ab841fdfbf32b23b85524
coding-with-fun/Python-Lectures
/Lec 4/Task/dictTrial.py
363
3.84375
4
""" stu = {'12':{'Roll no':'12', 'Name':'Harsh', 'Marks':'23'}} """ roll_no = {} marks = {} name = {} stud = {} cnt = 1 i = str(cnt) roll_no[i] = input("Enter roll no: ") marks[i] = int(input("Enter marks: ")) name[i] = input("Enter name: ") stud[roll_no[i]] = {roll_no[i]: {"Roll No": roll_no[i], "Marks": marks[i], "Name": name[i]}} print(stud[roll_no[i]])
97128f21e73b655557a2dee31dc5610b40b6011a
coding-with-fun/Python-Lectures
/Lec 7/Types of UDF.py
2,476
4.875
5
# Function Arguments: # 1) Required arguments # 2) Keyword arguments # 3) Default arguments # 4) Variable-length arguments # 5) Dictionary arguments # 1) Required arguments: # Required arguments are the arguments passed to a function in correct positional order. # Here, the number of arguments in the function call should match exactly with the function definition. def fn1(a): print (a) fn1("Hello World") #Output:Hello World # 2) Keyword arguments: # Keyword arguments are related to the function calls. # When you use keyword arguments in a function call, # the caller identifies the arguments by the parameter name. def fn2(str): print str fn2(str="Good Evening") #Output:Good Evening # 3) Default arguments: # A default argument is an argument that assumes a default value # if a value is not provided in the function call for that argument,it prints default value if it is not passed def fn3(name,marks=35): print "Name=",name print "Marks=",marks fn3(marks=50,name="XYZ") #Output: # Name=XYZ # Marks=50 fn3(name="ABC") #Output: # Name=ABC # Marks=35 # 4) Variable-length arguments # You may need to process a function for more arguments than you specified while defining the function. # These arguments are called variable-length arguments and are not given in the function definition, # An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. # This tuple remains empty if no additional arguments are specified during the function call. def fn4(arg1,*tuplevar): print "arg1=",arg1 for var in tuplevar: print "tuple=",var fn4(50) #Output:50 fn4(60,70,"Hello") #Output: # 60 # 70 # Hello # 5) Dictionary arguments # #A keyword argument is where you provide a name to the variable as you pass it into the function. # #One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. # #That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out. def fn5(**kwargs): if kwargs is not None: for key,value in kwargs.items(): print("%s = %s" %(key, value)) fn5(fn='Abc',ln='Def') #Output: # fn=Abc # ln=Def
aac2010b083f2a082b15cd18b24e25b1ae33f119
coding-with-fun/Python-Lectures
/Lec 3/Task/My work/tupleSpacing.py
835
4
4
tup = (1, 1, "Asit", 'N', 45.5, "Harshal", (1, 1, "Asit", "Harshal", 'N', 45.5, 45.5), "Harsh") for i in tup: if type(i) == int: print("Integer value: ", i) elif type(i) == float: print(" Float value: ", i) elif type(i) == str: print(" String value: ", i) else: print("--------------------------------------------------------------------") print("Starting of nested tuple.") for j in i: if type(j) == int: print("Integer value: ", j) elif type(j) == float: print(" Float value: ", j) elif type(j) == str: print(" String value: ", j) print("End of nested tuple.") print("--------------------------------------------------------------------")
17e3ac6e070a0e0acb70447582202642b434fbb4
lizuofeng/algorithm
/sort_algorithm/selection_sort.py
579
3.96875
4
# -*- encoding: utf-8 -*- """ :author: zfli :date: 2019/12/24 """ # 选择排序 def selection_sort(lst): """ 时间复杂度:好:O(n²) 均:O(n²) 坏:O(n²) 空间复杂度:O(1) 稳定性:不稳定 """ for i in range(len(lst)): minimum = i for j in range(i + 1, len(lst)): if lst[j] < lst[minimum]: minimum = j lst[i], lst[minimum] = lst[minimum], lst[i] if __name__ == '__main__': sort_lst = [1, 3.5, 4, 0.5, -0.3, 2, 2, 0.5, 1] selection_sort(sort_lst) print(sort_lst)
7fcfec8b98de979e0459d4416ed6adba2749616d
mirakl834/AdventOfCode2017
/Day1_Part1.py
415
3.640625
4
# Initializing data input reader inputString = raw_input("Input data please: ") # Initializing the linked list sumNum= 0 count = 0 while count < len(inputString): num1 = int(inputString[count]) if count+1 == len(inputString): numNext = int(inputString[0]) else: numNext = int(inputString[count + 1]) if num1 == numNext: sumNum += num1 count += 1 print(sumNum)
410e663ef379537a20a8020977757db774c04176
wlf5241/learning_python_hardway
/习题40.py
514
3.546875
4
class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print(line) happy_bday = Song(["Happy birthday to you", "I do'nt want to get sued", "So I'll stop right there"]) my_lyrics = ["They rally around the family", "With pockets full of shells" ] bulls_bday_parade = Song(my_lyrics) happy_bday.sing_me_a_song() bulls_bday_parade.sing_me_a_song()
fd8100771d5b5e688a470de173dfe3331facc3a1
guntursandjaya/GunturSandjaya_ITP2017_Exercise
/5-6 Stages of life.py
317
4.15625
4
age = input("Insert age : ") age = int(age) if age<2: print("The person is a baby") elif age>=2 and age<4: print("The person is a kid") elif age>=13 and age<20: print("The person is a teenager") elif age>=20 and age<65: print("The person is a adult") elif age>65: print("The person is an elder")
1b44d5e42a47de35de9b3e6052e845aa220b46ac
guntursandjaya/GunturSandjaya_ITP2017_Exercise
/5-9 No Users.py
265
3.984375
4
names = [] if names: for name in names: if name == "Admin": print("Hello admin,would you like to see a status report?") else: print(name + ",thank you for logging in again.") else: print("We need to find more Users")
5257331115dcbd1896086f317122465bc146b3fe
cfeenstra67/txt_learn
/data_manager.py
1,711
3.53125
4
#!/usr/bin/local/python3 import sqlite3 DATA_FOLDER = 'data' def abs_path(filename): return '%s/%s' % (DATA_FOLDER, filename) DATAFRAME_DEST = 'dataframe.pkl' MODEL_DEST = 'model.pkl' DATABASE_DEST = 'english-text.db' from txt_learn import wrap_str with sqlite3.connect(abs_path(DATABASE_DEST)) as conn: # Managing the Databse curs = conn.cursor() def __maketable(cursor): cursor.execute(""" CREATE TABLE IF NOT EXISTS all_data ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, english INT, content TEXT ) """) __maketable(curs) def run_query(query, vals=None, quiet=False): try: if vals: curs.execute(query, vals) else: curs.execute(query) except: if not quiet: print('Query Failed: %s' % query) def add_text_samples(*args, quiet=False): """ Adds rows w/ values provided in each argument, 3-tuple formatted as (name, english, content) """ for name, english, content in args: run_query(""" INSERT INTO all_data (name, english, content) VALUES (?,?,?) """, (wrap_str(name), int(english), wrap_str(content)), quiet=quiet) conn.commit() def add_text_sample(name,english,content, quiet=False): """ Add a single row w/ values provided """ add_text_samples((name,english,content), quiet=quiet) def get_all_samples(fields='*', quiet=False): """ Retrieve all rows of the table. May specify a string to use for as indexes i.e. (name, english, content) """ run_query(""" SELECT %s FROM all_data """ % fields, quiet=quiet) return curs.fetchall() def clear_all_samples(quiet=False): """ Clear all samples currently held in database """ run_query(""" DELETE FROM all_data """, quiet=quiet) conn.commit()
7ccc9cd8d40842c8f2f2a8311973393ad7c33f79
Timofeitsi/Repo_dz
/lesson3/less3_2.py
2,212
4
4
""" Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой. """ def my_f1(**kwargs): global my_dict my_dict = kwargs return (kwargs) name = input('введите имя пользователя - ') surname = input('введите фамилию пользователя - ') year = input('введите год рождения пользователя - ') sity = input('введите город проживания пользователя - ') email = input('введите адрес эл.почты пользователя - ') phone = input('введите телефон пользователя - ') print(f'Данные пользователя - {my_f1(Имя=name, Фамилия=surname, Год_рождения=year, Город_проживания=sity, Email=email, Телефон=phone)}\n') for key in my_dict: print(f'{key}: {my_dict[key]}',end=", ") #------------Второй вариант def my_f2(): name = input('введите имя пользователя - ') surname = input('введите фамилию пользователя - ') year = input('введите год рождения пользователя - ') sity = input('введите город проживания пользователя - ') email = input('введите адрес эл.почты пользователя - ') phone = input('введите телефон пользователя - ') my_dict = {"Имя": name, "Фамилия": surname, "Год_рождения": year, "Город_проживания": sity, "Email": email, "Телефон": phone} print('Данные пользователя:') for key in my_dict: print(f'{key}: {my_dict[key]}', end=", ") return print(my_f2())
7528f5ce3093e4a5562dd9a4d87937c69edc539d
Timofeitsi/Repo_dz
/lesson5/less5_3.py
921
3.578125
4
''' Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников. ''' less5_3 = open("text_3.txt", "r", encoding="utf-8") list =[] itog = 0 for line in less5_3: summa = float(line.split(" ")[1].replace('\n', '')) name = (line.split(" ")[0]) data = {name: summa} list.append(data) itog = itog + summa if summa < 20000.0: print(f'{name} имеет оклад менее 20000') print(list) print(f'{itog/len(list)} тугриков средняя величина дохода') less5_3.close()
11fe73c369e3de81d8a95cef024dcf19041c70bd
Timofeitsi/Repo_dz
/lesson2/less2_3_1.py
528
3.734375
4
my_list = [[12, 1, 2], [4, 5, 3], [7, 8, 6], [10, 11, 9]] a = int(input("Введите порядковый номер месяца - ")) for i in range(len(my_list)): if my_list[i].count(a): if i == 0: print("Зима") break elif i == 1: print("Весна") break elif i == 2: print("Лето") break elif i == 3: print("Осень") break else: print("нет такого месяца")
d61693097552a7223a11a3b81aaa5c2526840044
Timofeitsi/Repo_dz
/lesson3/less3_6.py
2,170
3.546875
4
""" Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func(). """ # ----- Мне кажется получился самый простой вариант который работает и для одного слова и для строка #------ на более сложную конструкцию у меня пока мозгов не хватает def int_func(): while True: str = input('введите слово, состоящее из маленьких латинских букв - ') str_ = str.replace(" ","") #Добавил код убирающий все пробелы в строке, появилась возможность несколько слов сразу вводить lat_Lower = set('abcdefghijklmnopqrstuvwxyz') #Для проверки корректности ввода можно было предыдущую строку не добавлять а к буквам пробел добавить if ((set(str_) - lat_Lower)) == set(): print(f'Начальный текст - {str}') break else: print("введенное слово содержит некорректные символы,\nпожалуйста, попробуйте еще раз") continue return (f'Слова с заглавных букв - {(str.title())}') print(int_func())
ea5ec5c939042da78f027466057174d704b3308d
rfpoulos/python-exercises
/2.1.18/word_summary.py
975
4.0625
4
def histograham(): words_or_letters = raw_input("Would you like to count word's or letters? (w / l): ") if words_or_letters == "w": user_input = raw_input("What word's would you like to count?: ") user_list = user_input.split(" ") else: user_input = raw_input("What word would you like to letter count?: ") user_list = list(user_input) letters_dict = {} for i in range(len(user_list)): if user_list[i] in letters_dict: letters_dict[user_list[i]] += 1 else: letters_dict[user_list[i]] = 1 print letters_dict dict_keys = letters_dict.keys() dict_values = letters_dict.values() list_tuples = [] for i in range(len(dict_keys)): list_tuples.append((dict_keys[i], letters_dict[dict_keys[i]])) sorted_frequency = sorted(list_tuples, key=lambda occurance: occurance[1], reverse=True) print sorted_frequency print sorted_frequency[:3] histograham()
0bdd0d5acbe261113fe3ff023be27216a3aad75b
rfpoulos/python-exercises
/1.31.18/blastoff.py
287
4.125
4
import time numbers = int(raw_input("How many numbers should we count down?: ")) text = raw_input("What should we say when we finish out countdown?: ") for i in range(0, numbers + 1): if numbers - i == 0: print text else: print numbers - i time.sleep(1)
a2acc5778a677f03e5474f25b9750224c509b316
rfpoulos/python-exercises
/1.30.18/name.py
509
4.5
4
first_name = raw_input('What is your first name? ') last_name = raw_input('%s! What is your last name? ' % first_name) full_name = '%s %s' % (first_name, last_name) print full_name #Below is a qualitative analysis if first_name == 'Rachel': print "That's a great name!" elif first_name == 'Rachael': print "That's the devil's spelling. . ." else: print "That's a fine name, but not the BEST name." print (full_name.upper() + "! Your full name is " + str(len(full_name)) + " character's long")
4178907191d3f725d6afccdccfbc732911795e08
rfpoulos/python-exercises
/2.1.18/smallest.py
119
3.53125
4
def smallest(numbers): sorted_numbers = sorted(numbers) return sorted_numbers[0] print smallest([5, 1 , 3, 4])
85ff20e6227089fc6a39a189aaf2ce2e5f51aaa9
Nidhintsajee/Bitmanipulation-codes
/lsb.py
171
4.0625
4
#program to read an integer from the keyboard and print the value of its LSB, part2 question f) a=input("Enter binary number:") print("Value of value of LSB: "+str(a&1))
c1d447a84c7e1495e8069b53f961c8c94bf30e46
CodecoolGlobal/lightweight-erp-python-sudocrem
/hr/hr.py
4,037
3.546875
4
""" Human resources module Data table structure: * id (string): Unique and random generated identifier at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters) * name (string) * birth_year (number) """ # everything you'll need is imported: # User interface module import ui # data manager module import data_manager # common module import common TITLES = ['Name', 'Birth year'] NAME, BIRTH = (1, 2) def start_module(): """ Starts this module and displays its menu. * User can access default special features from here. * User can go back to main menu from here. Returns: None """ menu = ['Display table', 'Add', 'Remove', 'Update', 'Oldest person', 'Closest to average age'] file_name = 'hr/persons.csv' while True: table = data_manager.get_table_from_file(file_name) ui.print_menu( 'Human resources manager', menu, 'Go back to main menu') hr_input = ui.get_inputs(["Please enter a number:"], "") if hr_input[0] == '0': return None elif hr_input[0] == '1': show_table(table) elif hr_input[0] == '2': table = add(table) elif hr_input[0] == '3': table = remove(table, ui.get_inputs(['ID'], "Removing")[0]) elif hr_input[0] == '4': table = update(table, ui.get_inputs(['ID'], "Updating")[0]) elif hr_input[0] == '5': ui.print_result(get_oldest_person(table), "They are the oldest") elif hr_input[0] == '6': ui.print_result(get_persons_closest_to_average(table), "They are the closest to average age") data_manager.write_table_to_file(file_name, table) def show_table(table): """ Display a table Args: table (list): list of lists to be displayed. Returns: None """ title_list = ["ID"] + TITLES common.show_table(table, title_list) def add(table): """ Asks user for input and adds it into the table. Args: table (list): table to add new record to Returns: list: Table with a new record """ return common.add(table, TITLES) def remove(table, id_): """ Remove a record with a given id from the table. Args: table (list): table to remove a record from id_ (str): id of a record to be removed Returns: list: Table without specified record. """ return common.remove(table, id_) def update(table, id_): """ Updates specified record in the table. Ask users for new data. Args: table (list): list in which record should be updated id_ (str): id of a record to update Returns: list: table with updated record """ return common.update(table, id_, TITLES) # special functions: # ------------------ def get_oldest_person(table): """ Question: Who is the oldest person? Args: table (list): data table to work on Returns: list: A list of strings (name or names if there are two more with the same value) """ min_birth_year = min(int(person[BIRTH]) for person in table) return [person[NAME] for person in table if int(person[BIRTH]) == min_birth_year] def get_persons_closest_to_average(table): """ Question: Who is the closest to the average age? Args: table (list): data table to work on Returns: list: list of strings (name or names if there are two more with the same value) """ # equivalent to: who's birth year is closest to the average birth year? birth_years = [int(person[BIRTH]) for person in table] average_year = common.average(birth_years) min_dist = min(abs(average_year - int(person[BIRTH])) for person in table) closest_persons_names = [] for person in table: if abs(average_year - int(person[BIRTH])) == min_dist: closest_persons_names.append(person[NAME]) return closest_persons_names
e1ee2de5e97f8a356dca3d6c0c42fb0721c612c6
kojuki/python_intense
/Lesson4.2.py
2,925
3.828125
4
#первые три варианта - встроенная функция max. #первый вариант в функцию передает лист (количество значений не ограничено) def max_func_list (num_list): return max(num_list) #второй использует args (количество значений не ограничено) def max_func_args (*args): return max(args) #третий для трех переменных (будут взяты первые три значения из введеных) def max_func_3_num (num1,num2,num3): return max(num1,num2,num3) #следующие три функции с ручным определением максимального значения. #первый вариант в функцию передает лист (количество значений не ограничено) def manual_max_list (num_list): max = num_list[0] for num in num_list: if num > max : max = num return max #второй использует args (количество значений не ограничено) def manual_max_args (*args): max = args[0] for num in args: if num > max : max = num return max #третий для трех переменных (будут взяты первые три значения из введеных) def manual_max_3_num (num1,num2,num3): max = num1 if num2 > max : max = num2 if num3 > max : max = num3 return max my_num_list = list(map(int, input(f'введите числа (не ограничено по количеству) через запятую: ').split(','))) #можно вводить более 3х чисел print (f'исходный лист:\n{my_num_list}') #исходный лист print(f'встроенная функция max, с передачей листа в кастомную функцию: {max_func_list(my_num_list)}') print(f'встроенная функция max, с передачей args в кастомную функцию: {max_func_args(*my_num_list)}') print(f'встроенная функция max, с передачей первых 3 чисел в кастомную функцию: {max_func_3_num(my_num_list[0],my_num_list[1], my_num_list[2])}') print(f'кастомная функция определения максимального числа, с передачей листа в функцию: {manual_max_list(my_num_list)}') print(f'кастомная функция определения максимального числа, с передачей args в функцию: {manual_max_args(*my_num_list)}') print(f'кастомная функция определения максимального числа, с передачей первых 3 чисел в функцию: {manual_max_3_num(my_num_list[0],my_num_list[1], my_num_list[2])}')
e0fce39d558b799cfff7a5c8c80458265526be4f
GraemeHosford/Crypto-Assignment-01
/CryptoAssn01 - R00147327.py
2,378
3.765625
4
# Name: Graeme Hosford # Student ID: R00147327 from binascii import unhexlify cyphertexts = [ "4F58904A22CEA7704419666992030BDA1B921B70127D473D14CD3421E10B0D12049BA4B68D008AC8D4ED19008CF2E918FF1745B01A3F48DDDCDD0B28450313", "4F5890183386AB230D0B6664DB070CC356891D311529482A16C12866A613071340D4B7ADDF498A8DDBB90F0181F0BA4BFE1602E0103409CF998D072E160D5D0D1633F22E7BABB57E2231671B", "5243D54C2F8FBA231D173325920A43C849891D6546324F780FCD6662E909010F43D4B3A3CE02D98EDABF4A0A94F0A74BE71650F5582310DD9FD902231618150C5F26F5266C", "5A43D54B2F81B96D4419246A8D0143C74FC6047E13314D7816C92D64A605480D4B9AB6E2D900948D95B9054F80E7AC0AE15956F81D660BD58CC50B28", "5355D55C2E9DBA6A0A1B3269824410CF52825365097D4B3403DE2321E70A0C414587F1B5C8499884D9ED01018DE2E91FE55940FC19300D9C91C80F34454C09065F37F83E6FA8FB", "5A109751358AEE6A0A58326D9E440BCF55825378157D5E3710DC2E21F21307414D9AF1B6C50CD98AC0BE024F8DE7E918E55956F81D661BDD85C4003D160B120C0C", "4F589018349AAF7110582963DB100BCB1B95167F1238473B07882967F2010641479BBFB6CC00979B95AC4A1B8AF0E904F85951FF583200D9858D1D3B4F", "4C55D55C2880BA230A1D2361DB0A0C8E5E820672072940370C883164A600070F50D4BFA7C80DD986DAED1E078DE0AE03FE5941FF16321AD3908D003516081C1B1475E72A7BADBA796F", "4C5187183086AF7744113525921043C95489173100325B7803CA356EEA111C04488DF1ACC21D9181DBAA4A1C83ECE902FE5943F7192F06", "52109455679AA666441D2162DB0902C01B921B741F7D482A07883269E3440D0643D4BCA3C349B0C8D4A04A1B8AF0E91CEB1550E50B", "585F985D6781A023051622258F0508CB1B9F1C64147D4B3D11DC6672EE0B1C414891A5E2C00CD99BD0A84A188AF4BD4BF31657E61D660FD388", "4B58904F6788A17144196668920A16DA5EC60779032F4C782B882A6EF510480C5D87B4AECB49B0C8D9A2191BC2F8B018EF1544B013271AD19D8D1E355A051E0C", "1B51D54B378FAD66441932258F0C068E48921263127D413D0ED83521F20C0D414686B4A3C600978F95AA054F86FABE05AA0D4AF558241AD99DC60734514C1A065F31FB3C67", "5F5F901826CEAA66010A6664DB0206C35A8A163102384C2A42DA2778A6054805569BA1E2C20FD98FDAA10E0A8CB5BA1EE4594FF5582748D29DC00B7A5F4C1E081339B42670BDBE6664", "4845984C2F87A0230D166671930143D95A9F53620E3809350DDE2372A6051C155695B2B6DE49948D95A1030487B5A704AA1656F81D3448D588DE4E2E44191849" ] to_decrypt = "4F5890182280A764091966729A1743C75590167F12384D7800D16672E50C01134691A4B18D1A96C8DCB94A1883" def xor_strings(s1: str, s2: str): s1_ord = [] s2_ord = [] res = [] if len(s1) < len(s2): s2 = s2[:len(s1)] else: s1 = s1[:len(s2)] for i in range(len(s1)): s1_ord += [ord(s1[i])] s2_ord += [ord(s2[i])] xor = s1_ord[i] ^ s2_ord[i] # Check within bounds of ASCII uppercase letters if 65 <= xor <= 90: res += [xor] else: # 63 == The ASCII character for a question mark. Using this to fill in empty spaces in output res += [63] print("Result Ordinal") restext = "" for r in res: # Adding an extra space just for formatting restext += chr(r) + " " print("%d, " % r, end="") print("\n") return restext def main(): xor_results = [] main_cipher = str(unhexlify(to_decrypt), "latin_1") for c in cyphertexts: res = xor_strings(main_cipher, str(unhexlify(c), "latin_1")) xor_results.append(res) for x in xor_results: print("\n", x) main()
f47fd9998823803e0b731023430aa0d226b12ca0
ssahussai/Python-control-flow
/exercises/exercise-5.py
824
4.34375
4
# exercise-05 Fibonacci sequence for first 50 terms # Write the code that: # 1. Calculates and prints the first 50 terms of the fibonacci sequence. # 2. Print each term and number as follows: # term: 0 / number: 0 # term: 1 / number: 1 # term: 2 / number: 1 # term: 3 / number: 2 # term: 4 / number: 3 # term: 5 / number: 5 # etc. # Hint: The next number is found by adding the two numbers before it terms = int(input("Enter term:")) n1 = 0 n2 = 1 count = 0 if terms <= 0: print("Enter a positive number!") elif terms == 1: print(f"Fibonacci sequence: {n1}") elif terms < 51: print("Fibonacci sequences:") while count < terms: print(n1) nth = n1 + n2 n1 = n2 = nth count += 1 else: print("This function goes only upto 50 terms!")
d4a4dd99e068910c239d94119bac23744e7e0e8b
AIHackerTest/xinweixu1_Py101-004
/Chap0/project/ex36_number_guess.py
1,899
4.34375
4
#ex 36 # The task of this exercise is to design a number guessing game. import random goal = random.randint(1, 20) n = 10 print ("Please enter an integer from 0 to 20." ) print ("And you have 10 chances to guess the correct number.") guess = int(input ('> ')) while n != 0: if guess == goal: print ("Yes, you win!") exit(0) elif guess < goal: n = n - 1 print ("Your guess is smaller than the correct number.") print (f"You can still try {n} times.") guess = int(input ('> ')) else: n = n - 1 print ("Your guess is larger than the correct number.") print (f"You can still try {n} times.") guess = int(input ('> ')) #Notes on if-statements & loops: # Rules for if-statements: # 1) every if-statement must have an else # 2) if this else should never run because it doesn't make sense, # then you must use a die function in the else that prints out # an error message and dies # 3) never nest if-statements more than two deep # 4) treat if-statements like paragraphs, where if-elif-else grouping # is like a set of sentences. Put blank lines before and after # 5) Your boolean tests should be SIMPLE! # If they are complex, move their calculations to variables earlier in # your function and use a good name for the variable. # Rules for Loops: # 1) use a while loop ONLY to loop forever, and that means probably never... # this only applies to python, other languages might be different # 2) use for-loop for all other kinds of looping, esp. if there is a # fixed or limited number of things to loop over # Tips for debugging: # 1) The best way to debug is to use print to print out the values of # variables at points in the program to see where they go wrong # 2) Do NOT write massive files of code before you try to run them, # code a little, run a little, fix a little.
5bdb9a1f899e939913026e94b520e2c58f2deb77
BrianSChase/Flask_Blog
/create_post.py
889
3.703125
4
"""This will be the function that creates new blog content. it will accept data from the create html page, and then store it in the database.""" from flask import Flask, url_for, render_template, request, redirect import cgi, cgitb import sqlite3 def create_post(): # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields, title and content of blog post title = form.getvalue('title') content = form.getvalue('content') #enter the title and content into database #id for post will also need to be created print("hello from create post\n") print ("Content-type:text/html\r\n\r\n") print ("<html>") print ("<head>") print ("<title>Hello - Second CGI Program</title>") print ("</head>") print ("<body>") print ("<h2>Hello %s %s</h2>") % (title, content) print ("</body>") print ("</html>")
fa69a550806f7cfcbf2fd6d02cbdf443a9e48622
lepperson2000/CSP
/1.3/1.3.7/LEpperson137.py
1,231
4.3125
4
import matplotlib.pyplot as plt import random def days(): '''function explanation: the print will be of the 'MTWRFSS' in front of 'day' and the print will include the 5-7 days of September ''' for day in 'MTWRFSS': print(day + 'day') for day in range(5,8): print('It is the ' + str(day) + 'th of September') plt.ion() # sets "interactive on": figures redrawn when updated def picks(): a = [] # make an empty list a += [random.choice([1,3,10])] plt.hist(a) plt.show() def roll_hundred_pair(): b = [] b += [random.choice([2,4,6])] plt.hist(b) plt.show() def dice(n): number = range(2-12) number += [random.choice(range(2,12))] return dice(n) def hangman_display(guessed, secret): letter = range(1,26) letter += [hangman_display(range(1,26))] return hangman_display(guessed, secret) def matches(ticket, winners): ticket = list[11,12,13,14,15] winners = list[3,8,12,13,17] for ticket in winners: print(matches) def report(guess, secret): color = range(1,4) color += [report(range(1,4))] return report(guess, secret)
8860a1eb440ef0f1249875bc5a97a5157bf0c258
ShamanicWisdom/Basic-Python-3
/Simple_If_Else_Calculator.py
2,753
4.4375
4
# IF-ELSE simple two-argument calculator. def addition(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) result = first_value + second_value # %g will ignore trailing zeroes. print("\nResult of %.5g + %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("Please insert proper numbers!") def subtraction(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) result = first_value - second_value # %g will ignore trailing zeroes. print("\nResult of %.5g - %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("Please insert proper numbers!") def multiplication(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) result = first_value * second_value # %g will ignore trailing zeroes. print("\nResult of %.5g * %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("Please insert proper numbers!") def division(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) if second_value == 0: print("Cannot divide by zero!") else: result = first_value / second_value # %g will ignore trailing zeroes. print("\nResult of %.5g / %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("\nPlease insert proper numbers!\n") print("==Calculator==") user_choice = -1 while user_choice != 0: print("1. Addition.") print("2. Subtraction.") print("3. Multiplication.") print("4. Division.") print("0. Exit.") try: user_choice = int(input("Please input a number: ")) if user_choice not in [0, 1, 2, 3, 4]: print("\nPlease input a proper choice!\n") else: if user_choice == 0: print("\nExiting the program...\n") else: if user_choice == 1: addition() else: if user_choice == 2: subtraction() else: if user_choice == 3: multiplication() else: if user_choice == 4: division() except ValueError: print("\nProgram will accept only integer numbers as an user choice!\n")
e1c78b78e6d11112d2f6dfe451aa3a08a136fedc
thevickypedia/Fun-Python
/shapes_and_colors.py
2,239
3.703125
4
"""Rectangle and Oval shapes with colors filled.""" from tkinter import Frame, Canvas, Radiobutton, Checkbutton, Button, W, E, N class Geometry(Frame): def __init__(self): """Sets up windows and widgets""" Frame.__init__(self) self.master.title("Canvas") self.grid() self.canvas = Canvas(self, width=300, height=300, bg='white') self.canvas.grid() self.r1 = Radiobutton(self, text="Rectangle", command=self.create_rectangle) self.r1.grid(row=1, column=0, sticky=W) self.r1.deselect() self.r2 = Radiobutton(self, text="Oval", command=self.create_oval) self.r2.grid(row=1, column=0, sticky=N) self.r2.deselect() self.r3 = Checkbutton(self, text="Filled", command=self.is_filled) self.r3.grid(row=1, column=0, sticky=E) self.b1 = Button(self, text="Clear", command=self.clear_frame) self.b1.grid(row=2, column=0) self.oval_created = False self.rect_created = False def create_rectangle(self, color=None): """Creates a rectangle""" self.rect_created = True self.canvas.create_rectangle(50, 50, 250, 250, fill=color) def rectangle_is_filled(self): """Calls createRectangle passing the color argument""" self.create_rectangle(color='red') def clear_frame(self): """Deletes the entire canvas""" self.oval_created = False self.rect_created = False self.canvas.delete("all") self.r1.deselect() self.r2.deselect() self.r3.deselect() def create_oval(self, color=None): """Create an oval""" self.oval_created = True self.canvas.create_oval(50, 100, 250, 200, fill=color) def oval_is_filled(self): """Calls createOval passing the color argument""" self.create_oval(color='yellow') def is_filled(self): """Checks if rectangle is created and then calls rectangleIsFilled, and checks if oval is created and then calls ovalIsFilled""" if self.rect_created: self.rectangle_is_filled() if self.oval_created: self.oval_is_filled() if __name__ == '__main__': Geometry().mainloop()
11622016b22c032313d420c9e822f28b32a27e41
mfouda/Probabilistic-Graphical-Models
/hwk1/logistic_regression.py
3,261
3.765625
4
""" This class implements a logistic regression to a 2D model, with points X and labels Y in {0, 1}. The boundary we will learn is in the form f(x) = transpose(w) * x + b affine (with a constant term) """ from copy import deepcopy import matplotlib.pyplot as plt import numpy as np from base_classification import BaseClassification import utils.adv_math as adv_math class LogisticRegression(BaseClassification): def __init__(self, data_x, data_y, w0, data_x_test=None, data_y_test=None, dataset_name=None, nb_iterations=20, lambda_val=0): super(LogisticRegression, self). __init__(data_x, data_y, data_x_test, data_y_test, dataset_name) # Initial point of the iteration self.w0 = w0 # Array of log-likelihoods at each step of the iteration self.log_likelihood = [] self.nb_iterations = nb_iterations # Constant to penalize w self.lambda_val = lambda_val # adding a column of ones to include constant term self.data_x = np.hstack((data_x, np.ones((data_x.shape[0], 1)))) self.data_x_test = np.hstack((data_x_test, np.ones((data_x_test.shape[0], 1)))) # Plot titles self.title_training_plot = "Logistic Regression: Training" self.title_test_plot = "Logistic Regression: Test" def train(self): iteration = 0 w = deepcopy(self.w0) log_likelihood = [self.compute_log_likelihood(self.w0)] while iteration < self.nb_iterations: try: search_dir = self.compute_newton_direction(w) w = w + search_dir log_likelihood.append(self.compute_log_likelihood(w)) iteration += 1 print "iteration %s" % iteration except OverflowError: print "Some computation gives back a double too large to be represented, most certainly in w" break self.w = w[0:2, :] self.b = w[2, 0] self.log_likelihood = log_likelihood def plot(self, test_mode=False): super(LogisticRegression, self).plot(test_mode) def plot_convergence_func(self): plt.plot(xrange(len(self.log_likelihood)), self.log_likelihood, color='black') plt.xlabel("Number of iterations") plt.ylabel("Log-Likelihood") plt.title("Logistic Regression: Training dataset %s" % self.dataset_name) def compute_log_likelihood(self, w): return self.data_y.T.dot(adv_math.LOG(adv_math.SIGMOID_FUNC(self.data_x.dot(w))))[0, 0] + \ (1. - self.data_y).T.dot(adv_math.LOG(adv_math.SIGMOID_FUNC(- self.data_x.dot(w))))[0, 0] def compute_newton_direction(self, w): # vectors of sigmoid applied to every data point sigmoid_vec = adv_math.SIGMOID_FUNC(self.data_x.dot(w)) # the gradient vector gradient = self.data_x.T.dot(self.data_y - sigmoid_vec) - 2 * self.lambda_val * w # the hessian matrix diagonal = np.diag(sigmoid_vec[:, 0]).dot(np.diag(1 - sigmoid_vec[:, 0])) - np.diag(2 * self.lambda_val * w.T) hessian = self.data_x.T.dot(diagonal).dot(self.data_x) # compute search direction search_dir = np.linalg.inv(hessian).dot(gradient) return search_dir
94a0ce757ff1516ca4badb0513bdf4ecf1edef9a
shikhar-sharma1703/Data-Structures-Codechef
/Bracket-matcher.py
604
3.875
4
def BracketChecker(abc): stack = [] opening = ['{', '(', '['] closing = ['}', ')', ']'] for i in range(len(abc)): ch = abc[i] if ch in opening: stack.append(ch) elif ch in closing: if len(stack) > 0: chx = stack.pop() if (ch == ')' and chx != '(') or (ch == ']' and chx != '[') or (ch == '}' and chx != '{'): print("Error at {} , {} is mismatched".format(i, ch)) else: print("Error at {} , {} is mismatched".format(i, ch)) abc = input() BracketChecker(abc)
2abdd20cfe2d53653a7bdd71f01a5d5b61ae6e5f
MichelAbdo/movie-list
/movies/movies_service.py
1,665
3.578125
4
from .helper import Helper from .people_service import PeopleService class MoviesService: """ Class Containing Movie related functions """ # @todo: Define env variables movies_url = "https://ghibliapi.herokuapp.com/films" people: list movies: list people_service: None def __init__(self): """ Class constructor """ self.people_service = PeopleService() def get_movies(self) -> list: """ Get movies through an api call @return: list @rtype: list """ self.movies = Helper.make_request(self.movies_url).json() return self.movies def get_movies_people(self) -> list: """ Return movies with their people. For each movie add its related people :return: list of movies with their people @rtype: list """ movies = self.get_movies() people = self.people_service.get_people() # Get people per movie and fill them in a dict having the movie id as key movie_people = {} for person in people: for movie in person['films']: movie_id = movie.rsplit('/', 1)[-1] if movie_id in movie_people: movie_people[movie_id].append(person) else: movie_people[movie_id] = [person] # For each movie, set its people for movie in movies: movie_id = movie.get('id') if movie_id in movie_people: movie['people'] = movie_people[movie_id] else: movie['people'] = [] return movies
43eabed5fc6f4332de8e06fa7915cf9fd69c2b0a
gabriellechen-nyu/Python-INFO1-CE9990-1
/line.py
186
3.546875
4
""" line.py Output a horizontal line of X's. """ import sys inner = 1 while inner <= 36: print("X", end = "") inner += 1 print() #Output one newline character. sys.exit(0)
a3564f4aaa38b6d3feb76bb8bb71e4fec8d3b297
gabriellechen-nyu/Python-INFO1-CE9990-1
/infiniteloop.py
308
3.6875
4
""" infiniteloop.py Output a never-ending story. """ import sys import time while True: print("It was a dark and stormy night.") print("Some Indians were sitting by a campfire.") print("Then their chief rose and said,") print() time.sleep(3) #Do nothing for 3 seconds. sys.exit(0)
a402e3f599a80492ebeb6b1c8f1c63979b1fac4d
eclecticitguy/pynet_paid
/class1/ex8_confparse.py
606
3.578125
4
''' 8. Write a Python program using ciscoconfparse that parses this config file. Note, this config file is not fully valid (i.e. parts of the configuration are missing). The script should find all of the crypto map entries in the file (lines that begin with 'crypto map CRYPTO') and for each crypto map entry print out its children. ''' from ciscoconfparse import CiscoConfParse config = CiscoConfParse('cisco_ipsec.txt') crypto_map = config.find_objects(r"^crypto map CRYPTO") for crypto in crypto_map: print crypto.text for child in crypto.children: print child.text print "!"
f4e5c78842a8f47232fd46d4c3143330b96db7c1
RodolfoContreras/AprendaPython
/Multiplo.py
286
4.0625
4
# Multiplo.py # Autor: Contreras Galvan Rodolfo Alejandro # Fecha de creación: 02/09/2019 #Simplifique el nombre de los multiplos n=int(input("Introduce un numero entero: ")) m3=((n%3)==0) m5=((n%5)==0) m7=((n%7)==0) if ((m3 and m5) or m7): print("Correcto") else: print("Incorrecto")
d44bfd60a198620f51aca7b57ff570ed8b904325
RodolfoContreras/AprendaPython
/Acumulado.py
347
3.734375
4
# Acumulado.py # Autor: Contreras Galvan Rodolfo Alejandro # Fecha de creación: 02/09/2019 i=int(0) numero=str("") while True: numero=input("Introduce un numero entero: ") if numero=="": print("Vacio, salida del programa") break else: i+=int(numero) salida="Cantidad acumulada: {}" print(salida.format(i))
dc34292ed2081d6738a15d0c69c1abbd3fd3cb7b
priyanka1815/euler_project
/Q9.py
249
3.65625
4
# There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. for i in range(1,26): for j in range(1,i+1): if(i*(i+j)==500): print 2*((i*i*i*i) -(j*j*j*j))*(i*j) break;
0f2d5f861255457438614a1f62ff54c9851b2dcb
priyanka1815/euler_project
/sumNatural.py
211
3.828125
4
#!C:/Python27/python.exe -u # Filename : sumNatural.py sum=0 for i in range(1,1000): if( i%3 ==0 or i%5 ==0): sum = sum+ i print '''The sum of natural numbers divisile' by 3 and 5 is ''',sum
d29f6125a3269367c6111caf1d62eb426a83a666
SpringCheng/Python--practice
/day4/while循环.py
503
3.671875
4
""" 猜数字大小 -*- coding: UTF-8 -*- @date: 2019/9/2 22:19 @name: while循环.py @author:Spring """ import random answer = random.randint(1, 100) counter = 0 while True: counter += 1 number = int(input('请输入数字:')) if number < answer: print("猜小了") elif number > answer: print("猜大了") else: print('恭喜你答对了!') break print('你总共猜了%d次' % counter) if counter > 7: print('你的智商有点低')
0da82a8a4e21d91c567a50ca11ae6dfd526108c9
SpringCheng/Python--practice
/day8/函数/装饰器.py
314
3.84375
4
""" @date: 2019/9/10 9:53 @author:Spring """ def add(a, b): r = a + b return r def mul(a, b): r = a * b return r def new_add(a, b): r = add(a, b) m=mul(a,b) return r,m # 希望函数在计算前打印开始计算,计算结束后打印计算完毕 print(new_add(123, 345))
5ed08635fcd0666a50fd9abca4f11c29a01de8cd
Ryougi-Mana/demo
/fibo.py
443
4
4
# 斐波那契(fibonacci)数列模块 # __all__ = ['fib','fib2','fib_attr'] fib_attr = 100 sum0 =111 def fib(n): # 定义到 n 的斐波那契数列 a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a + b print() def fib2(n): # 返回到 n 的斐波那契数列 result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a + b return result def fib3(n): return n*2
c1730b8e545837183c3a5eada399cbdfc686d611
Plotkine/HackerRank
/Easy/Mini-Max_Sum.py
1,495
3.65625
4
#!/bin/python3 import math import os import random import re import sys from copy import deepcopy def find4Min(arr): #returns array with 4 smallest elements of arr temp = [10**9,10**9,10**9,10**9] for elem in arr: if elem < temp[3]: temp[0] = temp[1] temp[1] = temp[2] temp[2] = temp[3] temp[3] = elem elif elem < temp[2]: temp[0] = temp[1] temp[1] = temp[2] temp [2] = elem elif elem < temp[1]: temp[0] = temp[1] temp[1] = elem elif elem < temp[0]: temp [0] = elem return temp[0]+temp[1]+temp[2]+temp[3] # Complete the miniMaxSum function below. def find4Max(arr): #returns array with 4 largest elements of arr temp = [1,1,1,1] for elem in arr: if elem > temp[3]: temp[0] = temp[1] temp[1] = temp[2] temp[2] = temp[3] temp[3] = elem elif elem > temp[2]: temp[0] = temp[1] temp[1] = temp[2] temp [2] = elem elif elem > temp[1]: temp[0] = temp[1] temp[1] = elem elif elem > temp[0]: temp [0] = elem return temp[0]+temp[1]+temp[2]+temp[3] def miniMaxSum(arr): temp = deepcopy(arr) print(str(find4Min(arr))+" ", end='') print(str(find4Max(arr)), end='') if __name__ == '__main__': arr = list(map(int, input().rstrip().split())) miniMaxSum(arr)
ca3454e4e7b432dbe413d60edbd36e471a9c10cc
GT-Frappuccino/SeaTrash_Cleaning_Drone_CCP
/car/python/action_to_nearby.py
908
3.59375
4
def action(region): currentMin = min(region.values()) direction_min = min(region.keys(),key=(lambda k: region[k])) if (region["back_bl"] > FAR and region["back_left"] > FAR and region["left"] > FAR and region["forward"] > FAR and region["forward_right"] > FAR and region["right"] > FAR and region["back_right"] > FAR and region["back_br"] > FAR): print("nothing \n") forward(0.01) elif (direction_min == "forward_left" or direction_min == "left" or direction_min == "back_left" or direction_min == "back_bl"): print("turn left \n") left(0.01) elif (direction_min == "forward_right" or direction_min == "right" or direction_min == "back_right" or direction_min == "back_br"): print("turn right \n") right(0.01) elif (direction_min == "forward"): print("forward \n") forward(0.01)
5b4e467c5f58baa8c93806f2861ab9b968f95e6f
stevenhorsman/advent-of-code-2017
/day-06/memory_reallocation.py
1,123
3.75
4
import itertools from collections import Counter input_file = 'day-06/input.txt' def find_repeat(input, get_cycle_length = False): banks = [int(block) for block in input.split()] seen = {} steps = 0 while tuple(banks) not in seen: seen[tuple(banks)] = steps # Find biggest bank # i, m = max(enumerate(banks), key=lambda k: (k[1], -k[0])) max_value = max(banks) index = banks.index(max_value) banks[index] = 0 # Distribute amongst others # Smarter, but less efficient # counter = Counter(itertools.islice(itertools.cycle(range(len(banks))), index + 1, index + max_value + 1)) # for counts in counter.items(): # banks[counts[0]] += counts[1] for _ in range(0, max_value): index = (index + 1) % len(banks) banks[index] += 1 steps += 1 if get_cycle_length: steps -= seen[tuple(banks)] return steps def part1(input): return find_repeat(input) def part2(input): return find_repeat(input, True) if __name__ == "__main__": with open(input_file) as f: data = f.read() print("Part 1: ", part1(data)) print("Part 2: ", part2(data))
17d3a5f87c328f57d3e5057910d1a76b2cf2d48a
bnja123456789/TrabajoJulio
/Ejercicio3 .py
1,598
3.9375
4
def Ejercicio3(): print("Matricula Cursos Estudiante:") isCurso = 1 nCursos = 10 contador = 0 sumCreditos = 0 multCredCalif = 0 multCredCalifX = 0 matriz = [[0] * nCursos for i in range(nCursos)] while (isCurso): matriz[contador][0] = input("Ingrese el codigo del curso:") if (matriz[contador][0] != "9999"): matriz[contador][1] = input("Ingrese el Nombre del Curso:") matriz[contador][2] = float(input("Ingrese la calificacion del curso:")) matriz[contador][3] = int(input("Ingrese el numero de Creditos:")) multCredCalif = matriz[contador][2] * matriz[contador][3] multCredCalifX = multCredCalifX + multCredCalif sumCreditos = sumCreditos + matriz[contador][3] contador = contador + 1 else: if (sumCreditos >= 25 and sumCreditos <= 50): isCurso = 0 for i in range(0, contador): print(matriz[i][0], "\t", matriz[i][1], "\t", matriz[i][2], "\t", matriz[i][3]) print("Cantidad de Cursos Matriculados es:", contador) print("Promedio Ponderado es:", multCredCalifX / sumCreditos) print("La suma de los creditos es:", sumCreditos) else: print("La suma de creditos debe ser mayor o igual que 25 y menor o igual que 50") print("Ingrese Nuevamente los Cursos:") isCurso = 1 contador = 0 sumCreditos = 0 if __name__=="__main__": Ejercicio3()
2d7c02875b462d093fcef3af82717b97bfddaa89
bnja123456789/TrabajoJulio
/Ejercicio12.py
851
3.84375
4
def Ejercicio12(): print("Cajero de supermercado:") opcion=input("Para ingresar datos de un nuevo cliente ingrese N o T para terminar el dia:") totalCobrado=0 while opcion=="N": opcion2 = "N" totalaPagar=0 while opcion2=="N": precio=float(input("Ingrese el precio del articulo:")) unidades=int(input("Ingrese la cantidad de unidades:")) totalaPagar=totalaPagar+precio*unidades opcion2=input("Si desea ingresar un nuevo articulo ingrese N o T para terminar:") print("Total a pagar:", totalaPagar) totalCobrado=totalCobrado+totalaPagar opcion = input("Para ingresar datos de un nuevo cliente ingrese N o T para terminar el dia:") print("Total cobrado:", totalCobrado) if __name__=="__main__": Ejercicio12()
362e83d167d4e388abb4978d696aa7916d7dcbbd
ShinsakuOkazaki/PythonPractice
/assign1-11.py
1,364
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 20 22:58:10 2018 @author: sinsakuokazaki """ #1.11 #seconds for one year secondsForYear = 60 * 60 * 24 * 365 #corrent population correntPopulation = 312032486 #number of birth in one year birthInYear = secondsForYear // 7 #number of death in one year deathInYear = secondsForYear // 13 #number of death in one year immigrantInYear = secondsForYear // 45 #population increasing in one year increasedPopulation = birthInYear - deathInYear + immigrantInYear #population in next first year firstPopulation = correntPopulation + increasedPopulation #population in next second year secondPopulation = correntPopulation + 2 * increasedPopulation #population in next third year thirdPopulation = correntPopulation + 3 * increasedPopulation #population in next fourth year fourthPopulation = correntPopulation + 4 * increasedPopulation #population in next fifth year fifthPopulation = correntPopulation + 5 * increasedPopulation #print each population in each year print("The population for next first year is", firstPopulation) print("The population for next second year is", secondPopulation) print("The population for next third year is", thirdPopulation) print("The population for next fourth year is", fourthPopulation) print("The population for next fifth year is", fifthPopulation)
3c878c789c968dff38652e2bc0aa1720f6d27465
janice-cotcher/bullseye_ans
/bullseye_ans_v2/bullseye_ans_v2.pyde
481
3.828125
4
# bullseye that alternates red and white size(600, 600) # black background background(0) def circle(d): """circle function that is centred in the middle of the screen with diameter d""" ellipse(300, 300, d, d) colour = "red" # 6 concentric circles that alternate red and white for d in range(600, 0, -100): if colour == "red": fill(255, 0, 0) colour = "white" else: fill(255) colour = "red" circle(d)
687059c6dcb301e04f4b15385758e491d71880f8
aagrebe/Python_basic
/les_3_hw_6.py
1,004
4.03125
4
def int_func (word): first_char = ord(word[0]) if first_char >= 1072 and first_char <= 1103 or first_char >= 97 and first_char <= 122: replace_char = chr(first_char - 32) word_list = list(word) word_list[0] = replace_char word_rep = (''.join(word_list)) return word_rep else: print('Слово должно начинаться с буквы') """ Первая часть задания """ input_word = input('Введите любое слово: ') word = input_word.lower() word_rep = int_func(word) print(word_rep) """ Вторая часть задания """ input_sentence = input('Введите неколько слов, разделенных пробелами: ') sentence = input_sentence.lower() sentence = sentence.split(' ') sentence_list = [] for index in range(len(sentence)): word_rep_sentence = int_func(sentence[index]) sentence_list.append(word_rep_sentence) sentence_rep = (' '.join(sentence_list)) print(sentence_rep)
cc0c7322ce17ab845f6b6eb23b8b549e2810d112
RF-Fahad-Islam/Python-Practice-Program
/jumble_funny_names.py
847
4.0625
4
''' Author : Fahad Practice Problem 9 Solution ''' import random def jumbleName(nameList): #* Jumbled the names lastnames = [] firstnames = [] jumbled = [] for name in nameList: name = name.split(" ") for i in range(1,len(name)): lastnames.append(name[1]) firstnames.append(name[0]) lastnames.reverse() for i,l in enumerate(lastnames): jumbled.append(f"{firstnames[i]} {lastnames[random.randint(0, len(lastnames)-1)]}") for name in jumbled: print(name) if __name__ == "__main__": #* Take the input from the user n = input("Enter the friends number : ") nameList = [] for i in range(int(n)): name = input(f"{i+1}. Enter the friend name : ") nameList.append(name) jumbleName(nameList)
1bcc95433faba176fcf99a6c97392233f47ff5c1
overflowzhang/Python-Practice
/stack.py
648
4.09375
4
class Stack(object): def __init__(self): self.data_stack = [] def init_stack(self): self.data_stack = [] def insert(self,data): self.data_stack.append(data) def pop(self): if len(self.data_stack)==0: return None data = self.data_stack[-1] del self.data_stack[-1] return data def size(self): return len(self.data_stack) stack = Stack() stack.insert(1) stack.insert(2) stack.insert(3) print("The size of stack : ") print(stack.size()) print('The stack is : ') print(stack) for i in range(1,stack.size()+1): tail = stack.pop() print(tail)
c6cbfb6a8c91fedba94151405a0e6e064a9cf7dd
pradeep-sukhwani/reverse_multiples
/multiples_in_reserve_order.py
581
4.25
4
# Design an efficient program that prints out, in reverse order, every multiple # of 7 that is between 1 and 300. Extend the program to other multiples and number # ranges. Write the program in any programming language of your choice. def number(): multiple_number = int(raw_input("Enter the Multiple Number: ")) start_range = int(raw_input("Enter the Start Range Number: ")) end_range = int(raw_input("Enter the End Range Number: ")) for i in range(start_range, end_range+1) [::-1]: if i % multiple_number == 0: print i, number()
deca9d3412cbba8fdc210e34ada33095fdfd7593
AdityaLad/python
/python-projects/src/root/frameworks/lambda-map-filter.py
437
3.578125
4
''' Created on Sep 10, 2014 @author: lada ''' def greet(m, user): print m(user) welcome = lambda x: "Welcome to python, " + x greet(welcome, "Spiderman") a = [2,3,4,6,5,7,8] #use of map and lambda, functions on the fly for asd in a: b = map(lambda x: x*x,a) print b names = ('john','sam','jonathan','ram','dave') c = map(lambda x: x.capitalize(), names) print c n = filter(lambda x: x[0] in 'jJ', names) print n
b2825f7313f3834263cc59e8dd49cf3e11d2a86a
AdityaLad/python
/python-projects/src/root/frameworks/ClassCar.py
550
4.125
4
''' Created on Sep 11, 2014 @author: lada the only purpose of init method is to initialize instance variables ''' ''' def __init__(self, name="Honda", *args, **kwargs): self.name = name ''' class Car: #constructor def __init__(self, name="Honda"): self.name = name def drive(self): print "Drive car", self.name #destructor def __del__(self): print "Car object destroyed.." c1 = Car("Toyota") c2 = Car("Nissan") c3 = Car() c1.drive() c2.drive() c3.drive()
9dbc6104a92d5772f65ed42862636253282a9f36
AdityaLad/python
/python-projects/src/root/frameworks/csv_parser.py
172
3.8125
4
''' Created on Sep 12, 2014 @author: lada ''' import csv with open(file) as f: records = csv.reader(f) for name, age, loc in records: print name, age, loc
a3545e01d65fa30474db20a2d4165f2220b1729f
AdityaLad/python
/python-projects/src/root/frameworks/comprehensions.py
527
3.84375
4
''' Created on Sep 10, 2014 @author: lada ''' nums = [1,2,3,4,5,6,78,40] #result = map(lambda x: x*x, nums) #Using comprehensions, its a different kind of fop loop result = [ x*x for x in nums ] print result names = ('john','sam','jonathan','ram','dave') v = tuple(n.upper() for n in names) print v #store square of even numbers, combination of maps and filter zz = [x*x for x in nums if x%2 == 0] print zz #this will give a generator object ansxx = ( x*x for x in nums) print type(ansxx) for ab in ansxx: print ab,
d19dfa83cdbe51bbde60512eb58dd3954e2b17d0
dander521/Python_Learning
/10.19.1/10.19.1/List.py
305
3.65625
4
#coding:utf-8 list1 = ['Google', 'Runoob', 1997, 2000] list2 = [1, 2, 3, 4, 5] list3 = ["a", "b", "c", "d"] print(list1[0]) print(list2[1:2]) list1[1] = 2001 print(list1) del list1[1] print(list1) for x in [1, 2, 3]: print(x) list4 = [1, 1, 1, 1, 2, 2, 3] print(list4.count(1)) print(list4)
8743994af6f41f5ac0ee05b0cddd0b074860bee3
dander521/Python_Learning
/10.24/10.24/ErrorAndException.py
446
3.921875
4
#coding:utf-8 # while True: # try: # x = int(input("Please enter a number: ")) # break # except ValueError: # print("Oops! That was no valid number. Try again ") # def divide(x, y): try: result = x / y except ZeroDivisionError: # raise print("division by zero!") else: print("result is", result) finally: print("executing finally clause") divide(2, 0)
e10a4bfdb13bf65cddee92cc28c7512ffa1d2110
sohanur-it/machine_learning
/Neural_networks_2_marks_me.py
2,607
3.546875
4
#!/usr/bin/python3 import numpy as np # x = (hours sleeping, hours studying), y = score on test x = np.array(([2, 9], [1, 5], [3, 6]), dtype=float) y = np.array(([92], [86], [89]), dtype=float) xPredicted = np.array(([4,8]), dtype=float) # scale units X = x / np.amax(x) # maximum of X array Y = y/100 # max test score is 10 xPredicted = xPredicted/np.amax(xPredicted, axis=0) # maximum of xPredicted (our input data for the prediction) #print(xPredicted) #print(X) #print(Y) class Neural_Network(object): def __init__(self): self.inputSize = 2 self.outputSize = 1 self.hiddenSize = 3 #3x2 input matrix X self.W1 = np.random.randn(self.inputSize, self.hiddenSize) #(2x3) weight matrix from input to hidden layer self.W2 = np.random.randn(self.hiddenSize, self.outputSize) # (3x1) weight matrix from hidden to output layer def forward(self, X): #dot multiplication between input value and weight = z2 self.z2= np.dot(X, self.W1) ##3x2 dot 2x3 = 3x3 #apply activation function to our total z2 self.a2 = self.sigmoid(self.z2) #3x3 #hidden layer to output layer ,dot multiplication between activation and weights self.z3= np.dot(self.a2 , self.W2) # 3x3 dot 3x1 = 3x1 #final activation function yhat = self.sigmoid(self.z3) #3x1 matrix return yhat def sigmoid(self, s): #activation function return 1/(1+np.exp(-s)) def sigmoidPrime(self, s): #derivative of sigmoid return s * (1-s) def costfunction(self,X,Y): self.yhat = self.forward(X) j = 0.5 * sum((y- self.yhat)**2) return j def backward(self, X ,Y, yhat): self.o_error = Y - yhat # error in output # Y = (3x1) and yhat = 3x1 self.delta3= self.o_error*self.sigmoidPrime(yhat) #3x1 self.W2 +=np.dot(self.z2.T,self.delta3) #3x3 dot 3x1 = 3x1 matrix #print(self.W2) self.delta2 = np.dot(self.delta3,self.W2.T)*self.sigmoidPrime(self.z2) #3x3 matrix #print(self.djdw1) self.W1 += np.dot(X.T,self.delta2) #3x2 matrix #print(self.W1) def trains(self,X,Y): yhat= self.forward(X) self.backward(X,Y,yhat) def predict(self): print("predicted data based on trained weights") print ("Input (scaled): \n" + str(xPredicted)) print ("Output: \n" + str(self.forward(xPredicted))) NN = Neural_Network() for i in range(1000): # trains the NN 1,000 times print ("# " + str(i) + "\n") print ("Input (scaled): \n" + str(X)) print ("Actual Output: \n" + str(y)) print ("Predicted Output: \n" + str(NN.forward(X))) print ("Loss: \n" + str(NN.costfunction(X,Y))) print ("\n") NN.trains(X,Y) NN.predict()
b673a44965d31b1cb410c1e64fcdae7b466dad3b
alexxa/Python_for_beginners_on_skillfeed_com
/ch_03_conditionals.py
723
4.28125
4
#!/usr/bin/python #AUTHOR: alexxa #DATE: 18.12.2013 #SOURSE: https://www.skillfeed.com/courses/539-python-for-beginners #PURPOSE: Conditionals. a,b = 0,1 if a == b: print(True) if not a == b: print(False) if a != b: print('Not equal') if a > b: print('Greater') if a >= b: print('Greater or equal') if a < b: print('Smaller') if a <= b: # not => print('Smaller or equal') if a==b or a < b: print('This is True') if a!=b and b > 0: print('This is also True') if a!=b and b < 0: print('This is also True') if a > b: print('a is greater than b') elif a < b: print('a is less than b') else: print('a s equal to b') #END
016d83a9190ffce1b5cba09a2e176793f0eb0c32
alexxa/Python_for_beginners_on_skillfeed_com
/ch_04_looping.py
1,525
4
4
#!/usr/bin/python #AUTHOR: alexxa #DATE: 18.12.2013 #SOURSE: https://www.skillfeed.com/courses/539-python-for-beginners #PURPOSE: Looping. # while loops a = 0 while a < 100: print(a) a +=1 print() # for loops for data in [1, 2, 3, 4, 5]: print(data) print() for data in 'string': print(data) print() for key,data in enumerate('string'): if key % 2 == 0: print('This letter {} is in an even location'.format(data)) print() # exceptions tuple1 = (1, 2, 3, 4, 5) try: tuple1.append(6) except: print('Error formed') else: for each in tuple1: print(each) print() tuple2 = (1, 2, 3, 4, 5) try: tuple2.append(6) except AttributeError as e: print('Error formed:', e) else: for each in tuple2: print(each) print() tuple3 = (1, 2, 3, 4, 5) try: tuple3.append(6) for each in tuple3: print(each) except AttributeError as e: print('Error formed:', e) print() tuple3 = (1, 2, 3, 4, 5) try: #tuple3.append(6) for each in tuple3: print(each) except AttributeError as e: print('Error formed:', e) except IOError as e: print('File not found:', e) print() # break, continue and else list1 = [1,2,3,4,5,6,7,8,9] for var in list1: if var ==7: break print(var) else: print('default') print() list1 = [1,2,3,4,5,6,7,8,9] for var in list1: if var ==7: continue print(var) else: print('default') #END
a5026b6c09eb7381209e6a4f3fb7e3d93e0dd140
wentao75/pytutorial
/05.data/dict.py
759
4.0625
4
# 字典(dictionary)是另一个有用的数据类型 # 字典可以理解为一组 (key: value)组成的数据,并且key在字典中是唯一的。 # 使用{}可以创建一个空的字典对象;在大括号中使用逗号分割的key: value可以添加初始的数据 tel = {'jack': 4098, 'sape': 4139} tel['guido'] = 4127 tel tel['jack'] del tel['sape'] tel['irv'] = 4127 tel list(tel) sorted(tel) 'guido' in tel 'jack' not in tel # 可以使用dict()从key-value数据对序列中直接构建 dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) # dict Comprehensions也类似可用 {x: x**2 for x in (2, 4, 6)} # 如果key是简单的字符串,也可以直接使用关键字参数的方式创建 dict(sape=4139, guido=4127, jack=4098)