blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
569ba0b2a041c57f29effce4f5d0769bae0dc109
Paolopdp/finished-school-projects
/Elaborato_Python/progetto.py
6,561
3.78125
4
#!/usr/bin/python """ Codice per l'esame """ #P1 """ dato un dizionario che associa gli id del FASTA file alla stringa di DNA, ritorna il numero di record nel dizionario """ def get_num_records(records): return len(records.keys()) #P2 """ dato un dizionario che associa gli id del FASTA file alla stringa di DNA, ritorna un dizionario che associa gli id del dizionario alla lunghezza della stringa. """ def get_length_map(records): new_records = {} for k in records.keys(): new_records[k]=len(records[k]) return new_records """ dato un dizionario che associa gli id alla lunghezza della stringa, ritorna la lunghezza della stringa minima e la lunghezza della stringa massima """ def get_min_max_length(len_map): ret=sorted(len_map.values()) return(ret[0],ret[-1]) """ dato un dizionario che associa gli id alla lunghezza della stringa, ritorna il numero delle sequenze che hanno lunghezza minima e massima """ def get_min_max_num(len_map): maxc,minc=0,0 ret=sorted(len_map.values()) for k in len_map.keys(): if len_map[k]==ret[-1]: maxc=maxc+1 elif len_map[k]==ret[0]: minc=minc+1 return (minc,maxc) """ dato un dizionario che associa gli id alla lunghezza della stringa, ritorna la lista di id associati alle sequenze che hanno lunghezza minima e massima """ def get_min_max_length_id(len_map): minlist=[] maxlist=[] minn,maxx=get_min_max_length(len_map) for k in len_map.keys(): if len_map[k]==maxx: maxlist.append(k) elif len_map[k]==minn: minlist.append(k) return (minlist,maxlist) #P3 """ data una sequenza di dna ed un frame di lettura, restituisce la lista di tutti gli ORF contenuti nella stringa di DNA. """ def get_ORF_list(dna,frame=0) : orf_list=[] orf=["atg"] stop_codons=["tga","tag","taa"] for i in range(frame,len(dna),3): codon=dna[i:i+3].lower() if codon in orf: for k in range(i+3,len(dna),3): codon=dna[k:k+3].lower() if codon in stop_codons: orf_list.append(dna[i:k+3]) break return orf_list """ dato un dizionario che associa gli id del FASTA file alla stringa di DNA, restituisce un dizionario che associa gli id alla lista di ORF contenuti nella sequenza corrispondente. """ def get_ORF_map(records,frame=0) : orf_map={} for k in records.keys(): orf_map[k]=get_ORF_list(records[k]) return orf_map """ un dizionario che associa gli id alla lista degli ORF per quella sequenza, restituisce l'id associato all'ORF piu' lungo, l'ORF piu' lungo e la lunghezza di tale ORF (in caso ci fossero piu' ORF massimali restituire uno qualsiasi di questi ORF). """ def longest_ORF(orf_map): maxn=0 for k in orf_map.keys(): for i in range (0,len(orf_map[k]),1): if len(orf_map[k][i])>maxn: maxn=len(orf_map[k][i]) maxid=k maxorf=orf_map[k][i] return (maxid,maxorf,maxn) #P4 """ data una lunghezza n ed una lista di sequenze di nucleotidi, restituisce un dizionario che associa tutte le sottostringhe ripetute di lunghezza n (i.e., sottostringhe che compaiono almeno una volta in almeno una sequenza) al loro numero di occorrenze in tutte le sequenze. """ def get_all_repeats(n,seq_list): diz={} test=''.join(seq_list) for i in range(0,len(test),1): trip=test[i:i+3] if trip not in diz.keys(): diz[trip]=1 else: diz[trip]=diz[trip]+1 return diz """ dato un dizionario che associa sottostringhe al numero di occorrenze, ritorna la sottostringa con il numero massimo di occorrenze (ed il numero di occorrenze) """ def most_frequent_repeat(rep_map): max=0 for k in rep_map.keys(): if rep_map[k]>max: max=rep_map[k] substrmax=k return substrmax,max """ dato un dizionario che associa sottostringhe al numero di occorrenze ed un numero di occorrenze occ, ritorna l'insieme delle stringhe che ha un numero di occorrenze associato pari almeno a occ. """ def filter_repeats(rep_map,occ): diz2={} for k in rep_map.keys(): if rep_map[k]>occ: diz2[k]=rep_map[k] stringhe=diz2.keys() return stringhe if __name__ == "__main__" : filename = input("Scegliere file fasta:\n\ta) dna.simple.fasta\n\tb) dna.long.fasta\n") if (filename == 'a'): filename = 'dna.simple.fasta' else: filename = 'dna.long.fasta' from fastautil import read_fasta #test P1 records = read_fasta(filename) print("Test numero record, a) 5 b) 28 ") print("numero record = %s " % get_num_records(records)) #test P2 len_map = get_length_map(records) #print("dizionario lunghezze = %s " % len_map) min_seq,max_seq = get_min_max_length(len_map) print("test lunghezza a) min: 29 max: 112 b) min: 186 max: 1686") print("lunghezza seq minima %s e massima %s " % (min_seq,max_seq)) n_min,n_max = get_min_max_num(len_map) print("numero lunghezza seq a) min: 2 max: 1 b) min: 1 max: 1") print("numero seq con lunghezza minima %s e massima %s " % (n_min,n_max)) id_min,id_max = get_min_max_length_id(len_map) print("id seq a) min: ['id2','id3'] max: ['id4'] b) min: ['lcl|EU819142.1_cds_ACF06958.1_18'] max: ['lcl|EU819142.1_cds_ACF06952.1_12']") print("id seq con lunghezza minima %s e massima %s " % (id_min,id_max)) #test P3 test_string = 'CATGCTATGGTGCCCTAAAAGATGACGCCCTACCCCCCCCCTAGTGATTAGTTTCGAGACATACTGTGTTT' print("test_string contiene 2 ORF in frame 0 ed 1 in frame 1") print("lista ORF associata alla stringa %s : %s" % (test_string,get_ORF_list(test_string))) orf_map = get_ORF_map(records) #print("dizionario ORF = %s " % orf_map) print("numero ORF totali: a) 2 b) 253 ") #print("numero ORF totali: %s " % orf_map.values()) print("numero ORF totali: %d " % sum([len(k) for k in orf_map.values()])) id_lorf,lorf,length_lorf = longest_ORF(orf_map) #print("id sequenza ORF piu' lungo = %s, ORF piu' lungo = %s, lunghezza ORF = %d" % (id_lorf,lorf,length_lorf)) print("id ORF piu' lungo e lunghezza orf a) id4, 54 b) lcl|EU819142.1_cds_ACF06952.1_12, 1686") print("id sequenza ORF piu' lungo = %s, lunghezza ORF = %d" % (id_lorf,length_lorf)) #Test P4 n = 3 rep_map = get_all_repeats(n,records.values()) #print('dizionario delle sottostringhe ripetute di lunghezza %d : %s' % (n,rep_map)) m_f_rep,rep_n = most_frequent_repeat(rep_map) print("sottostringa ripetuta piu' di frequente e numero di occorrenze a) CCC, 70 b) GCC, 954") print("sottostringa ripetuta piu' di frequente nel dizionario = %s , numero di occorrenze = %d" % (m_f_rep,rep_n)) occ = 30 rep_set = filter_repeats(rep_map,occ) print("dimensione insieme a) 1 b) 64 ") print("dimensione insieme di tutte le sottostringhe ripetute che occorrono almeno %d volte = %s " % (occ,len(rep_set)))
12c5c89a4aa589a8dc530300b4d0aafea0bc7141
cdchris12/Project_Euler
/Project_9.py
1,120
4.21875
4
#!/usr/bin/python def FindTriplet(): a = 1 b = 2 c = 3 while a <= 334: while b <= 499: while c <= 997: if a + b + c == 1000: if ((a * a) + (b * b) == (c * c)): return ((a, b, c)) # End if # End if c += 1 # End while c = 1 b += 1 # End while c = 1 b = 1 a += 1 # End while return ((1,2,3)) # End def def main(): a, b, c = FindTriplet() print "The pythagorean triplet for which a + b + c equals 1000 is:\ \na:\t%s\ \nb:\t%s\ \nc:\t%s" % (a, b, c) print "The product of these numbers is: %s" % (a * b * c) # End def if __name__ == "__main__": main() # End if # Goal: """A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc."""
f01e2b0d1fd9ed196c71fbef7a95a02b45789059
hashbanger/Python_Advance_and_DS
/DataStructures/Minimal/Stacks/01_Stack.py
653
4.125
4
# Implementing a stack class Stack(object): def __init__(self): self.items = [] def isEmpty(self): return len(self.items) == 0 def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) # if __name__ == '__main__': # s1 = Stack() # print(s1.push(1)) # print(s1.push(2)) # print(s1.push(3)) # print(s1.push(4)) # print(s1.size()) # print(s1.peek()) # print(s1.pop()) # print(s1.pop()) # print(s1.isEmpty())
a2db4ca5084f19a6e54260465765e44a05725b31
rbrokenshaw/Python-Challenges
/Mathematical/Pairs of Prime Number/prime_pairs.py
548
3.6875
4
import itertools def primePairs(n): if n >= 4: # find all prime numbers between 2 and n multiples = [] primeNums = [] for i in range(2, n+1): if i not in multiples: primeNums.append(i) for x in range(i*i, n+1, i): multiples.append(x) # find all pairs that meet constraint pairs = [] for p in primeNums: for q in primeNums: if p*q <= n: pairs.append(p) pairs.append(q) return " ".join(str(x) for x in pairs) else: return 0 # test the function print (primePairs(4)) print (primePairs(8))
172f55b1a394695bab0b7dcd90cf632a5b1d5e80
kyeongbukpjs/python-programming
/exercise2/problem2.py
135
3.78125
4
#y = 7x^3 + 4x^2 + 2x +5 #x는 표준입력으로, y는 표준 출력으로 x = int(input()) y = 7*(x**3) + 4*(x**2) + 2*x +5 print(y)
3a4f66afa7f8c213b1879882a97da75411999a35
bpuderer/python-snippets
/util/list_of_dictionaries.py
1,276
3.96875
4
""" list of dictionaries helpers """ def exists_lod(lst, key, val): """is key-value in list of dicts""" return any(d[key] == val for d in lst) def index_lod(lst, key, val): """index of first occurrence key-value in list of dicts""" return next((i for (i, x) in enumerate(lst) if x[key] == val), -1) def find_lod(lst, key, val): """get dict of first match of name-value pair in list of dicts""" return next((x for x in lst if x[key] == val), None) def findall_lod(lst, key, val): """get list of dicts of all matches of key-value pair in list of dicts""" return [x for x in lst if x[key] == val] def remove_lod(lst, key, val, only_first_occur=False): """remove from list matches of key-value pair in list of dicts""" for i in range(len(lst)-1, -1, -1): if lst[i][key] == val: del lst[i] if only_first_occur: return if __name__ == "__main__": lst = [{'a': 0}, {'a': 1, 'b': 1}, {'a': 2}, {'a': 1}, {'a': 5}] print(exists_lod(lst, 'a', 3)) print(exists_lod(lst, 'a', 2)) print(index_lod(lst, 'a', 1)) print(find_lod(lst, 'a', 1)) print(findall_lod(lst, 'a', 1)) print('---') remove_lod(lst, 'a', 1) #remove_lod(lst, 'a', 1, True) print(lst)
93ac6f48157222bebf9cd71b991cc59576a366da
owensheehan/ModularProgramming
/Revision_Lab1_Question1.py
409
3.828125
4
#Script: Revision_Lab1_Question1.py #Author: Owen Sheehan #Description: Read and display Students name and over all mark ok=True try: while ok: studentName=input("Please enter the name of the student:") overallMark=int(input("Please enter the students overall exam mark (numerically):")) print("Student Name:",studentName," Overall Exam Mark:",overallMark) except: print("error")
371b1b10cbfc33771ef441621c2a94b37fb7684b
laurenwolfe/coding-practice
/trees/bin_tree_traversal.py
2,239
4.09375
4
from trees import binary_tree from lists.linked_list import build_linked_list, LinkedList from collections import deque def build_tree_from_linked_list(head): """Converts a linked list to binary tree. Add nodes to queue as they're traversed. Popped value is current root. """ tree_queue = deque() tree = binary_tree.BinaryTree() if not head: tree.root = None return tree.root = binary_tree.Node(head.data) tree_queue.append(tree.root) head = head.next while head: parent = tree_queue.popleft() r_child = None l_child = binary_tree.Node(head.data, parent) tree_queue.append(l_child) head = head.next if head: r_child = binary_tree.Node(head.data, parent) tree_queue.append(r_child) head = head.nextß parent.left = l_child parent.right = r_child return tree def traversal(root): """Basic form for traversal.""" if root is not None: # print("preorder: ", root.data) traversal(root.left) # print("inorder: ", root.data) traversal(root.right) # print("postorder: ", root.data) def find_height(root, height): if not root: return height else: return find_height(root.left, height + 1) def breadth_first_traversal(tr_queue, level, build_str): """Print a graphical depiction of the tree using breadth first traversal.""" if len(tr_queue) == 0: return root = tr_queue.popleft() build_str = build_str + "{0:4d}".format(root.data) if root.data == 2**level - 1: # reached a new level of tree print_str = "{: ^50}\n".format(build_str) build_str = "" print(print_str) level = level + 1 if root.left: tr_queue.append(root.left) if root.right: tr_queue.append(root.right) breadth_first_traversal(tr_queue, level, build_str) if __name__ == "__main__": """Generate linked list, convert to binary tree.""" l_list = build_linked_list(24, 1, LinkedList()) bin_tree = build_tree_from_linked_list(l_list.head) queue = deque() queue.append(bin_tree.root) breadth_first_traversal(queue, 1, "")
4869609a2a12d0ec5f101d60bc4369f33f34453f
perfect-python/perfect-python
/part4/chapter16/nx1.py
911
3.890625
4
import networkx as nx def main(): # edgeのリストを渡して初期化 g = nx.Graph([(0, 1), (1, 2), (2, 3), (10, 20), (20, 30), (30, 40), (40, 10)]) # nodeのリストを取得する print(g.nodes()) #=> [0, 1, 2, 3, 40, 10, 20, 30] # edgeのリストを取得する print(g.edges()) #=> [(0, 1), (1, 2), (2, 3), # (40, 10), (40, 30), (10, 20), (20, 30)] # nodeから出ている edge の数の辞書を返す print(g.degree()) #=> {0: 1, 1: 2, 2: 2, 3: 1, # 10: 2, 20: 2, 30: 2, 40: 2} # Graphのインスタンスに対してnodeをインデックスアクセスすると、 # 接続しているedgeの情報が取れる print(g[1]) #=> {0: {}, 2: {}} if __name__ == '__main__': main()
963c1655b9d12ad386b4c20d62a76b31e883b8c4
d3zd3z/euler
/python3/pr037.py
1,367
4.15625
4
#! /usr/bin/env python3 """ Problem 37 14 February 2003 The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. 748317 """ import mrabin import misc def main(): rights = right_truncatable_primes() rights = [x for x in rights if x > 9 if is_left_truncatable(x)] print(sum(rights)) def right_truncatable_primes(): result = [] progress = [2, 3, 5, 7] while len(progress) > 0: result.extend(progress) progress = add_primes(progress) return result def add_primes(numbers): result = [] for number in numbers: for extra in [1, 3, 7, 9]: n = number * 10 + extra if mrabin.is_prime(n): result.append(n) return result def is_left_truncatable(number): while number > 0: if number == 1 or not mrabin.is_prime(number): return False tmp = misc.reverse_number(number) number = misc.reverse_number(tmp // 10) return True if __name__ == '__main__': main()
f4c98e1a5e8b7cb56f6851f5e64753b34fff7097
vojtadavid/IV122
/10/monty_hall_problem.py
1,873
3.78125
4
import random repeat = 10000 #option=0 never change tour guess #option=1 always change your guess #option=2 randomly change your guess def monty_hall(option=1): good_guess = 0 for i in range(repeat): car_position = random.randint(0,2) choosen_pos = random.randint(0,2) host_pos = -1 if (car_position==1 and choosen_pos==0) or (car_position==0 and choosen_pos==1): host_pos = 2 if (car_position == 0 and choosen_pos == 2) or (car_position == 2 and choosen_pos == 0): host_pos = 1 if (car_position == 1 and choosen_pos == 2) or (car_position == 2 and choosen_pos == 1): host_pos = 0 if host_pos==-1: if random.randint(0,1): host_pos = (car_position +1)%3 else: host_pos = (car_position -1)%3 if option==1: s = set([0,1,2]) s.remove(host_pos) s.remove(choosen_pos) choosen_pos = s.pop() # option 0 dont change your guess #option 2 randomly change your guess if option==2 and random.randint(0,1): s = set([0,1,2]) s.remove(host_pos) s.remove(choosen_pos) choosen_pos = s.pop() if car_position==choosen_pos: good_guess+=1 if option==1: print("always change your guess",good_guess/repeat) if option==2: print("randomly change your guess",good_guess/repeat) if option == 0: print("never change your guess", good_guess / repeat) monty_hall(0) monty_hall(1) monty_hall(2) # experimentalni vyhodnoceni ruznych strategii odpovida predpokladanym vysledkum # jako nejvyhodnejsi strategie se jevi vzdy zmenit nas puvodni tip # never change your guess 0.3348 # always change your guess 0.6666 # randomly change your guess 0.499
9f5d70a0384e24e214e795dbf66dcbee88270f16
Kulchutskiyyura/Yura
/play_bango/play_bango.py
202
3.984375
4
def play_banjo(name): if name[0]=="r" or name[0]=="R": return name + " plays banjo" else: return name + " dont plays banjo" name=input("enter name: ") print(play_banjo(name))
43e9d27327251ea1d9408f540d119cbdc32e4b2e
rsnastin/Zad3-CB-Snake
/venv/snake.py
2,978
3.5
4
import random import curses class Snake: #head = 0 body = 0 move_snake = 0 grow = 0 class Food: position = 0 new = 0 remove = 0 class Game: key = 0 snk_x = 0 snk_y = 0 def update_snake(snake, action = 'move'): if action == 'move': w.addch(Snake.body[0], Snake.body[1], ' ') w.addch(snake[0][0], snake[0][1], curses.ACS_BLOCK) for part in snake[1:]: w.addch(part[0], part[1], curses.ACS_CKBOARD) elif action == 'eat': w.addch(snake[0][0], snake[0][1], curses.ACS_BLOCK) for part in snake[1:]: w.addch(part[0], part[1], curses.ACS_CKBOARD) else: pass def adding_info(food=0, length=3, width=0): Snake.grow = length separator = (width-1) * '*' w.addstr(1, 0, separator) w.addstr(0 , 3, "Length of snake: " + str(Snake.grow)) w.addstr(0, int(width/2), "Food eaten: " + str(food)) ############################################################################### # initialize the screeen s = curses.initscr() curses.curs_set(0) sh, sw = s.getmaxyx() w = curses.newwin(sh, sw, 0, 0) w.keypad(1) w.timeout(100) curses.COLOR_RED Game.snk_x = int(sw/4) Game.snk_y = int(sh/2) snake = [ [Game.snk_y, Game.snk_x], [Game.snk_y, Game.snk_x-1], [Game.snk_y, Game.snk_x-2] ] food = [int(sh/2), int(sw/2)] w.addch(food[0], food[1], curses.ACS_DIAMOND) Game.key = curses.KEY_RIGHT Food.new = 0 Snake.grow = len(snake) while True: offset = 2 adding_info(Food.new, Snake.grow, int(sw)) next_key = w.getch() Game.key = Game.key if next_key == -1 else next_key if snake[0][0] in [offset-1, sh-1] or snake[0][1] in [0, sw-1] or snake[0] in snake[1:]: curses.endwin() print("Game Over") print("You results: snake length = %d , food eaten: = %d" % (Snake.grow, Food.new)) quit() elif Game.key == 113: # pressing "q" will quite the game curses.endwin() print("User exit the game") quit() else: Snake.move = [snake[0][0], snake[0][1]] if Game.key == curses.KEY_DOWN: Snake.move[0] += 1 if Game.key == curses.KEY_UP: Snake.move[0] -= 1 if Game.key == curses.KEY_LEFT: Snake.move[1] -= 1 if Game.key == curses.KEY_RIGHT: Snake.move[1] += 1 snake.insert(0, Snake.move) if snake[0] == food: food = None Food.new += 1 Snake.grow += 1 while food is None: Food.position = [ random.randint(1, sh-offset), random.randint(1, sw-1) ] food = Food.position if Food.position not in snake else None w.addch(food[0], food[1], curses.ACS_DIAMOND) update_snake(snake, 'eat') Food.remove=+1 else: Snake.body = snake.pop() update_snake(snake, 'move')
d396a0aa92456c83c6563a461a30c7bafa089b89
timwangmusic/Algorithm-Design
/Linked_list/LFU_cache.py
3,028
3.953125
4
""" Analysis: Take the idea from LRU cache, inc freq of an item and move the node to the list with new freq. Track linked-list node reference with hash table Track linked-list head with frequency count For evictions, we need to track the least frequency If the current LF = 3, and there are 2 items with freq=3. After eviction LF = 1. If the current LF = 3, and there are just 1 item with freq=3. After eviction LF = 1. If current LF = 1, after eviction LF = 1. """ import collections class Node: def __init__(self, key: int, val: int): self.key = key self.val = val self.prev = None self.next = None class LFUCache: def __init__(self, capacity: int): self.capacity = capacity self.heads = {} # freq-->(head, tail) mapping self.nodes = {} # key-->node mapping self.least_freq = 0 self.frequencies = {} # node-->freq mapping self.counter = collections.Counter() def insert_to_head(self, node: Node, freq: int): if freq not in self.heads: self.create_list(freq) head, tail = self.heads[freq] tmp = head.next node.prev = head node.next = tmp head.next = node tmp.prev = node self.counter[freq] += 1 self.frequencies[node] = freq def remove_from_tail(self, freq: int): _, tail = self.heads[freq] last = tail.prev self.counter[freq] -= 1 if self.counter[freq] == 0: self.counter.pop(freq) self.nodes.pop(last.key) self.frequencies.pop(last) tmp = last.prev tmp.next = tail tail.prev = tmp def remove_node(self, node: Node): p, n = node.prev, node.next p.next = n n.prev = p def create_list(self, freq: int): head, tail = Node(-1, -1), Node(-1, -1) head.next = tail tail.prev = head self.heads[freq] = (head, tail) def inc_key(self, key: int): node = self.nodes[key] self.remove_node(node) prev_freq = self.frequencies[node] self.counter[prev_freq] -= 1 if self.counter[prev_freq] == 0: self.counter.pop(prev_freq) self.frequencies[node] += 1 freq = self.frequencies[node] self.insert_to_head(node, freq) if self.least_freq not in self.counter: self.least_freq += 1 def get(self, key: int) -> int: if key not in self.nodes: return -1 self.inc_key(key) return self.nodes[key].val def put(self, key: int, value: int) -> None: if self.capacity == 0: return if key in self.nodes: self.inc_key(key) self.nodes[key].val = value return if len(self.nodes) == self.capacity: self.remove_from_tail(self.least_freq) self.least_freq = 1 new_node = Node(key, value) self.insert_to_head(new_node, 1) self.nodes[key] = new_node
7c4da5b21313b15f5036a12c44d7d07a6ee04525
inthescales/art-gen
/src/color.py
1,953
3.625
4
class Color: def __init__(self, r, g, b, a=1.0): self.r = r self.g = g self.b = b self.a = a hsv = rgb_to_hsv(r, g, b) self.h = hsv[0] self.s = hsv[1] self.v = hsv[2] def string_rgb(self): return "(" + str(self.r) + ", " + str(self.g) + ", " + str(self.b) + ", " + str(self.a) + ")" def string_hsv(self): return "(" + str(self.h) + ", " + str(self.s) + ", " + str(self.v) + ", " + str(self.a) + ")" def rgb(r, g, b, a=1.0, depth=255.0): return Color(r / depth, g / depth, b / depth, a) def hsv(h, s, v, a=1.0): rgb = hsv_to_rgb(h, s / 100, v / 100) return Color(rgb[0], rgb[1], rgb[2], a) def hsv_to_rgb(h, s, v): c = v * s x = c * (1 - abs((h / d) % 2) - 1) m = v - c def get_tuple(c, x): if h < d: return (c, x, 0) elif h < d * 2.0: return (x, c, 0) elif h < d * 3.0: return (0, c, x) elif h < d * 4.0: return (0, x, c) elif h < d * 5.0: return (x, 0, c) else: return (c, 0, x) tup = get_tuple(c, x) return (tup[0], tup[1], tup[2]) def rgb_to_hsv(r, g, b): cmax = max(r, g, b) cmin = min(r, g, b) delt = cmax - cmin def get_hue(delt, cmax, cmin): val = 0 if delt == 0: return 0 elif cmax == r: val = ((g - b)/delt) elif cmax == g: val = ((b - r)/delt) elif cmax == b: val = ((r - g)/delt) val = (val * 60) % 360 return val def get_sat(delt, cmax): if cmax == 0: return 0 else: return (delt/cmax) return (get_hue(delt, cmax, cmin), get_sat(delt, cmax), cmax)
4a1758b1e38ae8cc6c1e20c6e5e2eb21bb352efc
dsurraobhcc/CSC-225-T1
/classes/class4/Coordinate.py
637
4.03125
4
import math ''' 2-dimensional coordinate (x, y) ''' class Coordinate(): # constructor def __init__(self, x, y): self.x = x # instance variable self.y = y # sqrt((x1 - x2)**2 + (y1 - y2)**2) def get_distance(self, other): return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2) # special method: override def __str__(self): return f'({self.x}, {self.y})' if __name__ == '__main__': origin = Coordinate(0, 0) # object: instance of Coordinate class point2 = Coordinate(3, 4) distance = origin.get_distance(point2) #print(distance) print(point2)
b19c76376f0ab525b33c9d829071322ad5d966d1
senavs/knn-from-scratch
/model/point.py
2,891
3.734375
4
import numpy as np class Point: def __init__(self, axis): """Point constructor :param axis: iterable with point coordinates :type: list, tuple and np.array :example: x y z w axis = [1, 0.3, 6.4, -0.2] """ self.axis = np.array(axis) def distance(self, other): """Euclidean distance between 2 points with n dimensions :param other: coordinates with same dimension of self :type: Point, list, tuple, np.array :example: np.array([-7, -4, 3]) Point(-7, -4, 3) [-7, -4, 3] (-7, -4, 3) :return: euclidean distance :type: float """ if not isinstance(other, Point): other = Point(other) # Euclidean distance return sum((self - other) ** 2) ** 0.5 def to_numpy(self): """Point class to np.array :return: self.axis :type: np.array """ return self.axis def to_list(self): """Point class to list :return: self.axis.tolist() :type: list """ return self.axis.tolist() def __add__(self, other): if isinstance(other, Point): return Point(self.axis + other.axis) return Point(self.axis + np.array(other)) def __radd__(self, other): return self.__add__(other) def __sub__(self, other): if isinstance(other, Point): return Point(self.axis - other.axis) return Point(self.axis - np.array(other)) def __rsub__(self, other): return self.__sub__(other) def __mul__(self, other): if isinstance(other, Point): return Point(self.axis * other.axis) return Point(self.axis * np.array(other)) def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): if isinstance(other, Point): return Point(self.axis / other.axis) return Point(self.axis / np.array(other)) def __rtruediv__(self, other): return self.__truediv__(other) def __floordiv__(self, other): if isinstance(other, Point): return Point(self.axis // other.axis) return Point(self.axis // np.array(other)) def __rfloordiv__(self, other): return self.__floordiv__(other) def __pow__(self, power, modulo=None): if modulo: return self.axis ** power % modulo return self.axis ** power def __eq__(self, other): if isinstance(other, Point): return max(self.axis == other.axis) return max(self.axis == other) def __getitem__(self, item): return self.axis[item] def __repr__(self): return f'Point{tuple(self.axis)}'
4d6a3be54d4d4c9ffcdb247783de1c5892aeb440
Kasrazn97/SMFinal_Project
/Country.py
3,644
3.859375
4
""" This module defines the attributes and methods of a Country class. Some countries are only 'senders', some are both senders and receivers. """ import pandas as pd import numpy as np class Country(): def __init__(self, data, num_agents, country_name): # input is a table with all info for a country, columns: 'country', '1', 'gdp', 'co2'... self.data = data self.data_diff = pd.DataFrame() self.population = num_agents self.num_of_immigrants = {k:0 for k in self.data.country} self.num_of_emmigrants = {k:0 for k in self.data.country} self._name = country_name self.timestep = 0 self.prob = list() # probability of being chosen as a distination self.restrictions = 0 self.destinations = ['Australia', 'Austria', 'Canada', 'Chile', 'Denmark', 'Finland', 'France', 'Germany', 'Greece', 'Ireland', 'Luxembourg', 'Netherlands', 'New Zealand', 'Norway', 'Portugal', 'Sweden', 'Switzerland', 'United Kingdom', 'United States'] self.community_network = None self.new_born = 0 self.new_agent = 0 def keep_brains(self): self.restrictions += 1 def get_data_diff(self): """ Returns the differences of all indicators of a given country and of all others """ self.data_diff = pd.DataFrame() if (self.timestep == 2)&(self._name == 'Iraq'): self.keep_brains() print('Restrictions introduced') data = self.data[self.data['year'] == self.timestep] for c in self.destinations: df = pd.DataFrame(data[data['country'] == c].iloc[0,1:] - data[data['country'] == self._name].iloc[0,1:]).T self.data_diff = self.data_diff.append(df, ignore_index=True) self.data_diff['beta0'] = np.ones(len(self.data_diff)) cols = self.data_diff.columns.tolist() cols = cols[-1:] + cols[:-2] # add beta0 as the first column self.data_diff = self.data_diff[cols] def set_country_probability(self): """ For a given country returns probabilities to go to other countries at step t """ self.prob = [] betas = np.array([1.679889e-02, -1.159363e-07, 1.323871e-03, 6.152302e-04, 5.340156e-04, 1.130067e-7]) # we will only define them here (they are set, unchangable values) denominator = 0 for i in range(len(self.data_diff)): country_data_diff = self.data_diff.loc[i].to_numpy() denominator += np.exp(np.dot(betas,country_data_diff)) for i in range(len(self.data_diff)): country_data_diff = self.data_diff.loc[i].to_numpy() p = np.exp(np.dot(betas, country_data_diff))/denominator # prob-s to go to other countries self.prob.append(p) def __repr__(self): """ Print info about the agent """ return f'{self._name}, number of immigrants: {self.num_of_immigrants}, number of emmigrants:{self.num_of_emmigrants}' def reporter(self): """ Collects data about a country at each step """ values = self.timestep, self._name, sum(self.num_of_immigrants.values()), sum(self.num_of_emmigrants.values()), self.population df = pd.DataFrame(values, index=None).T df.columns = ['step', 'country', 'num_of_immigrants', 'num_of_emmigrants', 'population'] return df def step(self): """ Update everything """ self.get_data_diff() # print(self._name, 'got diff') self.set_country_probability() self.timestep += 1
61e9dfa08cedc014078b24c551c82dcd30a2c12d
adeywojo/ATM
/validation.py
530
3.6875
4
def account_number_validation(account_number): if account_number: try: int(account_number) if len(str(account_number)) == 10: return True except ValueError: return False except TypeError: return False return False def user_input_validation(have_account): try: if int(have_account): return True except TypeError: print("Invalid Input. Please choose between options 1 & 2.") return False
06052c22928c9a4c9c7c4c8f59687e6694231ea7
Irkhammf/TBA_Tubes
/Lexical Analyzer_TBA.py
9,919
3.515625
4
import string print('-----------------------------------------------------------------------------------------------------') print('Selamat datang, silahkan lakukan chek validasi kata dengan menginputkan kata yang ada dalam daftar') print('Berikut adalah daftar kata yang bisa dichek pada lexical analyzer ini: ') print('ich, du, kleider, physik, saft, mais, studie, trinke, ernte, koche, nahen, tragen') print('-----------------------------------------------------------------------------------------------------') x = input() x = str(x) sentence = x input_string = sentence.lower()+'#' alphabet_list = list(string.ascii_lowercase) state_list = ['q0','q1','q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10', 'q11', 'q12', 'q13', 'q14' , 'q15', 'q16','q17', 'q18', 'q19', 'q20', 'q21', 'q22', 'q23', 'q24', 'q25', 'q26', 'q27', 'q28', 'q29' , 'q30', 'q31', 'q32', 'q33', 'q34', 'q35', 'q36', 'q37', 'q38', 'q40', 'q41'] transition_table = {} for state in state_list: for alphabet in alphabet_list: transition_table[(state, alphabet)] = 'error' transition_table[(state, '#')] = 'error' transition_table[(state, ' ')] = 'error' #spaces before input string transition_table['q0', ' ']='q0' #update the transition table for the following token: ich transition_table[('q0', 'i')]= 'q1' transition_table[('q1', 'c')]= 'q2' transition_table[('q2', 'h')]= 'q40' transition_table[('q40', ' ')]= 'q41' transition_table[('q40', '#')]= 'accept' transition_table[('q41', ' ')]= 'q41' transition_table[('q41', '#')]= 'accept' #transation for new token transition_table[('q41', 'i')]= 'q1' transition_table[('q41', 'e')]= 'q19' transition_table[('q41', 'm')]= 'q9' transition_table[('q41', 'd')]= 'q3' transition_table[('q41', 't')]= 'q30' transition_table[('q41', 'p')]= 'q4' transition_table[('q41', 'k')]= 'q24' transition_table[('q41', 's')]= 'q12' transition_table[('q41', 'n')]= 'q35' #update the transition table for the following token: du transition_table[('q0', 'd')]= 'q3' transition_table[('q3', 'u')]= 'q40' #update the transition table for the following token: trinke transition_table[('q0', 't')]= 'q30' transition_table[('q30', 'r')]= 'q31' transition_table[('q31', 'i')]= 'q32' transition_table[('q32', 'n')]= 'q33' transition_table[('q33', 'k')]= 'q18' transition_table[('q18', 'e')]= 'q40' #update the transition table for the following token: tragen transition_table[('q31', 'a')]= 'q34' transition_table[('q34', 'g')]= 'q37' #update the transition table for the following token: physik transition_table[('q0', 'p')]= 'q4' transition_table[('q4', 'h')]= 'q5' transition_table[('q5', 'y')]= 'q6' transition_table[('q6', 's')]= 'q7' transition_table[('q7', 'i')]= 'q8' transition_table[('q8', 'k')]= 'q40' #update the transition table for the following token: saft transition_table[('q0', 's')]= 'q12' transition_table[('q12', 'a')]= 'q13' transition_table[('q13', 'f')]= 'q14' transition_table[('q14', 't')]= 'q40' #update the transition table for the following token: studie transition_table[('q12', 't')]= 'q15' transition_table[('q15', 'u')]= 'q16' transition_table[('q16', 'd')]= 'q17' transition_table[('q17', 'i')]= 'q18' transition_table[('q18', 'e')]= 'q40' #update the transition table for the following token: nahen transition_table[('q0', 'n')]= 'q35' transition_table[('q35', 'a')]= 'q36' transition_table[('q36', 'h')]= 'q37' transition_table[('q37', 'e')]= 'q38' transition_table[('q38', 'n')]= 'q40' #update the transition table for the following token: kleider transition_table[('q0', 'k')]= 'q24' transition_table[('q24', 'l')]= 'q25' transition_table[('q25', 'e')]= 'q26' transition_table[('q26', 'i')]= 'q27' transition_table[('q27', 'd')]= 'q28' transition_table[('q28', 'e')]= 'q29' transition_table[('q29', 'r')]= 'q40' #update the transition table for the following token: koche transition_table[('q24', 'o')]= 'q22' transition_table[('q22', 'c')]= 'q23' transition_table[('q23', 'h')]= 'q18' transition_table[('q18', 'e')]= 'q40' #update the transition table for the following token: ernte transition_table[('q0', 'e')]= 'q19' transition_table[('q19', 'r')]= 'q20' transition_table[('q20', 'n')]= 'q21' transition_table[('q21', 't')]= 'q18' #update the transition table for the following token: mais transition_table[('q0', 'm')]= 'q9' transition_table[('q9', 'a')]= 'q10' transition_table[('q10', 'i')]= 'q11' transition_table[('q11', 's')]= 'q40' #lexical analysis idx_char = 0 state = 'q0' current_token = ' ' while state!='accept': current_char = input_string[idx_char] current_token += current_char state = transition_table[(state, current_char)] if state=='q40': print('current token: ', current_token, ', valid') current_token =' ' if state == 'error': print('current token: ', current_token, ', error') print('Maaf, kata yang anda masukan tidak valid') print('Silahkan periksa kembali kata yang anda masukan') break; idx_char = idx_char + 1 #conclusion if state == 'accept': print('semua token di input: ', sentence, ', valid') #PARSER GRAMMAR CHEKER #input example #x = input() #x = str(x) #sentence = x print() print('-----------------------------------------------------------------------------------------------------') print('Chek validasi kata dengan analyzer lexical telah selesai') print('Selanjutnya akan dichek aturan grammarnya') print('-----------------------------------------------------------------------------------------------------') tokens = sentence.lower().split() tokens.append('EOS') #symbols definition non_terminals = ['S', 'SB', 'VB', 'OB'] terminals = ['ich', 'du', 'kleider', 'physik', 'saft', 'mais', 'studie', 'trinke', 'ernte', 'koche', 'nahen', 'tragen'] #parse table definition parse_table = {} parse_table[('S', 'ich')] = ['SB', 'VB', 'OB'] parse_table[('S', 'du')] = ['SB', 'VB', 'OB'] parse_table[('S', 'kleider')] = ['error'] parse_table[('S', 'physik')] = ['error'] parse_table[('S', 'saft')] = ['error'] parse_table[('S', 'mais')] = ['error'] parse_table[('S', 'studie')] = ['error'] parse_table[('S', 'trinke')] = ['error'] parse_table[('S', 'ernte')] = ['error'] parse_table[('S', 'koche')] = ['error'] parse_table[('S', 'nahen')] = ['error'] parse_table[('S', 'tragen')] = ['error'] parse_table[('S', 'EOS')] = ['error'] parse_table[('SB', 'ich')] = ['ich'] parse_table[('SB', 'du')] = ['du'] parse_table[('SB', 'kleider')] = ['error'] parse_table[('SB', 'physik')] = ['error'] parse_table[('SB', 'saft')] = ['error'] parse_table[('SB', 'mais')] = ['error'] parse_table[('SB', 'studie')] = ['error'] parse_table[('SB', 'trinke')] = ['error'] parse_table[('SB', 'ernte')] = ['error'] parse_table[('SB', 'koche')] = ['error'] parse_table[('SB', 'nahen')] = ['error'] parse_table[('SB', 'tragen')] = ['error'] parse_table[('SB', 'EOS')] = ['error'] parse_table[('VB', 'ich')] = ['error'] parse_table[('VB', 'du')] = ['error'] parse_table[('VB', 'kleider')] = ['error'] parse_table[('VB', 'physik')] = ['error'] parse_table[('VB', 'saft')] = ['error'] parse_table[('VB', 'mais')] = ['error'] parse_table[('VB', 'studie')] = ['studie'] parse_table[('VB', 'trinke')] = ['trinke'] parse_table[('VB', 'ernte')] = ['ernte'] parse_table[('VB', 'koche')] = ['koche'] parse_table[('VB', 'nahen')] = ['nahen'] parse_table[('VB', 'tragen')] = ['tragen'] parse_table[('VB', 'EOS')] = ['error'] parse_table[('OB', 'ich')] = ['error'] parse_table[('OB', 'du')] = ['error'] parse_table[('OB', 'kleider')] = ['kleider'] parse_table[('OB', 'physik')] = ['physik'] parse_table[('OB', 'saft')] = ['saft'] parse_table[('OB', 'mais')] = ['mais'] parse_table[('OB', 'studie')] = ['error'] parse_table[('OB', 'trinke')] = ['error'] parse_table[('OB', 'ernte')] = ['error'] parse_table[('OB', 'koche')] = ['error'] parse_table[('OB', 'nahen')] = ['error'] parse_table[('OB', 'tragen')] = ['error'] parse_table[('OB', 'EOS')] = ['error'] #stack initialization stack = [] stack.append('#') stack.append('S') #input reading initialization idx_token = 0 symbol = tokens[idx_token] #parsing process try : while (len(stack) > 0): top = stack[len(stack)-1] print('top = ', top) print('symbol = ', symbol) if top in terminals: print('top adalah simbol terminal') if top==symbol: stack.pop() idx_token = idx_token + 1 symbol = tokens[idx_token] if symbol == 'EOS': print('isi stack: ', stack) stack.pop() else: print('error') break; elif top in non_terminals: print('top adalah simbol non-terminal') if parse_table[(top, symbol)][0] != 'error': stack.pop() symbols_to_be_pushed = parse_table[(top, symbol)] for i in range(len(symbols_to_be_pushed)-1,-1,-1): stack.append(symbols_to_be_pushed[i]) else: print('error') break; else: print('error') break; print('isi stack: ', stack) print() except KeyError : print('Kata tidak ditemukan dalam sistem') #conclusion print() if symbol == 'EOS' and len(stack) == 0: print('-----------------------------------------------------------------------------------------------------') print('Input string: ', sentence) print('Selamat!!!') print('Kalimat yang anda masukan diterima, karna sesuai Grammar') print('Terimakasih') print('-----------------------------------------------------------------------------------------------------') else : print('-----------------------------------------------------------------------------------------------------') print('Error, input string: ', sentence) print('Mohon Maaf') print('Kalimat yang anda masukan tidak diterima, karna tidak sesuai Grammar') print('atau terdapat kata yang tidak valid') print('Silahkan chek kembali kalimat yang anda masukan') print('Terimakasih') print('-----------------------------------------------------------------------------------------------------')
48055149e85ef7c7a9195c33f05c6ea033a59e27
bopopescu/HumanResourcesDepartment
/sum.py
281
3.515625
4
for i in range(10000): t = (i * 3 + 3) * 3 tSTR = str(t) sum = 0 for j in tSTR: sum += int(j) if sum != 9: print('Загадано: '+ str(i)+ ', Результат вычислений:'+str(t)+ ', Сумма результата: '+ str(sum))
e89a94f69dc6baa4a6da72d3a4f09e35afac8de5
Kenlin205/guess-num
/guess.py
484
4.125
4
import random start = int(input("Please choose an number to start -> ")) end= int(input("Please choose an number to end -> ")) r = random.randint(start,end) count = 0 while True: count += 1 # count = count +1 num = int(input("guess a number ->")) if num == r: print("you have guess it !!! ") print("This is" , count, "times guess") break elif num > r: print("bigger than answer ->") elif num < r: print("less than answer ->") print("This is" , count, "times guess")
4ccca9cf73186d3b5b42378dc7815108c5fcde00
b-meson/basic_crypto
/matasano/simplecrypt.py
2,399
3.515625
4
#!/usr/bin/python """ Solutions to Matasano's first set of cryptography challenges. As well as some bonus bits that might be useful for other things. """ import binascii import base64 import numpy as np import collections import string import array from string import ascii_lowercase import pdb def hex_to_ascii(hexstring): in_ascii = binascii.unhexlify(hexstring) return in_ascii def hex_to_base64(hexstring): in_base64 = base64.b64encode(hex_to_ascii(hexstring)) return in_base64 def base64_to_ascii(b64string): in_ascii = base64.b64decode(b64_input) return in_ascii def base64_to_hex(b64string): in_hex = binascii.hexlify(base64_to_ascii(b64string)) return in_hex def fixed_xor(string1, string2): xor_decimal = int(string1, 16) ^ int(string2, 16) xor_answer = hex(xor_decimal) return xor_answer.rstrip('L').lstrip('0x') def onechar_xor(singlechar, text): repeat_times = len(text)/2 test_key = singlechar * repeat_times xor_answer = fixed_xor( text,test_key.encode('hex')).zfill(len(text)) xor_ascii = xor_answer.decode('hex') # Fix \x00 and \x07 xor_ascii = xor_ascii.replace('\x00',' ') xor_ascii = xor_ascii.replace('\x07','\'') return xor_ascii def break_onechar_xor(ciphertext): keys = string.lowercase+string.uppercase # Baseline char frequencies english_weights = 0.065 # From Katz, Lindell crypto text test_weights = np.zeros(len(keys)) for x in range(0, len(keys)): # xor this key with the ciphertext xor_ascii = onechar_xor(keys[x], ciphertext) # score the result based on character frequencies test = collections.defaultdict(int) for y in string.lower(xor_ascii): test[y] += 1 normalize = float(len(xor_ascii)) intermed_weight = array.array('f') for z in ascii_lowercase: intermed_weight.append(test[z]/normalize) weights = np.array(intermed_weight) weight_score = sum(weights ** 2) test_weights[x] = weight_score # Determine which is the closest to English character frequencies key_index = np.abs(test_weights - english_weights).argmin(axis=0) key_answer = keys[key_index] answer_ascii = onechar_xor(key_answer, ciphertext) return key_answer, answer_ascii def detect_onechar_xor(ciphertexts): # Add return ciphertext
bc3a894231ff0bc416c22793b5fce3649192746a
Chencx901/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python
/Class.py
1,956
4.09375
4
# Fraction Class class Fraction(object): """docstring for Fraction""" def __init__(self, top,bottom): #初始化 self.den = bottom self.num = top def show(self): #展示函数 print(self.num,'/',self.den) # 重新定义__str__方法,后续可以使用print() def __str__(self): return str(self.num)+'/'+str(self.den) # arithmetic def __add__(self,fraction): newnum = self.num*fraction.den+self.den*fraction.num newden = self.den*fraction.den common = gcd(newnum, newden) return Fraction(newnum//common, newden//common) def __mul__(self,fraction): newnum = self.num*fraction.num newden = self.den*fraction.den common = gcd(newnum, newden) return Fraction(newnum//common, newden//common) def __sub__(self,fraction): newnum = self.num*fraction.den-self.den*fraction.num newden = self.den*fraction.den common = gcd(newnum, newden) return Fraction(newnum//common, newden//common) def __truediv__(self,fraction): newnum = self.num*fraction.den newden = self.den*fraction.num common = gcd(newnum, newden) return Fraction(newnum//common, newden//common) def __eq__(self,fraction): return self.num*fraction.den == self.den*fraction.num def __lt__(self,fraction): return self.num*fraction.den < self.den*fraction.num def __gt__(self,fraction): return self.num*fraction.den > self.den*fraction.num # GCD -- Euclid Algoritm,求最大公约数 def gcd(m,n): while m%n != 0: #终止条件:余数为0 d = m%n #取余数 m = n # 互换 n = d return n # test part if __name__ == "__main__": myf = Fraction(3,5) myf.show() print(myf) f1 = Fraction(1, 2) f2 = Fraction(1, 4) print(f1*f2) print(f1>f2)
4c57c8ee0302ea85dcb2df3a0ca569cb8a8af1d4
dsspasov/HackBulgaria
/week0/1-Python-simple-problems-set/problem5.py
367
3.921875
4
#problem5.py from problem4 import is_prime def prime_number_of_divisors(n): count = 2 for x in range(3,n): if(n%x==0): count = count +1 if(is_prime(n)): return True else: return False def main(): print (prime_number_of_divisors(8)) # a = prime_number_of_divisors(8) # if (a): # print("True") # else: # print("False") if __name__ == '__main__': main()
d9c28357ab0dd148db03cabf0f712527e1fdf32c
vpfeifer/evlutionary-computing-algorithms
/genetic/led_number_recognizer.py
9,767
3.6875
4
import random import numpy as np import matplotlib import matplotlib.pyplot as plotter # 0 - Imprime somente a geracao resultante # 1 - Imprime o resultado a cada geracao (populacao, aptidao de cada individuo, aptidao media) # 2 - Imprime os passos do algoritmo (selecao, reproducao, mutacao, avaliacao) # 3 - Imprime os detalhes da selecao dos individuos da proxima geracao verbose_level = 0 population_size = 8 target = [1,1,1,1,0,1,1,0,1,1,1,1] targetSize = len(target) crossover_rate = 0.5 mutation_rate = 0.02 execution_times = 1000 print "Reconhecer o 0 representado por",target print "Verbose level", verbose_level print "Tamanho da populacao :",population_size print "Taxa de crossover :", crossover_rate print "Taxa de mutacao :", mutation_rate print "Numero de execucoes",execution_times # Retorna um bit aleatorio que representa um gene. def gene(): return random.randint(0,1) def random_population_init(): initial_population = [] counter = 0 while counter < population_size: individual = [gene(), gene(), gene(), gene(), gene(), gene(), gene(), gene(), gene(), gene(), gene(), gene()] initial_population.append(individual) counter += 1 return initial_population def print_list(list, list_name): print "\n", list_name, "\n" i = 1 for item in list: print i, "- ", item i += 1 # Conta a quantidade de genes diferentes de um individuo em relacao ao alvo. def count_diff_genes(individual): diff = 0 i = 0 while i < targetSize: if target[i] != individual[i]: diff += 1 i+=1 return diff # Retorna o vetor das distancias de hamming da populacao def calculate_hamming_distance(population): hammingDistanceArray = [] for individual in population: diffBits = count_diff_genes(individual) hammingDistanceArray.append(diffBits) return hammingDistanceArray # Avalia a populacao def evaluate(population): h = calculate_hamming_distance(population) aptitudes = [] for item in h: aptitudes.append(targetSize - item) if verbose_level > 1: print "\n=== EVALUATION STEP ===" print "Target", target print_list(population, "Population") print "Target size", targetSize print "Hamming Array",h print "Aptitudes result", aptitudes return aptitudes # Gera o vetor com as faixas em graus da roleta def get_selection_ranges(aptitudes): init_range = 0 selection_ranges = [] generationAptitude = sum(aptitudes) for aptitude in aptitudes: individualRangeSize = 0 if generationAptitude == 0: individualRangeSize = 360/population_size else: individualRangeSize = float (360 * aptitude)/generationAptitude selection_ranges.append([init_range, individualRangeSize + init_range]) init_range += individualRangeSize if verbose_level > 2: print "\n\t=== GET SELECTION RANGES ===" print "\tAptitudes =", aptitudes print "\tSum aptitudes =",generationAptitude print_list(selection_ranges, "Selection Ranges") return selection_ranges # Realiza a selecao dos individuos para proxima geracao def selection(aptitudes, population): if verbose_level > 1: print "\n=== SELECTION STEP ===" selection_ranges = get_selection_ranges(aptitudes) selection_randoms = np.random.randint(360, size=population_size) if verbose_level > 1: print "Target", target print_list(population, "Population") print "Aptitudes", aptitudes print_list(selection_ranges,"Selection ranges") print "Random numbers", selection_randoms newGeneration = [] for srand in selection_randoms: if verbose_level > 2: print "\n\tThe random number", srand i = 0 for srange in selection_ranges: if srand >= srange[0] and srand <= srange[1]: if verbose_level > 2: print "\tMatch with", srange print "\tThen the individual",i, " - ",population[i],"from the population was selected" newGeneration.append(population[i]) i+=1 if verbose_level > 1: print_list(newGeneration, "New Generation Selected") return newGeneration # Faz o crossover e atualiza a populacao substituindo # os pais pelos filhos def make_crossover(population, couple_index): position = couple_index * 2 parent1 = population[position] parent2 = population[position+1] crossover_point = random.randint(0, targetSize-1) child1 = genetic_recombination(parent1, parent2, crossover_point) child2 = genetic_recombination(parent2, parent1, crossover_point) population[position] = child1 population[position+1] = child2 # Faz a recombinacao genetica dos pais e gera o filho def genetic_recombination(parent1, parent2, crossover_point): child = [] child.extend(parent1[:crossover_point]) child.extend(parent2[crossover_point:]) return child # Realiza a reproducao da populacao, podendo haver crossover # ou nao, baseado na taxa de crossover def reproduction(population): r = [random.random(), random.random(), random.random(), random.random()] for item in r: i = 0 if item < crossover_rate: make_crossover(population, i) i+=1 if verbose_level > 1: print "\n=== REPRODUCTION STEP ===" print "Target", target print_list(population, "Population") print "Crossover rate =", crossover_rate print "Random numbers =",r print_list(population, "Population after reproduction") # Realiza as mutacoes na populacao baseado na taxa de mutacao def mutation(population): if verbose_level > 1: print "\n=== MUTATION STEP ===" print "Mutation rate =", mutation_rate print "Target", target print_list(population, "Population") mutation_points = [] population_index = 0 for individual in population: individual_index = 0 while individual_index < targetSize: if random.random() < mutation_rate: mutation_points.append([population_index+1, individual_index+1]) individual[individual_index] = -individual[individual_index] + 1 individual_index+=1 population_index+=1 if verbose_level > 1: print "Tota mutations",len(mutation_points) print "Mutation points [Individual, Gene] =", mutation_points print_list(population, "Population after mutation") # Imprime os dados de uma geracao def print_generation_data(generationNumber, population, aptitudes): print "\n======== Geracao", generationNumber, " ========" print print_list(population, "Population") print "\nAptidoes =",aptitudes print "\nAptidao media da geracao =", float(sum(aptitudes)/population_size) # Condicao de parada def population_contains_target(aptitudes): for aptitude in aptitudes: if aptitude == targetSize: return True return False def execute_algorithm(generate_execution_chart): population = random_population_init() aptitudes = evaluate(population) # Dados para o grafico de uma execucao do algoritmo generations = [] aptitude_averages = [] max_aptitudes = [] min_aptitudes = [] generationsCounter = 1 while not population_contains_target(aptitudes): # Passos do algoritmo population = selection(aptitudes, population) reproduction(population) mutation(population) aptitudes = evaluate(population) # Dados para o grafico generations.append(generationsCounter) aptitude_avg = float(sum(aptitudes)/population_size) aptitude_averages.append(aptitude_avg) max_aptitudes.append(max(aptitudes)) min_aptitudes.append(min(aptitudes)) if verbose_level > 0: print_generation_data(generationsCounter, population, aptitudes) generationsCounter += 1 if generate_execution_chart: print_generation_data(generationsCounter, population, aptitudes) fig, ax = plotter.subplots() ax.plot(generations, aptitude_averages, label='Population Aptitude Average') ax.plot(generations, max_aptitudes, label='Max Aptitude') ax.plot(generations, min_aptitudes, label='Min Aptitude') handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels) ax.set(xlabel='Generations', ylabel='Aptitude',title='') ax.grid() fig.savefig("test.png") plotter.show() return generationsCounter executed = 0 # Dados para o grafico de todas as execucoes generations_needed_array = [] avg_array = [] max_array = [] min_array = [] executions = [] while executed < execution_times: generations_needed = execute_algorithm(False) generations_needed_array.append(generations_needed) executions.append(executed + 1) executed += 1 a = 0 avg_generations = sum(generations_needed_array)/len(generations_needed_array) max_val = max(generations_needed_array) min_val = min(generations_needed_array) while a < execution_times: max_array.append(max_val) min_array.append(min_val) avg_array.append(avg_generations) a+=1 fig, ax = plotter.subplots() ax.plot(executions, generations_needed_array, label='Generations Needed') ax.plot(executions, avg_array, label='Generations average') ax.plot(executions, min_array, label='Min Generation') ax.plot(executions, max_array, label='Max Generation') handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels) ax.set(xlabel='Executions') ax.grid() fig.savefig("test.png") plotter.show()
d9c5d76966d86de923ee31a678050096ce125e6e
3baaa/python-test
/10/10.py
2,895
3.65625
4
''' a = [1,2,3,4,5,6,3,3] r_set = {3,5} result = [i for i in a if i not in r_set] print(result) a = 'aaa' print(a*2) import math print(math.sqrt(25)) import math as m print(m.sqrt(25)) from math import sqrt print(sqrt(25)) from math import * print(pi) print(sqrt(25)) from math import sqrt as s print(s(25)) import urllib.request as r resp=r.urlopen('http://www.google.co.kr') print(resp.status) import s2 print(s2.b) print(s2.s(10)) from s2 import b,s print(b) print(s(10)) import person m = person.Person('마','2','서') m.greeting() from person import Person as p m = p('마',2,'서') m.greeting() import hello print('main.py __name__:',__name__) import calcp.operation import calcp.geometry print(calcp.operation.add(10,20)) print(calcp.operation.mul(10,20)) print(calcp.geometry.tri_area(30,40)) print(calcp.geometry.rect_area(30,40)) from calcp.operation import add, mul print(add(10,20)) print(mul(10,20)) import sys print(sys.path) import sys data=sys.stdin.readline().rstrip() print(data) r = min([1,2,3]) print(3) r = eval('(3+5) * 7') print(r) from itertools import permutations data = ['A','B','C'] r = list(permutations(data,3)) print(r) from itertools import combinations data = ['A','B','C'] r = list(combinations(data,2)) print(r) from itertools import product data = ['A','B','C'] r = list(product(data,repeat=2) ) print(r) from itertools import combinations_with_replacement data = ['A','B','C'] r = list(combinations_with_replacement(data,2)) print(r) import heapq def heapsort(i): h = [] result = [] for value in i: heapq.heappush(h,value) for i in range(len(h)): result.append(heapq.heappop(h)) return result result = heapsort([1,3,5,7,9,2,4,6,8,0]) print(result) import heapq heap = [] heapq.heappush(heap,4) heapq.heappush(heap,1) heapq.heappush(heap,7) heapq.heappush(heap,3) print(heapq.heappop(heap)) print(heap) import heapq def heapsort(i): h = [] result = [] for value in i: heapq.heappush(h,-value) for i in range(len(h)): result.append(-heapq.heappop(h)) return result result = heapsort([1,3,5,7,9,2,4,6,8,0]) print(result) from bisect import bisect_left,bisect_right a = [1,2,4,4,8] x = 4 print(bisect_left(a,x)) print(bisect_right(a,x)) from bisect import bisect_left,bisect_right def count_by_range(a,left_v,right_v): right_i = bisect_right(a,right_v) left_i = bisect_left(a,left_v) return right_i-left_i a = [1,2,3,3,3,3,4,4,8,9] print(count_by_range(a,4,4)) print(count_by_range(a,-1,3)) from collections import deque data = deque([2,3,4]) data.appendleft(1) data.append(5) print(data) print(list(data)) from collections import Counter counter = Counter(['r','b','r','g','b','b']) print(counter['b']) print(counter['g']) print(counter) print(dict(counter)) import math print(math.factorial(5)) print(math.sqrt(7)) print(math.gcd(21,14)) print(math.pi) print(math.e) '''
4ffc78535c0c63d8153dfdc80054316df8084aff
raffaellomarchetti/uri-python
/1873.py
1,094
3.734375
4
c=int(input()) while c > 0: a, b = input().split() a=a.lower() b=b.lower() if a=='lagarto': if b=='spock' or b=='papel': print('rajesh') elif b=='tesoura' or b=='pedra': print('sheldon') else: print('empate') elif a=='papel': if b=='pedra' or b=='spock': print('rajesh') elif b=='tesoura' or b=='lagarto': print('sheldon') else: print('empate') elif a=='pedra': if b=='tesoura' or b=='spock': print('rajesh') elif b=='papel' or b=='lagarto': print('sheldon') else: print('empate') elif a=='spock': if b=='tesoura' or b=='pedra': print('rajesh') elif b=='papel' or b=='lagarto': print('sheldon') else: print('empate') elif a=='tesoura': if b=='papel' or b=='lagarto': print('rajesh') elif b=='spock' or b=='pedra': print('sheldon') else: print('empate') c=c-1
dd59d47fa6ce522efa8682f9c5198d57c79fb257
jordan-carson/DataStructures-and-Algos
/ds_and_algos/structures/structures.py
392
3.765625
4
# class Stack class Node: def __init__(self, value): self.edges = list() self.value = value class Edge: def __init__(self, value, node_from, node_to): self.value = value self.node_from = node_from self.node_to = node_to class Graph: def __init__(self, nodes=list(), edges=list()): self.nodes = nodes self.edges = edges
073c8f9c727b9887b1ac5fd9851b54162d9eae84
victor-iyi/email-classification-challenge
/tools/staff_graph.py
3,597
3.59375
4
import community from matplotlib import pylab as pl import networkx as nx import numpy as np import pandas as pd def construct_graph(df_emails): '''From an email dataframe, output the biggest connected component of the graph where nodes are sender/recipients and edges are emails sent between them. Arguments: - df_emails (pd dataframe): the pd dataframe containing the emails Output: - G_connected (nx graph): biggest connected component of the graph ''' G = nx.Graph() for index, row in df_emails.iterrows(): sender = row["sender"] G.add_node(sender) recipients = row["recipients"] recipients_list = recipients.split() for rec in recipients_list: if "@" in rec: G.add_node(rec) G.add_edge(sender, rec, weight=1/len(recipients_list)) if not nx.is_connected(G): G_connected = next(nx.connected_component_subgraphs(G)) else: G_connected = G return G_connected def compute_teams(G): '''Split G into cluster according to Louvain algorithm Arguments: - G: the email graph Output: dictionary with two elements: - teams (list): team assignment for nodes in G. - n_classes (int): number of clusters ''' parts = community.best_partition(G) teams = {} for node in G.nodes(): teams[node] = parts.get(node) n_clusters = len(set(teams.values())) output_dict = {} output_dict["n_clusters"] = n_clusters output_dict["teams"] = teams output_dict["parts"] = parts return output_dict def assign_team(teams, n_clusters, email): '''Construct a vector to figure out in which team 'email' is. Arguments: - teams: assignmenet from Louvain algo. - n_clusters: number of clusters in the Louvain assignment - email (str): email address (one of the nodes of G) Output: - assignment (np.array): team assigned. ''' assignment = np.zeros(n_clusters) assignment[teams[email]] = 1 return assignment def compute_summary_graph(G, n_clusters, parts): '''Construct a summary graph to see the weights between classes and internal Arguments: - G: graph where each node is assigned to a team in 'parts'. - n_clusters: number of clusters in the Louvain assignment Output: - G_community (nx graph): team assigned. ''' G_community = nx.Graph() for node in G.nodes(): value = parts.get(node) G_community.add_node(value) for source_email, sink_email in G.edges(): source_value = parts.get(source_email) sink_value = parts.get(sink_email) if G_community.has_edge(source_value, sink_value): # we added this one before, just increase the weight by one G_community[source_value][sink_value]['weight'] += G.get_edge_data( source_email, sink_email )['weight'] else: # new edge. add with weight=weight in G G_community.add_edge( source_value, sink_value, weight=G.get_edge_data(source_email, sink_email)['weight']) # renaming nodes with their intern weight relabeling_dict = {} for node in G_community.nodes(): relabeling_dict[node] = int(G_community[node][node]['weight']) G_community = nx.relabel_nodes(G_community, relabeling_dict) return G_community
7942b4770f958373f8482d527200e06820a8904f
msabbir007/Introduction-to-Python
/Assignment(Round3)/kolmio.py
475
4.15625
4
# Johdatus ohjelmointiin # Introduction to programming # Area def area(a,b,c): s=(a+b+c)/2 import math tem=(s-a)*(s-b)*(s-c) result= math.sqrt(s*tem) return result def main(): line_a = float(input("Enter the length of the first side: ")) line_b = float(input("Enter the length of the second side: ")) line_c= float(input("Enter the length of the third side: ")) print("The triangle's area is ","{0:.1f}".format(area(line_a,line_b,line_c))) main()
2fa5dabf2e39eab6a5864e69fbf636fbcad55343
nidhiatwork/Python_Coding_Practice
/Lists/flipAndInvertImage.py
342
3.765625
4
def flipAndInvertImage(A): """ :type A: List[List[int]] :rtype: List[List[int]] """ result = [] for row in A: result.append(list(map(lambda x: 0 if x == 1 else 1, row[::-1]))) return result nums = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] print(flipAndInvertImage(nums))
1c4dcfa2aeb211442db69a230cd6d376a1e5897d
yamasampo/pathmanage
/huge_file_handler.py
10,302
3.734375
4
"""This script splits contents of one file into multiple files. Example ------- An input file contains >>ID1 >1 data >2 data >>ID2 >1 data >2 data >3 data ... >1000 data Then this script will output three files. One contains lines for the items for ID1 [outfile 1] >>ID1 >1 data >2 data The other two contain lines for the items for ID2. [outfile 2] >>ID2 >1 data >2 data >3 data >500 data [outfile 3] >>ID2 >501 data ... >1000 data ---------------- Change output files if - the first level ids change (i.e., ID1 -> ID2) - the number of items within the first level id exceed a given threshold if 500 is given as this number, the items of ID2 will be split into two files. The output files will have the first level ID. This process needs the following steps; - tell whether the current line is between the ids at the first level - count the number of items inside the first level id. Data can be output with a modification. Currently, this script supports the modification to remove redundant characters that appear at the beginning of the item. In this case, the order of members must be consistent across all the lines. """ import os import bz2 from typing import List from datetime import datetime from pathmanage import __version__ from nothingspecial.text import to_filelist from nothingspecial.keeplog import save_proc_setting_as_file def compress_all_files(input_dir, suffix, output_dir): """Read the entire file on memory and save into bzip file. For large file, we can add another option for read and output in chunk. lzma may be a good module for this possibility. This web article has a good demonstration: https://towardsdatascience.com/all-the-ways-to-compress-and-archive-files-in-python-e8076ccedb4b """ start = datetime.now().isoformat() input_args = { 'input_dir': input_dir, 'suffix': suffix, 'output_dir': output_dir } if not os.path.isdir(output_dir): os.mkdir(output_dir) log_file = os.path.join(output_dir, '0.log.txt') with open(log_file, 'a') as log_fh: save_proc_setting_as_file( log_fh, package_name = 'pathmanage', proc_desc = 'Compress all files in an input directory.', start_time = start, separator = ' = ', package_version = __version__, **input_args ) print('\n[Process log]', file=log_fh) in_fnames = [ fname for fname in os.listdir(input_dir) if fname.endswith(suffix) ] in_fpaths = [os.path.join(input_dir, fname) for fname in in_fnames] out_fnames = [ fname + '.bz2' for fname in in_fnames ] out_fpaths = [os.path.join(output_dir, fname) for fname in out_fnames] for in_fpath, out_fpath in zip(in_fpaths, out_fpaths): with open(in_fpath, 'rb') as in_fh, bz2.open(out_fpath, 'wb') as out_fh: out_fh.write(in_fh.read()) with open(log_file, 'a') as log_fh: print(f'\nOutput {out_fpath}') out_flist = to_filelist(output_dir) with open(log_file, 'a') as log_fh: print(f'A total of {len(out_flist)} files are saved.') return out_flist def split( input_file, output_file_prefix, max_item_num : int, item_prefixes : List[str] = [], item_separator : str = '\t' ): start = datetime.now().isoformat() # In case that user wants to remove prefixes that appear consistently # accross lines member_num = len(item_prefixes) contents = [] # Strings in this list will be output in the same file output_file_id = 1 first_level_id = '' second_level_item_num = 0 total_line_count = 0 total_file_count = 0 # Write input arguments to a log file input_args = { 'input_file': input_file, 'output_file_prefix': output_file_prefix, 'max_item_num': max_item_num, 'item_prefixes': item_prefixes, 'item_separator': item_separator } log_file = get_output_file_path(output_file_prefix, 'log') with open(log_file, 'a') as log_fh: save_proc_setting_as_file( log_fh, package_name = 'pathmanage', proc_desc = 'Split a huge file into multiple file.', start_time = start, separator = ' = ', package_version = __version__, **input_args ) print('\n[Process log]', file=log_fh) current_output_file_path = get_output_file_path( output_file_prefix, output_file_id ) # Get a file handler of the input file with open(input_file, 'r') as input_fh: # Access to each line from the top for l in input_fh: # Cut empty characters at the both ends. line = l.strip() if line == '': continue # If the current line indicates the first level ID if line.startswith('>>'): # If the current line is not the first item if first_level_id != '': # Output contents in output_lines to a file. current_output_file_path, contents = \ save_to_file_and_switch_output_file( contents, current_output_file_path, output_file_prefix, log_file, comment_line = '' ) total_file_count += 1 second_level_item_num = 0 first_level_id = line # If the current line indicates the second level ID elif line.startswith('>'): # If the number of second level ids is greater than a given value if second_level_item_num >= max_item_num: # Output contents in output_lines to a file. current_output_file_path, contents = \ save_to_file_and_switch_output_file( contents, current_output_file_path, output_file_prefix, log_file, comment_line = '' ) # If contents for one first level id are split into several, # Add the first level ID at the beginning in the next file. contents = [first_level_id] total_file_count += 1 second_level_item_num = 0 second_level_item_num += 1 # If the current line indicates data else: if member_num > 0: # Split a line to parts = line.split() # Check if the number of items matches to the expectation assert len(parts) == member_num modified_items = [ ''.join(item.split(exp_pref)[1:]) # Remove prefix for exp_pref, item in zip(item_prefixes, parts) if item.startswith(exp_pref) ] if len(modified_items) != member_num: msg = 'There is one or more items that do not start '\ f'with expected prefixes: \nObserved items: '\ f'{parts}\nExpected prefixes: {item_prefixes}' with open(log_file, 'a') as log_f: print(msg, file=log_f) raise ValueError(msg) line = item_separator.join(modified_items) contents.append(line) total_line_count += 1 # Output the remaining items current_output_file_path, contents = save_to_file_and_switch_output_file( contents, current_output_file_path, output_file_prefix, log_file, comment_line = '' ) total_file_count += 1 with open(log_file, 'a') as log_f: print(f'A total of {total_line_count} (except empty lines) lines are '\ f'recognized.', file=log_f) print(f'These lines are saved separately into {total_file_count} files.', file=log_f) return total_line_count, total_file_count def save_to_file_and_switch_output_file( contents : List[str], current_output_file_path : str, output_file_prefix : str, log_file : str, comment_line : str = '' ): # Output the contents to the current file with open(current_output_file_path, 'w') as f: if comment_line != '': print(comment_line, file=f) print('\n'.join(contents), file=f) with open(log_file, 'a') as log_f: print(f'Save contents to {current_output_file_path}.\n', file = log_f) # Get the next output file path curr_output_file_id = get_output_file_id_from_path(current_output_file_path) next_id = curr_output_file_id + 1 next_output_file_path = get_output_file_path(output_file_prefix, next_id) # Empty the contents contents = [] return next_output_file_path, contents def get_output_file_path(output_file_prefix, output_file_id): output_file_path = output_file_prefix + f'_{output_file_id}.txt' # Check if the file does not exist if os.path.isfile(output_file_path): raise FileExistsError(output_file_path) return output_file_path def get_output_file_id_from_path(file_path): return int(file_path.split('_')[-1].split('.')[0]) if __name__ == '__main__': import sys mode = sys.argv[1] if mode not in {'split', 'compress_all'}: raise ValueError('Please choose "split" or "compress_all"') if mode == 'split': split( sys.argv[2], sys.argv[3], int(sys.argv[4]), sys.argv[5].split(':'), item_separator = '\t' ) else: compress_all_files( sys.argv[2], sys.argv[3], sys.argv[4] )
a6227413b9490f64803c60d41446470cd1bb9a16
moenka/rc
/.bin/jsontree
668
3.5625
4
#!/usr/bin/env python3 """Print out the directory structure as json dict.""" from sys import argv import json import os def path_to_dict(path): d = {'name': os.path.basename(path)} if os.path.isdir(path): d['type'] = "directory" d['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir\ (path)] else: d['type'] = "file" return d def validate_path(path): return os.path.abspath(path) def main(): try: path = validate_path(argv[1]) except IndexError: print('Usage: jsontree <PATH>') else: print(json.dumps(path_to_dict(path))) if __name__ == "__main__": main()
5824bcb46d95ac0afe8029b521f2f45fbb138491
dinob0t/first_zero_in_binary_number
/first_zero_in_binary_number.py
441
3.921875
4
""" Algorithm to find the index of first zero in a binary number where index zero is furtherest right in array """ number = 20 bin_number = bin(number) print "Number is %d" %number print "Binary represendation is %s" %bin_number def get_first_zero(bin_number): for i in reversed(range(len(bin_number))): if bin_number[i] == "1": return len(bin_number) - i return -1 print "Index of the first 1 is: %d" %get_first_zero(bin_number)
693599e601211b8475b3cdeedfeb3b70360b0adb
xiao-a-jian/python-study
/剑指offer/3.two-dimensional_array.py
1,093
3.8125
4
""" 题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数 从右上角(左下角)开始找, 1)命中,查找成功 2)右上角数字比target大,删除最右一行 3)右上角比target小,删除上一行 PS:类似的,从左下角开始查找也是相同的道理。 PS2:该算法的利用的是夹逼的思想,不断从左右进行逼近,直至最终结果。 """ class Solution: def Find(self, target, array): m = len(array) - 1 n = len(array[0]) - 1 i = 0 while i <= m and n >= 0: if array[i][n] == target: return True elif array[i][n] > target: n -= 1 elif array[i][n] < target: i += 1 return False arr = [[1, 4, 8, 9], [4, 7, 10, 13]] target = 8 s = Solution() print(s.Find(target, arr))
26b1e8108601de13a6a25ad62f8dd2b6e7c854d8
10-15-5/Covid19-Tracker
/covidrequests.py
3,253
3.734375
4
import requests class ByCountryTotal: def __init__(self, country, date1, date2): """ :param country: The country that the user has chosen :param date1: The from date that will be sent to the Covid19 API :param date2: The to date that will be sent to the Covid19 API """ self.country = country self.date1 = date1 self.date2 = date2 def request(self): """ Sends the country, from date and to date to the API and gets back a list object as a response. :return list: Returns a list response got from the API """ url = "https://api.covid19api.com/total/country/" + self.country + "/status/confirmed" + "?from=" + \ str(self.date1) + "&to=" + str(self.date2) response = requests.get(url).json() return response[0] class CountryAllStatus: def __init__(self, country, date1, date2): """ :param country: The country that the user has chosen :param date1: The from date that will be sent to the Covid19 API :param date2: The to date that will be sent to the Covid19 API """ self.country = country self.date1 = date1 self.date2 = date2 def request(self): """ Sends the country, from date and to date to the API and gets back a list object as a response. :return list: Returns a list response got from the API """ url = "https://api.covid19api.com/country/" + self.country + "?from=" + str(self.date1) + \ "&to=" + str(self.date2) response = requests.get(url).json() return response[0] class ByCountryTotalAllStatus: def __init__(self, country): self.country = country def request(self): """ Sends the country to the API and gets back a list object as a response. :return list: Returns a list response got from the API """ url = "https://api.covid19api.com/total/country/" + self.country response = requests.get(url).json() return response class DayOne: def __init__(self, country): """ :param country: The country that the user has chosen """ self.country = country def request(self): """ Sends the country to the API and gets back a list object as a response. :return list: Returns a list response got from the API """ url = "https://api.covid19api.com/dayone/country/" + self.country + "/status/confirmed" response = requests.get(url).json() return response class WorldCases: def __init__(self, date1, date2): """ :param date1: The from date that will be sent to the Covid19 API :param date2: The to date that will be sent to the Covid19 API """ self.date1 = date1 self.date2 = date2 def request(self): """ Sends the from date and to date to the API and gets back a list object as a response. :return list: Returns a list response got from the API """ url = "https://api.covid19api.com/world/total" response = requests.get(url).json() return response
f8840974a55f960b4a9bcf8b236bb3f7a331c90f
Kblens56/ccbb_pythonspring2014
/2014-05-21_class_pt2.py
2,969
3.546875
4
import pandas import numpy cd documents/ccbb_pythonspring2014/ # open sites_complicated in pandas as an Excell file and then parse out Sheet 1 xl_c = pandas.ExcelFile('sites_complicated.xlsx') df_c = xl_c.parse('Sheet1') # how to output file in pandas # to write file in pandas and make csv will be called output.csv outfile = open('output.csv', 'w') df_c.to_csv(outfile) outfile.close() # to import all "*" from pandas from pandas import * # now can write excell file from pandas writer = ExcelWriter('output.xlsx') df_c.to_excel(writer, 'Sheet1') ## now moving onto ploting #import all "*" from ggplot from ggplot import * # open and parse sites simple xl = pandas.ExcelFile('sites_simple.xlsx') df = xl.parse('Sheet1', index_col = 0, header = 0) # make a plot saying what data will use etc my_plot = ggplot(df, aes(x = 'Expenditure', y = 'Species')) + geom_point() + xlim(0,350) + ylim(0,25) # to see plot my_plot #to save the plot # can save while looking at the plot by pushing the save button # or can save it programaticaly ggsave(my_plot, "demo_plot", "png") # now we will switch to working with a very large excel document # to import the data and name it big_matrix big_matrix = pandas.read_csv('big_matrix.csv') # to see the beginning of "big_matric" big_matrix.head() # this is what I see, April saw several of the first columns I assume this is a setting thing Out[37]: <class 'pandas.core.frame.DataFrame'> Int64Index: 5 entries, 0 to 4 Columns: 1001 entries, 0 to 0.5034046342 dtypes: float64(1000), int64(1) # to import te dat in a slightly differnt way ... not sure why the collumn now says entries 0 to 100 instead of 1 to 0.5 big_matrix = pandas.read_csv('big_matrix.csv', index_col=None, header=None) big_matrix.head() Out[40]: <class 'pandas.core.frame.DataFrame'> Int64Index: 5 entries, 0 to 4 Columns: 1001 entries, 0 to 1000 dtypes: float64(1000), int64(1) # to add a 1002nd collumn that will say Me for the first 250 rows and then My_Labmate for the rest of the rows big_matrix['1002'][0:250] = 'Me' big_matrix['1002'][250:] = 'My_Labmatee' # to display a sample of what column 1002 looks like big_matrix['1002'] # this is what it looks like Out[49]: 0 Me 1 Me 2 Me 3 Me 4 Me 5 Me 6 Me 7 Me 8 Me 9 Me 10 Me 11 Me 12 Me 13 Me 14 Me ... 485 My_Labmatee 486 My_Labmatee 487 My_Labmatee 488 My_Labmatee 489 My_Labmatee 490 My_Labmatee 491 My_Labmatee 492 My_Labmatee 493 My_Labmatee 494 My_Labmatee 495 My_Labmatee 496 My_Labmatee 497 My_Labmatee 498 My_Labmatee 499 My_Labmatee Name: 1002, Length: 500, dtype: object # make a plot where me and my labmates data are differnt colors on a scatterplot overlay = ggplot(aes(x=big_matrix.ix[0:499,2], y = big_matrix.ix[:,1], color='1002'), data=big_matrix) + geom_point() +geom_jitter() + ylab("Y Axis") + xlab("X Axis") +ylim(0,1) + xlim(0,1) + theme_bw() # to see plot overlay
224d21d56bb2a280def3c051ad798a472b4a18b6
wook0709/python
/class_prac.py
2,043
4.03125
4
''' python class 일반적인 c++ 이나 java에서 사용되는 class의 개념과 동일함. 인스턴스화 및 oop의 개념에 대한 부분을 python에서도 제공하고 있음 또한 global keyword를 통해 전역 변수도 지원해주고 있음. ''' result = 0 def adder(num): global result result += num return result print(adder(2)) print(adder(3)) ''' 위의 예제에서 다중 adder가 필요한 경우 별도의 이름으로 함수를 여러개 생성하여 사용하여야 한다. class를 통한 인스턴스화로 해당 문제를 해결 할 수 있다. ''' class Calcul: def __init__(self): self.result = 0 def adder(self, num): self.result += num return self.result cal1 = Calcul() cal2 = Calcul() print(cal1.adder(3)) print(cal1.adder(4)) print(cal2.adder(5)) print(cal2.adder(6)) #pass keyword는 real로다 pass다. class Simple: def sum(self,a,b): result = a+b print("%s + %s = %s 입니다." % (a, b, result)) test = Simple() test.sum(10,20) ''' self는 해당 인스턴스 명을 넘겨주게 된다. 해당 인스턴스 명은 class type을 체크하는 역할을 하는듯 하다. self라는 변수를 클래스 함수의 첫번째 인수로 받는것은 파이썬만의 특징이라고 한다. (in jump2python) getter / setter 이용시 self 는 this 키워드랑 비슷하다고 생각된다. python 에도 this 키워드가 있는지 확인필요. ''' class Pass: pass #pass는 임시로 코드 작성시 사용하는 키워드 ''' init 함수는 생성자 함수인듯하다. self의 사용에 대해서는 익숙해져야 할듯하다. this keyword라기 보다는 뭔가 인스턴스의 id값을 위한 처리라고 생각하는것이 편할 ''' class Service: secret ='this is secret' def __init__(self, name): self.name = name def sum(self, a, b ): result = a + b print("%s님 %s + %s = %s" %(self.name , a , b , result)) wook = Service('욱') wook.sum(1,1)
3bd4393d5f1ded92b7c4c9c451137cccdec3adac
reemahs0pr0/Machine-Learning
/Exercise 5 More Classification.py
1,640
3.625
4
#!/usr/bin/env python # coding: utf-8 # # More Classification - Decision Tree # In[27]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import sklearn # In[28]: df_train = pd.read_csv('LoanProfile-training.csv') df_test = pd.read_csv('LoanProfile-test.csv') # In[29]: df_train # In[30]: print(df_train['Age'].mean()) print(df_train['Creditdebt'].mean()) # In[31]: def agefunction(age): if age > 36.7: return 1 else: return 0 def credfunction(cred): if cred > 1.67: return 1 else: return 0 def deffunction(x): if x == 'N': return 0 else: return 1 df_train['Age'] = df_train['Age'].apply(agefunction) df_train['Creditdebt'] = df_train['Creditdebt'].apply(credfunction) df_train['Default'] = df_train['Default'].apply(deffunction) df_train # In[32]: df_test['Age'] = df_test['Age'].apply(agefunction) df_test['Creditdebt'] = df_test['Creditdebt'].apply(credfunction) df_test['Default'] = df_test['Default'].apply(deffunction) df_test # In[33]: X_train = df_train.iloc[:,0:2] X_test = df_test.iloc[:,0:2] y_train = df_train['Default'] y_test = df_test['Default'] # In[35]: from sklearn.tree import DecisionTreeClassifier dt = DecisionTreeClassifier() dt.fit(X_train, y_train) # In[37]: y_pred = dt.predict(X_test) # In[38]: from sklearn.metrics import accuracy_score accuracy_score(y_test, y_pred) # In[40]: from sklearn import tree import graphviz from graphviz import Source Source(tree.export_graphviz(dt, out_file=None, class_names=['No', 'Yes'], feature_names= X_train.columns))
9aae564f7d723b41afe0c65dae0474342dd2bd6a
YoupengLi/leetcode-sorting
/Solutions/0055_canJump.py
1,658
4.1875
4
# -*- coding: utf-8 -*- # @Time : 2019/4/7 0007 20:20 # @Author : Youpeng Li # @Site : # @File : 0055_canJump.py # @Software: PyCharm ''' 55. Jump Game Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example 1: Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. ''' class Solution: def canJump(self, nums: 'List[int]') -> 'bool': if not nums or len(nums) <= 0: return True goal = len(nums) - 1 for i in range(len(nums)-1)[::-1]: if i + nums[i] >= goal: goal = i return not goal def canJump_1(self, nums: 'List[int]') -> 'bool': m = 0 for i, n in enumerate(nums): if i > m: return False m = max(m, i + n) return True if __name__ == "__main__": a = Solution() nums = [2, 3, 1, 1, 4] res = a.canJump(nums) print(res) res = a.canJump_1(nums) print(res) nums = [3, 2, 1, 0, 4] res = a.canJump(nums) print(res) res = a.canJump_1(nums) print(res) nums = [3, 4, 1, 0, 4] res = a.canJump(nums) print(res) res = a.canJump_1(nums) print(res)
df528a14d0a076e9c5ae6bc0938fb2a94a0da201
kellytranha/cs5001
/hw12/connect_four/game_controller.py
1,465
3.625
4
from board import Board from chip import Chip from random import choice YELLOW = color(255, 255, 0) RED = color(249, 16, 0) class GameController: """ Maintains the state of the game and manages interactions of game elements. """ def __init__(self, num_row, num_col, side): """Initialize the game controller""" self.num_row = num_row self.num_col = num_col self.side = side self.board = Board(self.num_row, self.num_col, self.side) self.delay = 35 def update(self, mouse_pressed, mouse_x, mouse_y): """Updates game state on every frame""" # Delay if not self.board.is_red: if self.delay < 35: self.delay += 1 else: random_col = choice(self.board.find_avai_cols()) row = self.board.find_avai_row(random_col) self.board.add_chip(row, random_col) # Hover the chip if mouse_pressed and mouse_y <= self.side and self.delay >= 35: col = mouse_x // self.side self.board.display_temp_chip(col) # Show game board self.board.display() def handle_mousereleased(self, mouse_x, mouse_y): if mouse_y <= self.side and self.delay >= 35: col = mouse_x//self.side row = self.board.find_avai_row(col) if row > 0: self.board.add_chip(row, col) self.delay = 0
aaf0c419e15269a23cd779d15aa620dbab2ec5b7
forvicky/python_learn_new
/func_learn.py
739
4.125
4
""" 函数 """ def student_info(name,age=18,address='人民路小学'): # 默认参数 return name,age,address #返回多参序列 #序列拆包,最好用多个变量来接受多参返回值,这样每个变量含义比较明确 name,age,address=student_info('zww') print(name,age,address) name,age,address=student_info('zdd',address='柳园小学') #指定参数 print(name,age,address) """ 匿名函数 """ def add(x,y): return x+y print(add(1,2)) f= lambda x,y:x+y print(f(1,2)) #条件为真时返回的结果 if 条件判断 else 条件为假时返回的结果 a = 2 b = 1 r = a if a > b else b print(r) list_x= [1,0,1,0,1,0] r=filter(lambda x:True if x ==1 else False,list_x) print(list(r))
ad438b481ccadb3aaa816781a2538ab0f48fd0f5
WoodsChoi/algorithm
/al/al-81.py
1,977
3.75
4
# 搜索旋转排序数组 II ''' 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。 编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true,否则返回 false。 示例 1: 输入: nums = [2,5,6,0,0,1,2], target = 0 输出: true 示例 2: 输入: nums = [2,5,6,0,0,1,2], target = 3 输出: false ---------------------------------------- 题解: 和 al-33 一样二分法,只不过在二分法之前多了一层 head,i,tail 三个元素判断,比较下大小 如果相同,那么就无法判断二分法该向哪个方向,所以要从 head 到 tail 遍历一遍 ''' class Solution: def search(self, nums, target: int) -> int: l = len(nums) if l == 0: return False head, tail = 0, l - 1 i = tail // 2 while nums[i] != target: if head == tail: return False if target == nums[head]: return True if target == nums[tail]: return True if nums[head] == nums[tail] and nums[head] == nums[i]: for i in range(head, tail + 1): if nums[i] == target: return True return False if nums[0] > nums[i]: if target < nums[0] and target >= nums[i]: head = i + 1 i = (head + tail) // 2 else: tail = i i = (head + tail) // 2 else: if target < nums[i] and target >= nums[0]: tail = i i = (head + tail) // 2 else: head = i + 1 i = (head + tail) // 2 return True solution = Solution() res = solution.search([1,3,1,1,1], 3) print(res)
ac8916031d34706842bb0d3765cdc82fc8f9bc02
cristianS97/patterns
/piramide.py
1,169
3.9375
4
try: pisos = abs(int(input("Ingrese la cantidad de pisos de la piramide: "))) except ValueError: print("El valor ingresa no es un número, se usara el valor 3") pisos = 3 print("Manera clásica") for piso in range(pisos): for espacio in range(pisos - piso): print(" ", end="") for asterisco in range((2*piso)+1): print("*", end="") print() print("\n") for piso in range(pisos): for espacio in range(piso + 1): print(" ", end="") for asterisco in range(((pisos * 2) - ((2 * piso) + 1))): print("*", end="") print() print("\n") print("Manera resumida") for piso in range(pisos): print(" " * (pisos - piso), end="") print("*" * ((2*piso)+1)) print("\n") for piso in range(pisos): print(" " * (piso + 1), end = "") print("*" * ((pisos * 2) - ((2 * piso) + 1))) print("\n") print("Diamante") for piso in range(pisos): print(" " * (pisos - piso), end="") print("*" * ((2*piso)+1)) print("*" * ((2*pisos)+1)) for piso in range(pisos): print(" " * (piso + 1), end = "") print("*" * ((pisos * 2) - ((2 * piso) + 1))) input("Presione una tecla para continuar...")
9ed14f7fea49d8c693e1a6521dfc06a5af05907d
matteokg/PDXcodeguild-fullstack-night-03052018
/madlibs.py
914
3.671875
4
Adjective1 = input("Tell me an adjective and press enter.") Adjective2 = input("Give me another adjective.") Adjective3 = input("One more adjective") Noun1 = input("Hit me with a noun") Noun2 = input("Another noun") Number1= input("Give me a number") Number2= input("Another Number") Partofbody= input("What's a part of the body?") Personyouknow = input("Who is someone you know?") Pluralnoun1 = input("Plural Noun?") Pluralnoun2 = input("Another Plural noun?") Pluraloccupation = input("Plural occupation?") print("Many future big league baseball" + ' ' + Pluralnoun1 + ' ' + "Are being trained in little league today. The little leaguers are just like the big league" + ' ' + Pluralnoun2 + ' ' + "Except that the players are all between" + ' ' + Number1 + "and" + Number2 + "years old. When a" + Noun1 + ".goes out for a Little League team, he is given" + Adjective1 + ".tests in fielding fast" + Pluralnoun2)
6968c7ad0f088ff9f94acab28347da75a9151e60
timebird7/Solve_Problem
/SWEA/1224.py
1,537
3.6875
4
class Stack: def __init__(self): self.stack = [0]*50 self.pnt = 0 def push(self, x): self.stack[self.pnt] = x self.pnt += 1 def pop(self): if self.pnt == 0: return None else: self.pnt -= 1 return self.stack[self.pnt] def isEmpty(self): return self.pnt == 0 def peek(self): if self.pnt == 0: return None else: return self.stack[self.pnt-1] for tc in range(10): n = input() s = input() lst = ['(',')','+','*'] stack = Stack() ans = '' for c in s: if c == '(': stack.push(c) elif c == ')': while stack.peek() != '(': ans += stack.pop() stack.pop() elif c == '+': while stack.peek() == '+' or stack.peek() == '*': ans += stack.pop() else: stack.push(c) elif c == '*': while stack.peek() == '*': ans += stack.pop() else: stack.push(c) else: ans += c while not stack.isEmpty(): ans += stack.pop() nsum = Stack() for c in ans: if c == '+': x = nsum.pop() y = nsum.pop() nsum.push(x+y) elif c == '*': x = nsum.pop() y = nsum.pop() nsum.push(x*y) else: nsum.push(int(c)) print(f'#{tc+1} {nsum.stack[0]}')
89a0408fd1acf3e735dfbbd460118a64933b09fa
poipiii/app-dev-tutorial
/prac-test-revision/q3.py
5,831
3.796875
4
class Book: def __init__(self,isbn,title,author,quantity): self.__isbn = isbn self.__title = title self.__author = author self.__quantity = quantity def set_isbn(self,isbn): self.__isbn = isbn def set_title(self,title): self.__title = title def set_author(self,author): self.__author = author def set_quantity(self,quantity): self.__quantity = quantity def get_isbn(self): return self.__isbn def get_title(self): return self.__title def get_author(self): return self.__author def get_quantity(self): return self.__quantity #def __str__(self): # return 'There are {} copies of {} ({}) written by {}'.format(self.get_quantity(),self.get_title(),self.get_isbn(),self.get_author()) # #b = Book('012345678901z','Python for Everyone','Python King',100) # #print(b) class BookStore: def __init__(self): self.books = {} #self.create_dummy_books() self.load_books() def create_dummy_books(self): file = open('prac-test-revision/books.txt', 'w') file.write('012345678901z,Python for Everyone,Python King,100\n') file.write('112345678901y,Intermediate Python,John Python,200\n') file.write('212345678901x,Advanced Python,Anaconda,300\n') file.write('312345678901v,Beginner Python,Twisted Python,400\n') file.close() # initialize the books attribute with data from books.txt file def load_books(self): file = open('prac-test-revision/books.txt', 'r') for i in file: try: book = i.rstrip('\n').split(',') isbn = book[0] title = book[1] author = book[2] quantity = book[3] obj = Book(isbn,title,author,quantity) self.books[isbn] = obj except IndexError: pass file.close() # display all the book isbn and titles def display(self): for i in self.books.values(): print('There are {} copies of {} ({}) written by {}'.format(i.get_quantity(),i.get_title(),i.get_isbn(),i.get_author())) bs = BookStore() bs.display() #class BookStore: # def __init__(self): # self.books = {} # self.create_dummy_books() # self.load_books() # # def create_dummy_books(self): # file = open('prac-test-revision/books.txt', 'w') # file.write('012345678901z,Python for Everyone,Python King,100\n') # file.write('112345678901y,Intermediate Python,John Python,200\n') # file.write('212345678901x,Advanced Python,Anaconda,300\n') # file.write('312345678901v,Beginner Python,Twisted Python,400\n') # file.close() # # # initialize the books attribute with data from books.txt file # def load_books(self): # file = open('prac-test-revision/books.txt', 'r') # for i in file: # book = i.rstrip('\n').split(',') # self.isbn = book[0] # self.title = book[1] # self.author = book[2] # self.quantity = book[3] # self.books[self.isbn] = self.isbn,self.title,self.author,self.quantity # file.close() # # # # display all the book isbn and titles # def display(self): # print(self.books) # #bs = BookStore() #bs.display() # import random # fruit = {} # class Fruit: # def __init__(self, name, desc): # self.name = name # self.desc = desc # # This function # # (1) ask the user to enter the fruit name and description 3 times. # # (2) store the Fruit object in a dictionary # ''' # Sample output: # Enter the fruit name: Apple # Enter the description of the fruit: Snow White ate this fruit # Enter the fruit name: Orange # Enter the description of the fruit: Many people buy this fruit for CNY # Enter the fruit name: Watermelon # Enter the description of the fruit: This fruit is big and round. # ''' # def store_fruits(): # for i in range(3): # fruit_name = input('Enter the fruit name:') # fruit_desc = input('Enter the description of the fruit:') # f = Fruit(fruit_name,fruit_desc) # fruit[i+1] = f # # This function: # # 1. Randomly pick a fruit from the dictionary and display its description # # 2. Ask the user to guess the fruit. User will be given 3 chances. # # 3. If the user guesses correctly or used up the 3 chances, ask the user if he wants to try again. # # 4. If yes, repeat step 2 to 4. If no, exit. # ''' # Sample output: # Description of the fruit: # Snow White ate this fruit. # Guess a fruit: orange # You have 2 chance(s) left # Guess a fruit: apple # Bingo # Do you want to try again (Y/N)? y # Description of the fruit: # Many people carry this fruit during CNY # Guess a fruit: pear # You have 2 chance(s) left # Guess a fruit: apple # You have 1 chance(s) left # Guess a fruit: banana # You have 0 chance(s) left # Do you want to try again (Y/N)? n # ''' # def guess(): # chance = 3 # num = random.randint(1,3) # while True: # if chance > 0: # print(fruit[num].desc) # guess = input('Guess a fruit:') # if guess == fruit[num].name: # print('bingo') # again = input('Do you want to try again (Y/N)?') # if again.lower() == 'n': # break # else: # chance = 3 # num = random.randint(1,3) # continue # else: # chance -= 1 # print('you have {} chance(s) left'.format(chance)) # continue # else: # again = input('Do you want to try again (Y/N)?') # if again.lower() == 'n': # break # else: # chance = 3 # num = random.randint(1,3) # continue # store_fruits() # guess()
40c77aa9a0da6954c90b0442f0af82f4e9e41ad7
Vladyslav92/PythonIntro02
/lesson_03/example_1.py
519
4.0625
4
# Проверка принадлежит ли точка окружности. # Исходные данные: # x0, y0 - координаты центра окружности # r - радиус # x, y - координаты точки msg = ('Point coordinate X: ', 'Point coordinate Y: ', 'Circle center of coordinate X: ', 'Circle center of coordinate Y: ', 'Radius of circle: ') x, y, x0, y0, r = (float(input(msg[i])) for i in range(5)) print("YES" if (x - x0) ** 2 + (y - y0) ** 2 <= r * r else "NO")
aebeaed28bb5fb0604c11be2e2fcdb99f367c6a2
sje30/ATI-Feb20
/practical/main.py
4,446
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 3 11:45:14 2018 backprop for the XOR problem. 19th March 2019 JVS modified code and added graphics. """ import numpy as np import matplotlib.pyplot as plt # set random seed so get same sequence of random numbers each time prog is run. np.random.seed(1) ########## set input and output values ########## # set input vectors for XOR #Input array X = np.array([[0,0], [0,1], [1,0] , [1,1]]) # set output values for XOR targetvectors = np.array([[0],[1],[1],[0]]) # define unit activcation function as sigmoid function def sigmoid (x): return 1/(1 + np.exp(-x)) # define derivative of Sigmoid Function def derivatives_sigmoid(x): return x * (1 - x) ########## set parameters ########## niter = 3000 # number of training iterations plotinterval = 100 # interval between plotting graphs errors = np.zeros(niter) # record of errors during training numcorrects = np.zeros(niter) # number of correct outputs during training # decide if want to have sigmoidal or linear output units sigmoidalOutputUnits = 1 if (sigmoidalOutputUnits): lr = 0.5 # learning rate else: lr = 0.1 # learning rate inputlayer_neurons = X.shape[1] # number of units in input layer hiddenlayer_neurons = 2 # number of hidden layer units output_neurons = 1 # number of units in output layer # weight and bias initialization # weights between input and hidden layer wh = np.random.uniform(size=(inputlayer_neurons,hiddenlayer_neurons)) # biases of hidden layer units bh = np.random.uniform(size=(1,hiddenlayer_neurons)) # weights of output layer units wout = np.random.uniform(size=(hiddenlayer_neurons,output_neurons)) # biases of output layer units bout = np.random.uniform(size=(1,output_neurons)) ########## SET UP GRAPHS ########## # set interactive plotting on, so graphs appear outside of console. plt.ion() fig, axes = plt.subplots(1,2) axerror = axes[0] axnumcorrect = axes[1] axerror.set_xlabel('Epoch') axerror.set_ylabel('Error') axnumcorrect.set_ylabel('Number correct') axnumcorrect.set_xlabel('Epoch') # set state of bias unit; this code works if set to -1 or +1. biasunitstate = 1.0 ########## LEARN ########## for iter in range(niter): # Forward Propogation hidden_layer_input1 = np.dot(X,wh) # input from input layer hidden_layer_input = hidden_layer_input1 + bh*biasunitstate # add input from bias unit hiddenlayer_states = sigmoid(hidden_layer_input) output_layer_input1 = np.dot(hiddenlayer_states,wout) output_layer_input= output_layer_input1 + bout * biasunitstate # Backpropagation # get derivatives of errors wrt unit inputs ... # ... of output layer if (sigmoidalOutputUnits): output = sigmoid(output_layer_input) slope_output_layer = derivatives_sigmoid(output) else: # output units are linear output = output_layer_input slope_output_layer = output*0 + 1 # each derivative = 1 d = targetvectors - output # delta terms = errors in output layer # get derivatives of errors wrt unit inputs of hidden units slope_hidden_layer = derivatives_sigmoid(hiddenlayer_states) # get delta terms of output units = d_output d_output = d * slope_output_layer Error_at_hidden_layer = d_output.dot(wout.T) d_hiddenlayer = Error_at_hidden_layer * slope_hidden_layer # update weights of output units wout += hiddenlayer_states.T.dot(d_output) * lr # update biases of output units bout += np.sum(d_output, axis=0,keepdims=True) * biasunitstate * lr # update weights and biases of hidden units wh += X.T.dot(d_hiddenlayer) * lr bh += np.sum(d_hiddenlayer, axis=0,keepdims=True) * biasunitstate * lr error = np.linalg.norm(d) errors[iter] = error # count number of correct responses a = (output<0.5) b = (targetvectors<0.5) numcorrect = sum(a==b) numcorrects[iter] = numcorrect ########## Plot ########## if (iter % plotinterval == 0): axerror.plot(errors[0:niter],'k') plt.show() plt.pause(0.001) axnumcorrect.plot(numcorrects[0:niter],'k') plt.show() plt.pause(0.001) ########## Print results ########## print('Target values') print(targetvectors) print('Output values') print(output) error=np.linalg.norm(d) #print(i) print('Final error:') print(error) ########## The End ##########
e7366b4749ad9c7f68a1848790c7dea404ed67ff
MulderPu/legendary-octo-guacamole
/codewars/valid_phone_number.py
280
4.125
4
def validPhoneNumber(phoneNumber): if ' ' not in phoneNumber: return False elif '-' not in phoneNumber: return False elif len(phoneNumber) > 14: return False return True phoneNumber = "(323) 456-7890" print(validPhoneNumber(phoneNumber))
f9f6db5dc557e5c54fc4f354da644bd153205264
kisstom/cppdist
/src/scripts/main/common/data_gen/generate_biased.py
580
3.75
4
import sys, random def randomize(x, y, max): global maxP, minP if x < max / 2 and y < max /2: if random.random() < maxP: return 1 elif x >= max / 2 and y >= max /2: if random.random() < maxP: return 1 else: if random.random() < minP: return 1 return 0 numRow = int(sys.argv[1]) maxP = float(sys.argv[2]) minP = float(sys.argv[3]) for x in xrange(numRow): first = True for y in xrange(numRow): coin = randomize(x, y, numRow) if coin: if first: print '%d'%y, first = False else: print '%d'%y, print
b4277e4de6dad0d959ec366f6defd576745a1a94
jsyoungk/CodingDojoAssignments
/python_time_time/MSA.py
308
3.78125
4
#for x in range (1, 1000): #if (x%2==1): #print x #print range(5,100000,5) a=[1,2,5,10,255,3] def sumList(a): aSum = sum(a) print(aSum) aAvg = aSum/len(a) print aAvg sumList([1,2,3]) sumList(a) #this is how you make it into a function num = (1, 5, 7, 3, 8) print sorted(num)
259a03cee33be7e44c9be208cafe632d50ab6619
yassh-pandey/Data-Structures
/stack1.py
881
4.03125
4
class Stack(): def __init__(self, *args): self.list = list(args) def push(self, item): self.list.append(item) def display(self): for index, item in enumerate(self.list): if index == ( len(self.list) - 1 ): print("{}".format(item)) else: print("{} ->".format(item), end=" ") def pop(self): if self.isEmpty(): print("Stack is empty so can't perform pop operation !") else: return self.list.pop() def top(self): if self.isEmpty(): print("Stack is empty so top operation will return null !") else: return self.list[-1] def isEmpty(self): return len(self.list) == 0 # l = Stack() # l.push(1) # l.push(2) # l.push(3) # l.pop() # l.pop() # l.pop() # print(l.isEmpty()) # l.pop()
4418f0401eb37afa6791fb8d2fb39d8703d77814
dhellmann/presentation-zenofpy
/procedural.py
191
3.921875
4
def my_function(arg1, arg2): """This function multiplies arg1 by arg2. """ return arg1 * arg2 results = [] for i in range(5): results.append(my_function(i, i)) print results
4cd02741abbc8bf9a9be60faa4c7fb9ccff77ce2
SaashaJoshi/algorithm-design-and-analysis
/Data Structures/StackUsingLinkedList.py
1,603
4.09375
4
# Implementing Stack using Linked Lists class Node: def __init__(self, data): self.data=data self.next=None class Stack: def __init__(self): self.start=None self.enterchoice() def push(self, data): if self.empty(): self.start=Node(data) else: newNode = Node(data) newNode.next = self.start self.start = newNode def pop(self): if self.empty(): print('Stack is empty!') else: popped=self.start.data self.start=self.start.next return popped def display(self): while not self.empty(): print(self.start.data) self.start=self.start.next else: print('Stack is empty') def empty(self): if self.start is None: return True else: return False def top(self): print(self.start.data) def enterchoice(self): while True: print('Choice:\n1: Push\n2: Pop\n3: Display\n4: Exit\n5: Top') self.choice = int(input('Enter your choice: ')) if self.choice == 1: data = int(input('Enter value: ')) self.push(data) if self.choice == 2: self.pop() if self.choice == 3: self.display() if self.choice == 4: exit(0) if self.choice==5: self.top() if self.choice not in [1, 2, 3, 4,5]: print('Wrong choice try again!') continue
bbeec3cc08096e6f5353f586097f7bbea5eb48a6
osydorchuk/ITEA2
/lesson6/iters_example.py
142
3.71875
4
list = [1, 2, 3] b = list.__iter__() print(b.__next__()) print(b.__next__()) print(b.__next__()) # StopIteration print(b.__next__())
0d35eb75fc642d230ce4eeacef326cdf9412ff6b
SyncfusionWebsite/Python-Succinctly
/Python_Succinctly/chapter_6/10.py
191
4.03125
4
#!/usr/bin/env python3 contacts = {'David': '555-0123', 'Tom': '555-5678'} for person, phone_number in contacts.items(): print('The number for {0} is {1}.'.format(person, phone_number))
d7c1729539430feee61d34820c7cdecc06b89fcc
andreykutsenko/python-selenium-automation
/hw_alg_9/Sorts.py
213
3.859375
4
array = [3, 5, 8, 9, 4, 25, 6, 8, 56] array.sort() sorted(array) print(array) print(sorted(array)) # sort(*, key=None, reverse=False) # sorted(iterable, *, key=None, reverse=False) b = 'HelloH' print(sorted(b))
5208dea0a2005e1ac22d39a7971c332cddd9602e
cpe202fall2019/lab1-jackfales
/lab1.py
1,946
4.46875
4
# Name: Jack Fales # Course: CPE 202 # Instructor: Paul Hatalsky # Assignment: Lab 1 # Term: Fall 2019 def max_list_iter(int_list): # must use iteration not recursion """finds the max of a list of numbers and returns the value (not the index) If int_list is empty, returns None. If list is None, raises ValueError""" if int_list == None: # checks if int_list == None raise ValueError('List == None') if len(int_list) > 0: # if int_list is empty, return None max_value = int_list [0] for i in range(len(int_list)): if int_list [i] > max_value: max_value = int_list [i] return max_value return None def reverse_rec(int_list): # must use recursion """recursively reverses a list of numbers and returns the reversed list If list is None, raises ValueError""" if int_list == None: # checks if int_list == None raise ValueError('List == None') if len(int_list) == 0: return [] # base case else: return [int_list[-1]] + reverse_rec(int_list[:-1]) # remove the last element and add it to the beginning def bin_search(target, low, high, int_list): # must use recursion """searches for target in int_list[low..high] and returns index if found If target is not found returns None. If list is None, raises ValueError """ if int_list == None: raise ValueError('List == None') # checks if int_list == None if len(int_list) == 0: return None if high >= low: # if low > high then binary search is complete mid = (low + high) // 2 # middle index of the search range if int_list [mid] == target: # if index matches, return index return(mid) elif target > int_list[mid]: # if target is greater than value checked, condense the range return(bin_search(target, mid + 1, high, int_list)) else: return(bin_search(target, low, mid - 1, int_list)) return None # if target is not found return None
ed03a5d550a90fdcf1aa0a4f5743e06caeb9428a
tanujp99/2019-Winter-Work
/Week2/form og.py
3,814
4
4
import tkinter as tk from tkinter import * from tkinter import ttk import tkinter.font as tkfont root = tk.Tk() root.title("College Form") time = tkfont.Font(family='sERIF', size=30) Label(root, text="TERNA ENGINEERING COLLEGE", font=time, justify = tk.CENTER, padx = (int((root.winfo_screenwidth() / 3)))).grid(row=0,columnspan=100) #Label.config(root, font=("Courier", 44)) #_______________NAME_______________________________ Label(root, text="1.Enter your First Name:",pady=20, justify = tk.LEFT).grid(row=1,column=0) e1 = ttk.Entry(root, justify = tk.LEFT).grid(row=1, column=1) Label(root, text="Last Name:").grid(row=1,column=2) e1 = ttk.Entry(root, justify = tk.LEFT).grid(row=1, column=3) #__________________GENDER__________________________ q = tk.IntVar() q.set(2) # initializing the choice, i.e. Python gender = [ ("Female"), ("Male"), ("Other"), ] #def ShowChoice(): # print(v.get()) tk.Label(root, text="2. Gender:",pady=20, justify = tk.LEFT).grid(row=2) for val, language in enumerate(gender): tk.Radiobutton(root, text=language,variable=q, justify = tk.LEFT, # command=ShowChoice, value=val).grid(row=2,column=(val+1)) #____________________DOB__________________________ Label(root, text="3. Enter Birth Day:", pady=20).grid(row=6,column=0) e11 = ttk.Entry(root).grid(row=6, column=1) Label(root, text="Month").grid(row=6,column=2) e12 = ttk.Entry(root).grid(row=6, column=3) Label(root, text="Year").grid(row=6,column=4) e13 = ttk.Entry(root).grid(row=6, column=5) #___________________EMAIL________________________ Label(root, text="4. Enter e-Mail:",pady=20).grid(row=7,column=0) e21 = ttk.Entry(root).grid(row=7, column=1) #_____________________PREVIOUS_COLLEGE___________ Label(root, text="5. Previous College Name:",pady=20).grid(row=8,column=0) e31 = ttk.Entry(root).grid(row=8, column=1) #________________DROPDOWN_MENU__________________ #root = Tk() # Add a grid mainframe = Frame(root) mainframe.grid( sticky=(N,W,E,S) ) mainframe.columnconfigure(0, weight = 1) mainframe.rowconfigure(0, weight = 1) mainframe.grid() # Create a Tkinter variable tkvar = StringVar(root) # Dictionary with options choices = { '--Choose from below--','Mumbai University','SNDT','SVKM','VJTI','IIT'} tkvar.set('--Choose from below--') # set the default option popupMenu = OptionMenu(mainframe, tkvar, *choices) Label(mainframe, text="6. Degree completed in University:",pady=20).grid(row = 9,columnspan=3) popupMenu.grid(row = 10,columnspan=3) # on change dropdown value def change_dropdown(*args): print( tkvar.get() ) # link function to change dropdown tkvar.trace('w', change_dropdown) #root.mainloop() #________________RADIO_BUTTONS__________________ v = tk.IntVar() v.set(0) # initializing the choice, i.e. Python payments = [ ("Cash"), ("Cheque"), ("DD"), ("NEFT"), ("UPI") ] #def ShowChoice(): # print(v.get()) tk.Label(root, text="7. Choose your mode of payment:", justify = tk.LEFT, padx = 20).grid() for val, language in enumerate(payments): tk.Radiobutton(root, text=language, padx = 20, variable=v, justify = tk.LEFT, # command=ShowChoice, value=val).grid() #_______________fullscreen___________________ #w = Label(root, text="Hello, world!") root.overrideredirect(True) root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight())) root.focus_set() # <-- move focus to this widget root.bind("<Escape>", lambda e: e.widget.quit()) #w.pack() root.mainloop()
4bb3322710df63c00c842fbae4b4bbfc0f6141d3
mak428/Learning_Python
/ex3.py
775
4.375
4
# prints a statement print "I will now count my chickens:" # Gives an equation to find how many hens there are print "Hens", 25 + 30 / 6 # Gives an equation to find how many Roosters there are print "Roosters", 100 - 25 * 3 % 4 # prints a statement print "Now I will count the eggs:" # calculations print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # asks a question print "Is it true that 3 + 2 < 5 - 7?" # calculations print 3 + 2 < 5 - 7 # asks a question print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 # explanation print "Oh, that's why it's False." # prints a statement print "How about some more." # prints a statement print "Is it greater?", 5 > -2 # aks a question and gives an anwer print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
25e2c130fc8e214d4196271d82536f1918816d21
hb4y/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,154
3.96875
4
#!/usr/bin/python3 """ matrix_divided - divide a matrix for a number matrix: matrix to divide div: integer to divide the matrix """ def matrix_divided(matrix, div): """ Divide matrix method """ error_list = "matrix must be a matrix (list of lists) of integers/floats" error_size = "Each row of the matrix must have the same size" if not (isinstance(matrix, list)): raise TypeError(error_list) list_len = len(matrix[0]) for inner_list in matrix: if len(inner_list) != list_len: raise TypeError(error_size) for number in inner_list: if not (isinstance(number, int) or isinstance(number, float)): raise TypeError(error_list) if not (isinstance(div, int) or isinstance(div, float)): raise TypeError("div must be a number") if div == 0: raise ZeroDivisionError("division by zero") new_matrix = [] new_list = [] for inner_list in matrix: for number in inner_list: res = number / div new_list.append(round(res, 2)) new_matrix.append(new_list) new_list = [] return new_matrix
ab90f4756d1011ec566d8f6a3cff65b5efae33c1
iamovrhere/lpthw
/py2/ex33.py
412
4.1875
4
def number_loop(length): #i = 0 numbers = [] #while i < 6: while len(numbers) < length: print "At top i is %d" % len(numbers) numbers.append(len(numbers)) #i += 1 print "Numbers now: ", numbers print "At the bottom is %d" % len(numbers) print "The numbers: " for num in numbers: print num, number_loop(6) number_loop(8) number_loop(2)
7628634ce3b8c3884eb1e679b42e374c1e642f3e
Mr-Umidjon/python-tasks-sariq-dev
/36-lesson/tubSonmi.py
293
4
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 12 08:11:19 2021 @author: WINDOWS 10 """ def tubSonmi(n): if n == 2 or n == 3: return True if n % 2 == 0 or n < 2: return False for i in range(3, n, 2): if n % i == 0: return False return True
67002994cdced64fdbdac90ace02e5dea5e6b639
xDarKyx/School-Work
/Python/Lab2-4/Lab2-4P03/addFunctions.py
1,747
3.921875
4
import time ''''List with the only valid types of expenses allowed for the dictionary''' expTypes=["Transport","Food","House keeping","Clothing","Telephone&Internet","Others"] '''add() function: adds to a specific day a specific type and a amount of expense''' def add(expenses): t=input("Type:") #Type of exp d=input("Day:")# Day if(t in expTypes) and (int(d) in range(1,31)): td=t+d # Merge(combine) Type & Day v=int(input("Enter value:")) # Value expenses[td]=expenses.get(td)+v #Adds print("") print("Added",v,"RON for",t,"on day:",d) else: if(t in expTypes): #if the type is correct, prints out that the day is not valid and returns to add function print("") print("Please insert a day from range 1-31") add(expenses) else: print("") print("Invalid type, please enter a valid one.") add(expenses) '''addToday() function: adds to the date of today new expense''' def addToday(expenses): t=input("Type:") #Type of exp d=time.strftime("%d")# day number of today if(t in expTypes) and (int(d) in range(1,31)): td=t+d # Merge(combine) Type & Day v=int(input("Enter value:")) # Value expenses[td]=expenses.get(td)+v #Adds print("") print("Added",v,"RON for",t,"on day:",d) else: if(t in expTypes): #if the type is correct, prints out that the day is not valid and returns to add function print("") print("Please insert a day from range 1-31") addToday(expenses) else: print("") print("Invalid type, please enter a valid one.") addToday(expenses)
8feaa089fd51fd5d83120ac0d25ebfedef1c9099
AprilBlossoms/py4e
/ch_06/ex_06_04.py
240
4.09375
4
# Exercise 4: There is a string method called count that is similar to the function in the previous exercise. # Write an invocation that counts the number of times the letter a occurs in “banana”. str = 'banana' print(str.count('a'))
44cb0866c481d67eee8961bff5ca12f7aaceb44b
prasannatuladhar/30DaysOfPython
/prime_or_not.py
558
4.28125
4
#get a number and find prime or not using For loop num = int(input("enter a number :")) for divider in range(2,num): if num%divider==0: print("This is not Prime Number") break else: print(f"The {num} is prime number") #get a number and find prime or not using While loop new_num=int(input("Enter a number ")) divisor_num=2 while new_num>divisor_num: if new_num%divisor_num==0: print(f"This number {new_num} is not prime") break divisor_num += 1 else: print(f"This number {new_num} is prime")
d327bc981bcf0d88eee477ab9981a5312010caad
hetal149/Python_Django
/Day5/class_interest.py
339
3.703125
4
#calculate Interest class cal3: P=0 R=0 T=0 def __init__(self,P,R,T): self.P=P self.R=R self.T=T def callinterest(self): I=self.P*self.R*self.T/100 self.I=I def display(self): print("Interest is",self.I) myc=cal3(1000,3.75,5) myc.callinterest() myc.display()
7230509922bcac73b8a1ec1d18a3c42237bb4f28
Liusihan-1/PTA-Python
/判断素数.py
276
3.9375
4
def isPrime(num): num=int(num) for i in range(2,num): if num%i==0 : return False if(num!=1): return True n = int(input()) for i in range(1,n+1): t=int(input()) if(isPrime(t)): print("Yes") else: print("No")
285ce1ece82520565b717e5f23afcf3ed35d8238
tkp75/studyNotes
/learn-python-from-scratch/library_heapq1.py
294
3.671875
4
#!/usr/bin/env python3 import heapq heap = [] # Empty heap # Inserting elements in the heap heapq.heappush(heap, 10) heapq.heappush(heap, 70) heapq.heappush(heap, 5) heapq.heappush(heap, 35) heapq.heappush(heap, 50) # Popping the smallest value minimum = heapq.heappop(heap) print(minimum)
c5d544f4a4a2d1cf6a75797274d9b3966ef4e4a1
EwenFin/exercism_solutions
/python/sieve/sieve.py
336
3.90625
4
import math def sieve(limit): result = [] if limit >= 2: result.append(2) for x in range(3, limit+1, 2): if is_prime(x): result.append(x) return result def is_prime(n): i = 3 while (i <= math.sqrt(n)): if (n % i == 0): return False i += 2 return True
4b37a56b2957afbac5783c34e0e291d382c15a4d
mcerbauskas/battlescript
/main.py
3,012
3.859375
4
from classes.game import Person, bcolors #instantiating Person class for a mage character #array for 'magic' each spell has a name, mp cost, damage done magic = [{"name": "Fire", "mpcost": 10, "dmg": 100}, {"name": "Blizzard", "mpcost": 10, "dmg": 124}, {"name": "Frost", "mpcost": 10, "dmg": 100}] player = Person(460,65,60,34, magic) enemy = Person(1200, 65, 45, 25, magic) running = True i = 0 #ENDC used to end the text styling print(bcolors.FAIL + bcolors.BOLD + "An enemy attacks!" + bcolors.ENDC) while running: print("===============================") player.choose_action() choice = input("Choose action: ") #reducing choice by 1 (to start counting from 0) index = int(choice) - 1 print("You chose: ", index) #generating some damage if index == 0: dmg = player.generate_damage() #telling enemy to take the damage enemy.take_damage(dmg) print("You attacked with", dmg, "points of damage. Enemy current HP: ", enemy.get_hp()) #choose magic, generate spell damage, attack the enemy elif index == 1: player.choose_magic() #wrapping input and reducing it by 1 magic_choice = int(input("Choose which spell to cast:")) - 1 magic_dmg = player.generate_spell_damage(magic_choice) #after we generate the spell damage we need to reduce magic points by some cost spell = player.get_spell_name(magic_choice) cost = player.get_spell_mpcost(magic_choice) #getting current magic points of the player current_mp = player.get_mp() #if mp is enough cast a spell, otherwise "not enough mp" if cost > current_mp: print(bcolors.FAIL + "\nNot enough MP\n" + bcolors.ENDC) #we don't miss the turn, the enemy doesn't attack us, simply skips back to the next iteration (line 19) continue else: player.reduce_mp(cost) #telling enemy to take the damage enemy.take_damage(magic_dmg) print(bcolors.OKBLUE + "\n" + spell + " did ", str(magic_dmg), " amount of damage" + bcolors.ENDC) #enemy is going to attack right now enemy_choice = 1 enemydmg = enemy.generate_damage() player.take_damage(enemydmg) print("Enemy attacks for: ", enemydmg, "points.") #print everyone's HP print("-------------------------") print("Enemy HP: " + bcolors.FAIL + str(enemy.get_hp()) + "/" + str(enemy.get_maxhp()) + bcolors.ENDC + "\n") print("Your HP: " + bcolors.OKGREEN + str(player.get_hp()) + "/" + str(player.get_maxhp()) + bcolors.ENDC + "\n") print("Your MP: " + bcolors.OKBLUE + str(player.get_mp()) + "/" + str(player.get_maxmp()) + bcolors.ENDC + "\n") if enemy.get_hp() == 0: print(bcolors.OKGREEN + "You win !" + bcolors.ENDC) running = False elif player.get_hp() == 0: print(bcolors.FAIL + "You lost !" + bcolors.ENDC) running = False #run only once #running = False
1e3d741fd99fba1163948f1b9b6c0fdb39ccd6d9
kakakoszaza/CP3-Yotin-Saowakhon
/assignments/Exercise_8_Yotin.py
1,451
3.5625
4
print('--------------------------','LogIn','--------------------------') user = input('Username : ') password = input('Password : ') if user == 'ronin' and password == '1996' : print('------------------','Connected Done !','------------------') print('Welcome To _Smile_Shops...') print('>>> User : %s >>>\n' %user) print('--- กรุณาเลือกสินค้า ---\n1. USB 3.0 Hub\n2. USB 3.1 Hub') selected = int(input('Select >> ')) if selected == 1 : price,vat = 325,7 to1 = price + (price * vat / 100) print('USB 3.0 Hub') print('Price = %d THB' %price ,' + ','Vat 7 %') a = int(input('จำนวน (1-2) : ')) if a == 1 : print('\nUSB 3.0 Hub จำนวน 1ชิ้น\nPrice = %.2f THB' %to1) elif a == 2 : to2 = to1 * 2 print('\nUSB 3.0 Hub จำนวน 2 ชิ้น\nPrice = %.2f THB' %to2) elif selected == 2 : price,vat = 465,7 to1 = price + (price * vat / 100) print('\nUSB 3.1 Hub') print('Price = %d THB' %price ,' + ','Vat 7 %') a = int(input('จำนวน (1-2) : ')) if a == 1 : print('\nUSB 3.1 Hub จำนวน 1 ชิ้น\nPrice = %.2f THB' %to1) elif a == 2 : to2 = to1 * 2 print('\nUSB 3.1 Hub จำนวน 2 ชิ้น\nPrice = %.2f THB' %to2)
93d8953397cc52b3474fc5b3da578570bf01711a
HomingYuan/python_training
/Day1_homework.py
949
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: Homing @software: PyCharm Community Edition @file: Day1_homework.py @time: 2017/5/8 19:14 """ import random def guess_the_num(num): while True: a = int(input("Please enter a number:")) if a > num: print("The number is bigger:") elif a < num: print("The number is smaller") else: print("You are right!") break def game_continue_exit(): while True: str1 = input('enter yes continue and no to exit:') if str1 == 'no': print('Exit the game...') break if str1 == 'yes': print('Continue the game') num = random.randint(0, 99) guess_the_num(num) def main(): print("-------Begin game--------") num = random.randint(0, 99) guess_the_num(num) game_continue_exit() if __name__ == "__main__": main()
81a903a00474b6b855636b08ae4c138ff8c6ace0
Nic30/pyMathBitPrecise
/pyMathBitPrecise/utils.py
240
3.703125
4
from itertools import zip_longest def grouper(n, iterable, padvalue=None): """grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x') """ return zip_longest(*[iter(iterable)] * n, fillvalue=padvalue)
da3b9c90c1f8abef6d770361c78d351dc2bdda21
reshmapalani/pythonprogram
/1.py
120
3.578125
4
a=5 b=3 print(a,b,a+b) print(a,b,a-b) print(a,b,a*b) print(a,b,a/b)
e2ff007ed9f04c6ecae99e5ea4a9dd8088128b71
SaiKrishnaMohan7/Playground
/Python/100ProbsBishAintOne/P7.py
194
3.953125
4
X = int(input('Enter X: ')) Y = int(input('Enter Y: ')) matrix = [[0 for a in range(Y)] for b in range(X)] for i in range(X): for j in range(Y): matrix[i][j] = i * j print(matrix)
02f3ad2c664c33e3fa14a9769d5e304de7c5359e
yuryanliang/Python-Leetcoode
/100 medium/8/395 longest-substring-with-at-least-k-repeating-characters.py
990
4.09375
4
""" Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times. Example 1: Input: s = "aaabb", k = 3 Output: 3 The longest substring is "aaa", as 'a' is repeated 3 times. Example 2: Input: s = "ababbc", k = 2 Output: 5 The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times. """ class Solution(object): def longestSubstring(self, s, k): """ :type s: str :type k: int :rtype: int """ from collections import defaultdict lookup =defaultdict(list) for i, c in enumerate(s): lookup[c].append(i) less = [i for i in lookup.values() if len(i) < k] breakpt = [] for j in less: for n in j: breakpt.append(n) 1==1 if __name__ == '__main__': s = "aebabbc" k = 2 print(Solution().longestSubstring(s, k))
d269ac479f3a7c03c520ea4d11174e0cdefc1620
nicktakahashi/budget-tracker
/budget_calculator.py
738
3.765625
4
def main_method(): # each data has 3 fields a description and a value +/- , and a date TEST_DATA = [('paycheck', 1150, '07-20-2018'), ('rent', -850, "08-1-2018")] def calculate_net_cashflow(financial_data): net_cash = 0 for data in financial_data: net_cash += data[1] return net_cash monthly_net_cashflow = calculate_net_cashflow(TEST_DATA) def calculate_percent_saved(financial_data): total_income = 0 for data in financial_data: if data[0] == 'paycheck': total_income += data[1] percent_remaining = (monthly_net_cashflow * 100.0)/ total_income print monthly_net_cashflow, total_income return percent_remaining print calculate_percent_saved(TEST_DATA) if __name__ == "__main__": main_method()
30f53fc217638b6bb6abbbbc5e02ddcbe21f5d3d
tanya525625/Introdution-to-Python
/Fibonacci_Number_Generator.py
466
3.984375
4
def fibonacci_generator(n): a = 0 b = 1 i = 1 isOtr = False if n < 0: n = -n isOtr = True elif n == 0: yield 0 while i < n: b = b + a a = b - a i += 1 if (i % 2 != 0): if (isOtr == True): yield -a; else: yield a; else: yield a; print(list(fibonacci_generator(10))) print(list(fibonacci_generator(-10)))
c6ccf796445e9bebf7c41c1a57c771b9ea17b9a7
kumar-atul-au13/WoodpeckerTA_Codes
/Week6/Day5/Asignment/BFS_using_list.py
833
3.796875
4
#video[6:00] https://drive.google.com/file/d/1btERkgmo2f8Rv2OT2DlKmgYk_26vMptE/view?usp=sharing from queue import Queue graph= { 'A': {'B': 1, 'D': 4}, 'B': {'C': 1, 'A': 1}, 'D': {'A': 4, 'C': 1, 'E': 2, 'F': 11}, 'E': {'D': 2, 'F': 7}, 'F': {'D': 11, 'E': 7}, 'C': {'B': 1, 'D': 1, 'H': 2, 'G': 6}, 'G': {'C': 6, 'H': 2, 'I': 4}, 'H': {'C': 2, 'G': 2, 'I': 1}, 'I': {'G': 4, 'H': 1} } def bfs(graph,vertex): visited=set() queue=Queue() queue.enqueue(vertex) visited.add(vertex) while queue.peek(): # queue.display_head() curr_vert=queue.dequeue() print(curr_vert) for adj_vert in graph[curr_vert]: if adj_vert not in visited: queue.enqueue(adj_vert) visited.add(adj_vert) bfs(graph,'A')
3b6a5d614c2f51b09c128e5382df86b3d4135e9b
Lewizkuz/lewrep
/ttiw0300_data-analytiikka/tehtavat/kerta1/t1b_tuplat.py
265
3.703125
4
def Poistup(sana): sana = sana.lower() tmp = [] for kirj in sana: if kirj not in tmp: tmp.append(kirj) return ''.join(tmp) print Poistup("AnaNasakäämä") print Poistup("Saippuakauppias") print Poistup("Floridalainen broileri")
15513ef4a7a940482c16a63114e633f7dd66e94f
newgarden/CtCI
/ch_01_arrays_and_strings/pr_09_string_rotation.py
1,344
4.21875
4
# -*- coding: utf-8 -*- """ String Rotation Problem statement: Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring (e.g., "waterbottle" is a rotation of "erbottlewat"). """ import unittest def string_rotation(s1, s2): """ Check if s2 is a rotation of s1. Takes O(N+M) time and O(N) additional space, where N and M are lengths of s1 and s2. Operator "in" is used as a substitute for isSubstring. This problem may be solved in O(1) space without isSubstring, but use of this function is dictated by the problem statement. """ if len(s1) != len(s2): return False return s2 in (s1 + s1) class Test(unittest.TestCase): data = [ ('', '', True), ('abc', '', False), ('', 'spam', False), ('abcde', 'abcde', True), ('waterbottle', 'erbottlewat', True), ('waterbottle', 'elttobretaw', False), ('foo', 'bar', False), ('foo', 'foofoo', False), ('aaaa', 'aaaa', True), ('aaaa', 'aaa', False), ('racecar', 'carrace', True) ] def test_string_rotation(self): for data in self.data: self.assertEqual(string_rotation(data[0], data[1]), data[2])
e2cb62c9a2a2f04334aa44f082d3412be3391c8c
tjt7a/AutomataZoo
/YARA/code/yara2pcre.py
8,939
3.578125
4
# # Converts yara rules to PCRE # import os import sys import plyara import re import string # def addDelimiters(string): delim = "/" return delim + string + delim # Converts list of 0-255 int values to a string charset def values2Charset(values): retval = "[" for val in values: # retval = retval + "\\x" + hex(val)[2:] return retval + "]" # Converts two string hex chars to a charset. ? indicates a nibble wildcard def nibbles2Charset(high, low): result = "" values = list() if high == '?': if low == '?': result = '.' else: # find charset where high nib can be anything low_val = int(low, 16) for i in range(0,255): # mask low bits and compare if (i & 15) == low_val: values.append(i) result = values2Charset(values) else: if low == '?': # find charset where high nib can be anything high_val = int(high, 16) for i in range(0,255): # mask low bits and compare if (i >> 4 & 15) == high_val: values.append(i) result = values2Charset(values) else: result = "\\x" + high + low return result # Converts a YARA hex string to a regular expression def hexStringToRegex(hex_string): print "HEX TO REGEX START" done = False counter = 0 result = "" states = ['normal','jump','alternative'] state = 'normal' index = 0 while not done : # loop over characters #get next byte char = hex_string[index] index = index + 1 # ignore these chars if char == ' ': continue elif char == '\n': continue elif char == '{': continue # include these chars elif char == '(': result = result + char continue elif char == ')': result = result + char continue elif char == '|': result = result + char continue # end condition elif char == '}': done = True # jump handling elif char == '[': state = 'jump' continue elif char == ']': state = 'normal' continue # others else: # ignore jumps for now if state == 'jump': continue # we need to handle a byte pattern else: counter = counter + 1 if counter == 2: charset = nibbles2Charset(hex_string[index - 2], char) result = result + charset counter = 0 print result print "HEX TO REGEX END" return result # Parses a YAR file and emits regular expressions to a file def parseYARFile(file_path, file_name): sys.stdout.write(" - parsing input file: " + file_path + "\n") # read input file p = plyara.PlyaraParser() try: result = p.parseFromFile(file_path) except: sys.stdout.write("PARSER BARFED: " + file_path + "\n") return rules = "" wide_rules = "" rule_counter = 0 string_counter = 0 for rule in result: rule_name = rule['rule_name'] #sys.stdout.write("FOUND RULE: " + rule_name + "\n") rule_counter = rule_counter + 1 if 'strings' in rule: for strings in rule['strings']: print strings string_counter = string_counter + 1 id_string = file_name + "." + rule_name + "." + strings['name'] #sys.stdout.write(id_string + " : " + strings['value'] + "\n") final_rule = strings['value'] if final_rule.startswith("{"): final_rule = hexStringToRegex(final_rule) final_rule = addDelimiters(final_rule) elif final_rule.startswith("\""): # NEED TO ESCAPE SPECIAL CHARS HERE TO CONVERT TO EXACT MATCH STRING # TODO final_rule = final_rule[1:-1] escaped = final_rule.replace("\\", "\\\\") escaped = escaped.replace(".", "\.") escaped = escaped.replace("^", "\^") escaped = escaped.replace("|", "\|") escaped = escaped.replace("$", "\$") escaped = escaped.replace("*", "\*") escaped = escaped.replace("+", "\+") escaped = escaped.replace("?", "\?") escaped = escaped.replace("(", "\(") escaped = escaped.replace(")", "\)") escaped = escaped.replace("[", "\[") escaped = escaped.replace("]", "\]") escaped = escaped.replace("{", "\{") escaped = escaped.replace("}", "\}") final_rule = addDelimiters(escaped) else: # this is actually a regex already =P print "FOUND_REGEX" final_rule = final_rule # Now that we have a regex, check for modifiers ascii = False fullword = False wide = False nocase = False orig_rule = final_rule if 'modifiers' in strings : for mod in strings['modifiers']: if mod == 'ascii': # basically ignored unless also will wide mod ascii = True continue elif mod == 'fullword': # can only match if delimited by non-alphanumeric chars # [^0-9a-zA-Z]<pattern>[^0-9a-zA-Z] fullword = True final_rule = "/[^0-9a-zA-Z]" + final_rule[1:] if nocase: final_rule = final_rule[:-2] + "[^0-9a-zA-Z]/i" else: final_rule = final_rule[:-1] + "[^0-9a-zA-Z]/" continue elif mod == 'wide': # interleave ascii pattern with zeroes # BEFORE: pattern # AFTER: p\x00a\x00t\x00t\x00e\x00r\x00n\x00 wide = True continue # each byte actually needs to be two bytes elif mod == 'nocase': # add pcre modifier 'i' case insensitive to pcre final_rule = final_rule + "i" nocase = True continue else: #do nothing continue # # add original ascii rule as well as wide rule if wide: #wide_rules = wide_rules + id_string + " : " + final_rule + "\n" wide_rules = wide_rules + final_rule + "\n" if ascii: #rules = rules + id_string + " : " + final_rule + "\n" rules = rules + final_rule + "\n" else: #rules = rules + id_string + " : " + final_rule + "\n" rules = rules + final_rule + "\n" return rules,wide_rules def main(): sys.stdout.write("*******************************\n"); sys.stdout.write("YARA2PCRE by Jack Wadden\n") sys.stdout.write("*******************************\n"); # change directory to base yara rule dir #input_rule_dir = sys.argv[1] rules_dir = "/af5/jpw8bd/r/automata/YARA/rules" rules = "" wide_rules = "" for root, subdirs, files in os.walk(rules_dir): for name in files: if name.endswith(".yar"): if "index" not in name: if "utils" not in root: fn = os.path.join(root, name) #print(fn) new_rules = parseYARFile(fn, name) if new_rules is not None: if new_rules[0] is not None: rules = rules + new_rules[0] if new_rules[1] is not None: wide_rules = wide_rules + new_rules[1] # write rules to file with open("YARA_rules.txt", "w") as text_file: text_file.write(rules) with open("YARA_wide_rules.txt", "w") as text_file: text_file.write(wide_rules) if __name__== "__main__": main()
a44adc36994b1926a42d7d25f01c29f21fe82694
outrageousaman/Python_study_marerial
/pd/options.py
1,529
3.78125
4
# pandas options # pandas provides the api to change some aspects of its behaviour # the api is composed of 5 relavent options # get_option # set_option # reset_option # describe_option # option_context # get_option takes a single parameter and returns the value as given in the output below import pandas as pd print(pd.get_option('display.max_rows')) print(pd.get_option("display.max_columns")) # set_option we can change the default number of rows and column pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns',10) print(pd.get_option('display.max_rows')) print(pd.get_option("display.max_columns")) # reset_option reset a particular option pd.reset_option("display.max_rows") print(pd.get_option("display.max_rows")) # describe option prints the discription of arguments pd.describe_option("display.max_rows") print(pd.options['display.max_rows"']) # option_context context manager is used to set the option in with statement temporarily. Option values are restored automatically when you exit the with block − with pd.option_context("display.max_rows",10): print(pd.get_option("display.max_rows")) print(pd.get_option("display.max_rows")) # display.max_rows # # Displays maximum number of rows to display # # # display.max_columns # # Displays maximum number of columns to display # # display.expand_frame_repr # # Displays DataFrames to Stretch Pages # # display.max_colwidth # # Displays maximum column width # # display.precision # # Displays precision for decimal numbers
fc9b86286e93628d0b5335a441bb4e2a5b58acdf
AnaArce/introprogramacion
/Flujo_ciclico/E_3.py
68
3.625
4
for n in range(15,81): if n%5 == 0 or n%3 == 0: print(n)
eff0710a35069e165e2184f0ae6cc8e89e3ce31f
viv-Shubham/Computer-Society
/Basic/Calculate Factorial of A Number/SolutionByVanika.py
185
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 7 22:29:00 2020 @author: Vanika """ #factorial N = int(input("Enter number")) ans = 1 for i in range(1,N+1): ans = ans * i; print(ans)
981210cf8f49e5be0b5bdfce607627d03880652b
Y-Joo/Baekjoon-Algorithm
/pythonProject/divide and conquer/Quad-Tree.py
535
3.6875
4
def quad(x, y, n): check = nums[x][y] for i in range(x, x + n): for j in range(y, y + n): if check != nums[i][j]: print("(",end="") quad(x, y, n // 2) quad(x, y + n // 2, n // 2) quad(x + n // 2, y, n // 2) quad(x + n // 2, y + n // 2, n // 2) print(")", end="") return print(check,end="") return num = int(input()) nums = [] for i in range(num): nums.append(input()) quad(0,0,num)
bfca54cf7863556582464fe1a9c41c6e71a5161e
acc-cosc-1336/cosc-1336-spring-2018-Skynet2020
/src/homework/homework 12 last/win.py
608
3.65625
4
from tkinter import Tk, Button, Frame from display_labels import DisplayLabels class Win(Tk): def __init__(self): Tk.__init__(self, None, None) self.wm_title('Miles to km converter') self.geometry('320x90') self.frame = Frame() self.my_button = Button(self.frame, text='Display conversion', command=DisplayLabels) self.quit_button = Button(self.frame, text='Quit', command=self.destroy) self.my_button.pack(side='left') self.quit_button.pack(side='left') self.frame.pack(side='bottom') self.mainloop()
a550f8bff3fa125ed2bbc37800176bbdb03d8bbd
appy2k13/python_codes
/ass8.4.py
243
3.765625
4
fh = open('romeo.txt') lst = list() for line in fh: tlist = line.rstrip().split() #print (tlist) for word in tlist : #print(word) if word not in lst : lst.append(word) lst.sort() print(lst)
a42acbb485c2d777da2be045c6825083c09f71b5
python-ops-org/python-ops
/dates/26-08-2020/l2.py
771
3.546875
4
import subprocess from subprocess import Popen from subprocess import Popen, PIPE #subprocess.run executes a command and waits for it to finish # """ Popen you can continue doing your stuff while the process finishes and then just repeatedly call subprocess. communicate yourself to pass and receive data to your process """ """ Note that, what subprocess.run is actually doing is invoking for you the Popen and communicate, so you don't need to make a loop to pass/receive data nor wait for the process to finish. """ def cmd(): c = "free -m" """ p = subprocess.run(c, stdout=subprocess.PIPE, shell=True) print(p) """ p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=None, shell=True) o = p.communicate() print(o[0]) cmd()
f79380940e811b405414617af132d17d3687f781
buyi823/learn_python
/some_practices1/function_variable.py
254
3.9375
4
#!/usr/bin/python3 total = 0 #这是一个全局变量 def sum(arg1,arg2): total = arg1 + arg2 # total在这里是局部变量 print("函数内是局部变量 : ", total) return total sum(10,20) print('函数外是全局变量:' ,total)
b0a3b4a5dfba3f254a48a8a2dcf05016901f1370
kimth007kim/python_choi
/Chap7/Ex7_2.py
320
3.796875
4
import turtle t=turtle.Turtle() t.shape("turtle") def hexagon(): # turtle.penup() # turtle.goto(x,y) # turtle.pendown() for i in range(6): turtle.forward(50) turtle.left(60) # hexagon(125,125) # hexagon(0,0) for i in range(6): turtle.forward(50) turtle.right(60) hexagon()
940d939a9c92bf7da5f31bed65a88defc54e7e37
hezudao25/learnpython
/名片管理/cards_tools.py
2,747
3.875
4
#所有名片记录的列表 card_list=[] def show_menu(): """显示菜单""" print("*" * 50) print("欢迎使用【名片管理系统】 v1.0") print("") print("1.新增名片") print("2.显示全部") print("3.查找名片") print("") print("0.退出系统") print("*" * 50) def new_card(): """新增名片""" print("*" * 50) print("新增名片") #1. 提示用户输入名片的详细信息 name_str = input("请输入姓名:") phone_str = input("请输入电话:") qq_str = input("请输入QQ:") email_str = input("请输入Email:") #2.使用用户输入的信息建立一个名片 card_dict = {"name":name_str,"phone":phone_str,"qq":qq_str,"email":email_str} #3.将名片字典添加到list card_list.append(card_dict) print(card_list) #4 提示成功 print("添加 %s 的名片成功!" % name_str) def show_all(): """显示所有名片""" print("*" * 50) print("显示所有名片") if len(card_list)==0: print("目前没有名片,请使用新增功能添加名片") return for name in ["姓名","电话","QQ","Email"]: print(name,end="\t\t") print("") print("=" * 50) for ky in card_list: print("%s\t\t%s\t\t%s\t\t%s" % (ky["name"],ky["phone"],ky["qq"],ky["email"])) def search_card(): """查找名片""" print("*" * 50) print("查找名片") #1 提示输入姓名 search_str = input("关键词:") #2 遍历名片列表 for ky in card_list: if ky["name"] == search_str: print("姓名\t\t电话\t\tQQ\t\tEmail") print("=" * 50) print("%s\t\t%s\t\t%s\t\t%s" % (ky["name"], ky["phone"], ky["qq"], ky["email"])) # deal_card(ky) break else: print("没有找到 %s" % search_str) def deal_card(find_dict): print(find_dict) action_str = input("请选择要执行的操作" " 1 修改 2 删除 0 返回:") if action_str=="1": find_dict["name"]=input_card_info(find_dict["name"],"姓名") find_dict["phone"] = input_card_info(find_dict["phome"],"电话") find_dict["qq"]=input_card_info(find_dict["qq"],"qq") find_dict["email"]=input_card_info(find_dict["email"],"email") print("修改名片") elif action_str=="2": card_list.remove(find_dict) print("删除名片") def input_card_info(dict_value,tip_message): """ :param dict_value: :param tip_message: :return: """ action_str = input(tip_message+"[回车不修改]:") if action_str !="": return action_str else: return dict_value
2da81254ad00fabbb5ce192e12ffc2d0714e455b
HenriqueHideaki/100DaysOfAlgo
/Day 81/Determinant.py
1,558
4.21875
4
''' The value of determinant of a matrix can be calculated by following procedure – For each element of first row or first column get cofactor of those elements and then multiply the element with the determinant of the corresponding cofactor, and finally add them with alternate signs. As a base case the value of determinant of a 1*1 matrix is the single value itself'''. Cofactor of an element, is a matrix which we can get by removing row and column of that element from that matrix. # defining a function to get the minor matrix after excluding i-th row and j-th column. def getcofactor(m, i, j): return [row[: j] + row[j+1:] for row in (m[: i] + m[i+1:])] # defining the function to calculate determinant valueof given matrix a. def determinantOfMatrix(mat): # if given matrix is of order 2*2 then simply return de value by cross multiplyin elements of matrix. if(len(mat) == 2): value = mat[0][0] * mat[1][1] - mat[1][0] * mat[0][1] return value # initialize Sum to zero Sum = 0 # loop to traverse each column # of matrix a. for current_column in range(len(mat)): # calculating the sign corresponding # to co-factor of that sub matrix. sign = (-1) ** (current_column) # calling the function recursily to # get determinant value of # sub matrix obtained. sub_det = determinantOfMatrix(getcofactor(mat, 0, current_column)) # adding the calculated determinant # value of particular column # matrix to total Sum. Sum += (sign * mat[0][current_column] * sub_det) # returning the final Sum return Sum
6cf82ece8a78afda1a3ee0231829d5084b90e8ff
Anvi23/Practice_Programs
/factors of n.py
176
4.375
4
#Write a program to print all the factors of a given number. n=int(input('Enter a number: ')) print('Factors of n are: ') for i in range(1,n+1): if n%i==0: print(i)
380ca8177c0bf6f561b7856c697dd9758f403a68
Santhosh-23mj/Simply-Python
/VulnerabilityScanner/04_VulnerabilityScanner.py
1,016
3.609375
4
#!/usr/bin/python3 """ Program_4 The Most basic Vulnerability Scanner! """ import socket def retBanner(ip,port): s = socket.socket() try: s.connect((ip,port)) res = s.recv(1024) return res except Exception as e: print("[-] Error - "+str(e)) return def checkVulns(res): if("FreeFloat ftp server version 1.00 " in res): print("[+] The FreeFloat Server is vulnerable") elif("3Com 3CDaemon Ftp Server Version 2.0" in res): print("[+] The 3Com Server is Vulnerable") elif("Ability Server 2.34" in res): print("[+] The Ability server is vulnerable") elif("Sami Ftp Server 2.0.2" in res): print("[+] Sami Server is vulnerable") else: print("[-] The FTP Server isn\'t Vulnerable") return def main(): ip = "192.168.0.1" port = 21 banner = retBanner(ip, port) if(banner): print("[+]"+ip+banner.strip('\n')) checkVulns(banner) if __name__ == '__main__': main()
1e85fc96836d9eb53f63fa50ef3638fcaac2d723
webclinic017/New-Osama-Python
/Sending Email/osamasendemail.py
1,894
3.8125
4
""" import csv import yagmail emails = [] names = [] with open("contacts_file.csv") as file: reader = csv.reader(file) next(reader) # Skip header row for name, email, grade in reader: emails.append(email) names.append(name) yag_smtp_connection = yagmail.SMTP(user="osamapython@gmail.com", password="Os01265065()", host='smtp.gmail.com') subject = 'Hello from Osama' for x in range(len(names)): message = f"Hi Mr. {names[x].capitalize()}, it's just a test Message." contents = [message, 'D:\Python\Project\OsamaPython\image.jpg', 'D:\Python\Project\OsamaPython\message.txt'] yag_smtp_connection.send(emails[x], subject, contents) print('Sent ........') """ import csv import yagmail attachments = [] emails = [] names = [] receiver_file = input("Please enter a Path of file containing the e-mails to be sent like this 'D:\Docu\mycontact.cvs ' :") with open(receiver_file) as file: reader = csv.reader(file) next(reader) # Skip header row for name, email, grade in reader: emails.append(email) names.append(name) print(names) your_email = input('Please Enter Your Email') your_password = input('Please Enter Your Password') yag_smtp_connection = yagmail.SMTP(user=your_email, password=your_password, host='smtp.gmail.com') subject = input("Please Enter Subject Here") number_of_attachments = int(input("Please Enter Number of files attached:")) for x in range(number_of_attachments): attached = input("Please enter a Path of file you want a attached like this 'D:\Docu\myattached' :") attachments.append(attached) print(attachments) for x in range(len(names)): message = f"Hi Mr. {names[x].capitalize()}, it's just a test Message." contents = [message, 'D:\Python\Project\OsamaPython\image.jpg', 'D:\Python\Project\OsamaPython\message.txt'] yag_smtp_connection.send(emails[x], subject, contents) print('Sent ........')
534bd3260f0056ce94e33a4b5efc9af0df2e7b09
daniel-reich/ubiquitous-fiesta
/SYmHGXX2P26xu7JFR_17.py
1,159
3.640625
4
def number_groups(group1, group2, group3): z=[] h=[] a=set(group1) b=set(group2) c=set(group3) p=a.intersection(b) k=a.intersection(c) l=b.intersection(c) print(p,k,l) if p==set() and k==set(): return sorted(list(l)) elif p==set() and l==set(): return sorted(list(k)) elif k==set() and l==set(): return sorted(list(p)) ​ elif k==set(): d=list(l) g=list(p) for u in d: g.append(u) g=list(set(g)) return sorted(g) elif p==set(): d=list(l) g=list(k) for r in d: g.append(r) g=list(set(g)) return sorted(g) elif l==set(): d=list(p) g=list(k) for e in d: g.append(e) g=list(set(g)) return sorted(g) elif ((p!=set() and k!=set()) and (l!=set())): x=list(p) y=list(k) z=list(l) for i in y: x.append(i) for j in z: x.append(j) x=list(set(x)) return sorted(x) else: return []