blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
a194f811e9de0b020e0b22f9b6fd9531d55cf78b
YuTan9/leetcode
/2020JulyCodingChallenge/Maximum_Width_of_Binary_Tree.py
2,397
3.59375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # My code: (Passes) class Solution(object): def widthOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 width = 1 parents = [root] stop = False while not stop: level = [] for parent in parents: if parent != None: level.append(parent.left) level.append(parent.right) if parent == None and level != []: level.append(None) level.append(None) left = -1 right= len(level) for i in range(len(level)): if level[i] != None: left = i break for i in range(len(level) - 1, -1, -1): if level[i] != None: right = i break if left != -1 and right != len(level): if right - left + 1 > width: width = right - left + 1 else: stop = True parents = list(level) return width """ # Better solution: class Solution(object): def widthOfBinaryTree(self, root): if not root: return 0 max_width = 0 # queue of elements [(node, col_index)] queue = deque() queue.append((root, 0)) print(queue) while queue: level_length = len(queue) # level_head_index would be the first index of each level _, level_head_index = queue[0] # iterate through the current level for _ in range(level_length): node, col_index = queue.popleft() if node.left: queue.append((node.left, 2 * col_index)) # cuz the left child is the 2 * n in its level, where n is its parent's number if node.right: queue.append((node.right, 2 * col_index + 1)) max_width = max(max_width, col_index - level_head_index + 1) return max_width """
b478025bb4c45dd4c32c1a8083b828da9d9f958b
Davinder-Dole/python-challenge-Py-Me-Up-Charlie
/PyBank/hw/main.py
1,902
3.75
4
import os import csv csvpath = os.path.join("..", "Resources", "budget_data.csv") total_months = 0 total_profit = [] monthly_profit_change = [] min=0 max=0 # Open csv with open(csvpath, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # Skip the header labels csvheader = next(csvreader) # Iterate through the rows in the stored file contents for row in csvreader: # Calculate total months total_months+=1 # create a list total profit total_profit.append(int(row[1])) # Iterate through the profits for i in range(len(total_profit) - 1): # difference between two months and append to monthly profit change monthly_profit_change.append(total_profit[i + 1] - total_profit[i]) change = total_profit[i + 1] - total_profit[i] # Calculate max profit if change > 0: if max<change: max = change m=row[0] # Calculate the Max loss if(change<0): if(min>change): min=change n=row[0] total_average=round(sum(monthly_profit_change)/len(monthly_profit_change),2) print(f" Total Months = {total_months}") print(f" Total Amount = ${sum(total_profit)}") print(f" Average Change: ${total_average}") print(f"Greatest Increase in Profits: {m} (${max})") print(f"Greatest decrease in Profits: {n} (${min})") file = open("output.txt","w") file.write("Financial Analysis" + "\n") file.write("...................................................................................." + "\n") file.write(f" Total Months = {total_months}\n") file.write(f" Total Amount = ${sum(total_profit)}\n") file.write(f" Average Change: ${total_average}\n") file.write(f"Greatest Increase in Profits: {m} (${max})\n") file.write(f"Greatest decrease in Profits: {n} (${min})\n") file.close()
b227542479f4396cb317fbb2a42e79ad0d90da31
JhonattanDev/Exercicios-Phyton-29-07
/ex7.py
586
4.28125
4
import math # Pra explicar o programa print("Digite um valor abaixo para ver seu dobro, triplo, e raíz quadrada dele! \n") # Input para o usuário inserir o valor valor = int(input("Digite o valor: ")) # Aqui será realizados os cálculos que definirão as variáveis dobro = valor * 2 triplo = valor * 3 raizQuadrada = math.sqrt(valor) # Para pular uma linha print("") # Imprimir/mostrar o resultado do programa print("O valor digitado foi {}, sendo o seu dobro {}, seu triplo {}," " e sua raíz quadrada {}.".format(valor, dobro, triplo, raizQuadrada))
7683a451955599046bc8443143fe84f1bdd07d7f
JEONJinah/Shin
/for statment.py
921
3.859375
4
# 이중 for 문 곱셈 for i in range(2,10): for j in range(1, 10): print(i*j, end=" ") print(" ") a = [1,2,3,4] result = [num * 3 for num in a if num % 2 == 0] print(result) a = [(1, 3), (2, 4), (3, 5)] for (f, r) in a: print(f + r) marks = [90, 5, 67, 45, 80] number = 0 #print(student num) for points in marks: number += 1 if points < 60: print(f'{number}인 학생은 불합격입니다.') else: print(f'{number}인 학생은 합격입니다.') #Range # (Start, end, step) for i in range(0, 10): print(i, end=" ") print(" ") for i in range(0, 10, 2): print(i, end=" ") print() #list comprehension list_a = [1, 2, 3, 4] result = [num*3 for num in list_a] print(result) result = [num*3 for num in list_a if num% 2 == 0] print(result) result = [x * y for x in range(2,10) for y in range(1, 10)] print(result)
aebb76773c73791a6d997e678fd50c0f812f7144
sorcerer0001/courses-interactivepython-01
/c2.py
1,304
3.71875
4
import simplegui import random import math num_range = 100 remaining_guesses = 0 secret_number = 0 def new_game(): global num_range, remaining_guesses, secret_number secret_number = random.randrange(0, num_range) remaining_guesses = int(math.ceil(math.log(num_range, 2))) print print "New game. Range is from 0 to", num_range print "Number of remaining guesses is", remaining_guesses def range100(): global num_range num_range = 100 new_game() def range1000(): global num_range num_range = 1000 new_game() def input_guess(guess): global remaining_guesses, secret_number guess = int(guess) remaining_guesses -= 1 print print "Guess was", guess if guess == secret_number: print "Correct" new_game() elif remaining_guesses == 0: print "You lose" new_game() else: print "Number of remaining guesses is", remaining_guesses if guess < secret_number: print "Higher" else: print "Lower" frame = simplegui.create_frame("Guess the number", 200, 200) frame.add_button("Range is [0, 100)", range100, 200) frame.add_button("Range is [0, 1000)", range1000, 200) frame.add_input("Enter a guess", input_guess, 200) new_game()
83f5c1a07d2fa6535c3615e7c3c03af24d879a23
urielgoncalves/training-python
/fizzbuzz.py
572
3.921875
4
import numpy def fizzbuzz(numero): #se o numero for multiplo de 3 e 5 escreve fizzbuzz #se o numero dor multiplo de 3 escreve fizz #se o numero for multiplo de 5 escreve buzz #else escreve o numero #pass multiploDeTres = numero % 3 == 0 multiploDeCinco = numero % 5 == 0 if multiploDeTres and multiploDeCinco: print("fizzbuz") elif multiploDeTres: print("fizz") elif multiploDeCinco: print("buzz") else: print(numero) numero = int(input("informe um número de 10 a 100: ")) fizzbuzz(numero)
f51e447b76c578428adac4a07943ee05a6bb28a9
areebasif/myDS
/llist and stacks.py
6,830
3.921875
4
class node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self,data): new_node = node(data) if self.head is None: self.head = new_node return prev_node = self.head while prev_node.next: prev_node = prev_node.next prev_node.next = new_node def printlist(self): curr_node = self.head while curr_node: print(curr_node.data) curr_node = curr_node.next def remove_node(self,key): curr_node = self.head if curr_node and curr_node.data == key: self.head = curr_node.next curr_node.next = None prev = None while curr_node and curr_node.data != key: prev = curr_node curr_node = curr_node.next if curr_node is None: print("not found") return prev.next = curr_node.next curr_node = None def remove_node_by_index(self,idx): curr_node = self.head if idx == 0: self.head = curr_node.next curr_node = None return count = 0 prev = None while count != idx and curr_node: prev_node = curr_node curr_node = curr_node.next count = count+1 if curr_node is None: return prev_node.next = curr_node.next curr_node = None def iterative_length(self): count = 0 curr_node = self.head while curr_node: curr_node = curr_node.next count = count+1 return count def recursive_length(self, node): if node is None: return 0 return 1 + self.recursive_length(node.next) # def swap_nodes(self,key1,key2): # if key1 ==key2: # return # prev1 = None # curr_node1 = self.head # while curr_node1 and curr_node1.data != key1: # prev1 = curr_node1 # curr_node1 = curr_node1.next # # prev2 = None # curr_node2 = self.head # while curr_node2 and curr_node2.data != key2: # prev2 = curr_node2 # curr_node2 = curr_node2.next # # if not curr_node1 or not curr_node2: # return # if prev1: # prev1.next = curr_node2 # else: # self.head = curr_node2 # if prev2: # prev2.next = curr_node1 # else: # self.head = curr_node1 # # curr_node1.next, curr_node2.next = curr_node2.next, curr_node1.next def swap_node(self,key1,key2): if key1 == key2: return prev1 = None curr1 = self.head while curr1 and curr1.data!=key1: prev1 = curr1 curr1 = curr1.next prev2 = None curr2 = self.head while curr2 and curr2.data != key2: prev2 = curr2 curr2 = curr2.next if not curr1 or not curr2: return if prev1: prev1.next = curr2 else: self.head = curr2 if prev2: prev2.next = curr1 else: self.heaf = curr1 curr1.next, curr2.next = curr2.next, curr1.next def reverse_list_iterative(self): curr = self.head prev = None while curr: nxt = curr.next curr.next = prev prev = curr curr = nxt self.head = prev def reverse_list_recursive(self): def reverse_list_recursive(prev,curr): if not curr: return prev nxt = curr.next curr.next = prev prev = curr curr = nxt return reverse_list_recursive(prev,curr) self.head = reverse_list_recursive(prev = None,curr = self.head) def merge_linked_list(self,llist): p = self.head q = llist.head s=None if not p: return q if not q: return p if p and q: if p.data > q.data: s = q q = s.next else: s = p p = s.next new_head = s while p and q: if q.data > p.data: s.next = p s = p p = s.next else: s.next = q s = q q = s.next if not p: s.next = q if not q: s.next = p return new_head def remove_duplicates(self): my_dict = {} curr = self.head prev = None if not curr: return if prev is None: prev = curr my_dict[curr.data] = 1 curr = curr.next # else: while curr: if curr.data in my_dict: prev.next = curr.next curr = None else: my_dict[curr.data] = 1 print(my_dict) prev = curr curr = prev.next class stack: def __init__(self): self.items =[] def push(self,data): self.items.append(data) def pop(self): return self.items.pop() def is_empty(self): return self.items == [] def is_peek(self): return self.items[-1] def get_stack(self): return self.items def reverse_str(input_str): s = stack() out_str = '' for i in input_str: s.push(i) while not s.is_empty(): out_str = out_str + s.pop() return out_str # llist = LinkedList() # llist.append('a') # llist.append('b') # llist.append('c') # # llist.printlist() # # llist.remove_node('a') # # llist.printlist() # llist.printlist() # # llist.remove_node_by_index(1) # # llist.printlist() # print(llist.iterative_length()) # print(llist.recursive_length(llist.head)) # print(reverse_str("areeb")) # llist.printlist() # # llist.swap_node('b','c') # llist.printlist() # llist.reverse_list_recursive() # llist.printlist() llist = LinkedList() llist1 = LinkedList() llist.append(2) llist.append(3) llist.append(4) llist.append(6) llist.append(8) # llist.printlist() # print("\n") # llist1.append(1) # llist1.append(5) # llist1.append(7) # llist1.printlist() # llist1.merge_linked_list(llist) # llist.merge_linked_list(llist1) # print("\n") # llist.printlist() # print("\n") # llist1.merge_linked_list(llist) llist.append(2) llist.append(3) llist.printlist() print("\n") llist.remove_duplicates() llist.printlist()
2b6d2383e34cb69fa3ade28f93b0faca196dfe7a
ChanKamyung/Covert-transmission-based-on-ICMP
/transmitting terminal/mLib/Huffman.py
7,649
3.578125
4
#!/usr/bin/python3 # _*_ coding=utf-8 _*_ import sys sys.setrecursionlimit(1000000) #压缩大文件实时会出现超出递归深度,故修改限制 #定义哈夫曼树的节点类 class node(object): def __init__(self, value=None, left=None, right=None, father=None): self.value = value self.left = left self.right = right self.father = father def build_father(left, right): n = node(value= left.value + right.value, left= left, right= right) left.father = right.father = n return n def encode(n): if n.father == None: return b'' if n.father.left == n: return node.encode(n.father) + b'0' #左节点编号'0' else: return node.encode(n.father) + b'1' #右节点编号'1' #哈夫曼树构建 def build_tree(l): if len(l) == 1: return l sorts = sorted(l, key= lambda x: x.value, reverse= False) #升序排列 n = node.build_father(sorts[0], sorts[1]) sorts.pop(0) sorts.pop(0) sorts.append(n) return build_tree(sorts) def encode(node_dict, debug=False): ec_dict = {} for x in node_dict.keys(): ec_dict[x] = node.encode(node_dict[x]) if debug == True: #输出编码表(用于调试) print(x) print(ec_dict[x]) return ec_dict def encodefile(inputfile): #数据初始化 node_dict = {} #建立原始数据与编码节点的映射,便于稍后输出数据的编码 count_dict = {} print("Starting encode...") ####为带时间戳文件名定制的功能,可无视#### stamp = '' tmp = inputfile.split('_*C4CHE*_') if len(tmp) == 2: stamp = tmp[0] inputfile = tmp[1] #################################### with open(inputfile,"rb") as f: bytes_width = 1 #每次读取的字节宽度 i = 0 f.seek(0,2) count = f.tell() / bytes_width print('length =', count) nodes = [] #结点列表,用于构建哈夫曼树 buff = [b''] * int(count) f.seek(0) #计算字符频率,并将单个字符构建成单一节点 while i < count: buff[i] = f.read(bytes_width) if count_dict.get(buff[i], -1) == -1: count_dict[buff[i]] = 0 count_dict[buff[i]] = count_dict[buff[i]] + 1 i = i + 1 print("Read OK") #print(count_dict) #输出权值字典,可注释掉 for x in count_dict.keys(): node_dict[x] = node(count_dict[x]) nodes.append(node_dict[x]) tree = build_tree(nodes) #哈夫曼树构建 ec_dict = encode(node_dict) #构建编码表 print("Encode OK") head = sorted(count_dict.items(), \ key= lambda x: x[1] ,reverse= True) #对所有根节点降序排序 bit_width = 1 print("head:",head[0][1]) #动态调整编码表的字节长度,优化文件头大小 if head[0][1] > 255: bit_width = 2 if head[0][1] > 65535: bit_width = 3 if head[0][1] > 16777215: bit_width = 4 print("bit_width:", bit_width) outfile = stamp + inputfile.replace(inputfile[inputfile.index('.'):],'.hfm') with open(outfile, 'wb') as o: name = inputfile.split('/') o.write((name[-1] + '\n').encode('utf-8')) #写出原文件名 o.write(int.to_bytes(len(ec_dict), 2, byteorder= 'big')) #写出结点数量 o.write(int.to_bytes(bit_width, 1, byteorder= 'big')) #写出编码表字节宽度 for x in ec_dict.keys(): #编码文件头 o.write(x) o.write(int.to_bytes(count_dict[x], bit_width, byteorder= 'big')) print('head OK') raw = 0b1 last = 0 for i in range(int(count)): #开始压缩数据 for x in ec_dict[buff[i]]: raw = raw << 1 if x == 49: raw = raw | 1 if raw.bit_length() == 9: raw = raw & (~(1 << 8)) o.write(int.to_bytes(raw ,1 , byteorder= 'big')) o.flush() raw = 0b1 tmp = int(i / len(buff) * 100) if tmp > last: print("encode:", tmp, '%') #输出压缩进度 last = tmp if raw.bit_length() > 1: #处理文件尾部不足一个字节的数据 offset = 8 - (raw.bit_length() - 1) raw = raw << offset raw = raw & (~(1 << raw.bit_length() - 1)) o.write(int.to_bytes(raw ,1 , byteorder = 'big')) o.write(int.to_bytes(offset, 1, byteorder = 'big')) ### print("File encode successful.") def decodefile(inputfile): print("Starting decode...") with open(inputfile, 'rb') as f: f.seek(0, 2) eof = f.tell() f.seek(-1, 1) offset = int.from_bytes(f.read(1), byteorder= 'big') f.seek(0) name = inputfile.split('/') outputfile = inputfile.replace(name[-1], \ f.readline().decode('utf-8')) with open(outputfile.replace('\n','') ,'wb') as o: count = int.from_bytes(f.read(2), \ byteorder= 'big') #取出结点数量 bit_width = int.from_bytes(f.read(1), \ byteorder= 'big') #取出编码表字宽 de_dict = {} for i in range(int(count)): #解析文件头 key = f.read(1) value = int.from_bytes(f.read(bit_width), byteorder= 'big') de_dict[key] = value node_dict = {} nodes = [] inverse_dict = {} for x in de_dict.keys(): node_dict[x] = node(de_dict[x]) nodes.append(node_dict[x]) tree = build_tree(nodes) #重建哈夫曼树 ec_dict = encode(node_dict) #建立编码表 for x in ec_dict.keys(): #反向字典构建 inverse_dict[ec_dict[x]] = x data = b'' raw = 0 last = 0 for i in range(f.tell(), eof - 1): #efo处记录的是offset,故此处-1 raw = int.from_bytes(f.read(1), byteorder= 'big') #print("raw:",raw) j = 8 while j > 0: if (raw >> (j - 1)) & 1 == 1: data = data + b'1' raw = raw & (~(1 << (j - 1))) else: data = data + b'0' raw = raw & (~(1 << (j - 1))) if inverse_dict.get(data, -1) != -1: o.write(inverse_dict[data]) o.flush() if i == eof - 2 and j - offset == 1: break #print("decode",data,":",inverse_dict[data]) data = b'' j = j - 1 tep = int(i / eof * 100) if tep > last: print("decode:", tep,'%') #输出解压进度 last = tep raw = 0 print("File decode successful.") if __name__ == '__main__': if input("1:压缩文件\t2:解压文件\n请输入你要执行的操作:") == '1': encodefile(input("请输入要压缩的文件:")) else: decodefile(input("请输入要解压的文件:"))
8188340bb9b5f124562bfe9401c0259ba42ab673
baixianghuang/algorithm
/python3/print_1_to_n_largest.py
1,207
3.859375
4
def print1_to_n_largest(n): """ Big number problem print 1 to the largest n digits """ if n <= 0: return L = [] for i in range(n): L.append(0) # print(L) new_list = L[:] while True: new_list = add_one_list(new_list, n) print_list_to_num(new_list) list_convet_int = convert_list_to_int(new_list) if list_convet_int == 10**n - 1: break def add_one_list(L, n): """simulate integer arithmetic to list""" result = L[:] carry = 1 for i in range(n-1, -1, -1): # note that L[len(L)] is exceed the range sum = L[i] + carry if sum == 10: carry = 1 else: carry = 0 result[i] = sum % 10 return result def print_list_to_num(L): """print the number represented by the list without 0s prefix""" is_beginning_0 = True for c in L: if c != 0 and is_beginning_0: is_beginning_0 = False if not is_beginning_0: print(c, end='') print() def convert_list_to_int(L): list_to_str = '' for i in range(len(L)): list_to_str += str(L[i]) return int(list_to_str) print_1_to_n_largest(6)
bd6b8a39bd376c6bcf9a3a56a4a70453159e05f4
baixianghuang/algorithm
/python3/merge_linked_lists.py
2,215
4.3125
4
class ListNode: def __init__(self, val): self.val = val self.next = None def merge_linked_lists_recursively(node1, node2): """"merge 2 sorted linked list into a sorted list (ascending)""" if node1 == None: return node2 elif node2 == None: return node1 new_head = None if node1.val >= node2.val: new_head = node2 new_head.next = merge_linked_lists_recursively(node1, node2.next) else: new_head = node1 new_head.next = merge_linked_lists_recursively(node1.next, node2) return new_head def merge_linked_lists(head1, head2): """"merge 2 sorted linked list into a sorted list (ascending)""" node1 = head1 node2 = head2 if node1 == None: return head2 elif node2 == None: return head1 if node1.val >= node2.val: head_tmp = node2 node2 = node2.next else: head_tmp = node1 node1 = node1.next node_tmp = head_tmp while node1 and node2: # print(node1.val, node2.val) if node1.val >= node2.val: # insert node2 after head_new node_tmp.next = node2 node_tmp = node2 node2 = node2.next else: # insert node1 after head_new node_tmp.next = node1 node_tmp = node1 node1 = node1.next if node1 != None: while node1 != None: node_tmp.next = node1 node_tmp = node_tmp.next node1 = node1.next elif node2 != None: while node2 != None: node_tmp.next = node2 node_tmp = node_tmp.next node2 = node2.next return head_tmp # list 1: 1 -> 3 -> 5 # list 2: 2 -> 4 -> 6 node_1 = ListNode(1) node_2 = ListNode(2) node_3 = ListNode(3) node_4 = ListNode(4) node_5 = ListNode(5) node_6 = ListNode(6) node_1.next = node_3 node_3.next = node_5 node_2.next = node_4 node_4.next = node_6 test1 = merge_linked_lists(node_1, node_2) while test1: print(test1.val, " ", end="") test1 = test1.next print() # test2 = merge_linked_lists_recursively(node_1, node_2) # while test2: # print(test2.val, " ", end="") # test2 = test2.next
059bb202ef3eb4909e0e58327ddf149e64695b30
baixianghuang/algorithm
/python3/produce_ugly_number.py
1,779
3.703125
4
def produce_ugly_number_solution_1(n): """ produce the n-th ugly number by generating n ugly number the ugly number next to K is some number prior to K times 2 or 3 or 5 """ ls = [1] # store ugly number k = 0 t2, t3, t5 = 0, 0, 0 for i in range(n - 1): while 2 * ls[t2] < ls[i]: t2 += 1 m2 = 2 * ls[t2] while 3 * ls[t3] < ls[i]: t3 += 1 m3 = 3 * ls[t3] while 5 * ls[t5] < ls[i]: t5 += 1 m5 = 5 * ls[t5] ls.append(min(m2, m3, m5)) if ls[i + 1] == m2: t2 += 1 if ls[i + 1] == m3: t3 += 1 if ls[i + 1] == m5: t5 += 1 return ls[n-1] def produce_ugly_number_solution_2(n): """ less efficient than solution_1, "for i in range(len(ls))" is more time-consuming """ ls = [1] # store ugly number k = 0 while k < n: # find the first number * 2 or 3 or s larger than ls[k] for i in range(len(ls)): if ls[i] * 2 > ls[k]: m2 = ls[i] * 2 break for i in range(len(ls)): if ls[i] * 3 > ls[k]: m3 = ls[i] * 3 break for i in range(len(ls)): if ls[i] * 5 > ls[k]: m5 = ls[i] * 5 break ls.append(min(m2, m3, m5)) k += 1 return ls[n-1] def is_ugly(num): if num % 7 == 0: return False while num % 2 == 0: num /= 2 while num % 3 == 0: num /= 3 while num % 5 == 0: num /= 5 if num == 1: return True else: return False print(is_ugly(produce_ugly_number_solution_1(1500))) print(is_ugly(produce_ugly_number_solution_2(1500)))
9ad0651f040163eb373e3ed365f597520c08c432
baixianghuang/algorithm
/python3/min_in_rotated_list.py
910
3.546875
4
def min_in_rotated_list(ls): if ls == None: return False start = 0 end = len(ls) - 1 while ls[start] >= ls[end]: if end - start == 1: return ls[end] mid_index = (start + end) >> 1 # have to perform linear search if ls[mid_index] == ls[start] and ls[mid_index] == ls[end]: return linear_min_search(ls) # print(mid_index, L[mid_index]) if ls[mid_index] >= ls[start]: start = mid_index elif ls[mid_index] <= ls[end]: end = mid_index return ls[start] def linear_min_search(L): ans = L[0] for e in L: if e < ans: ans = e return ans print(linear_min_search([1, 1, 1, 0, 1])) print(min_in_rotated_list([3, 4, 5, 1, 2])) print(min_in_rotated_list([1, 2, 3, 4, 5])) # special case 1 print(min_in_rotated_list([1, 1, 1, 0, 1])) # special case 2
3d923845ebbf843842d3012738e3bfd89de988df
enomarozi/Crypto_Classic-Py
/Bruteforce_Char.py
360
3.609375
4
import sys def ROT(n): text = sys.argv[1] if sys.argv[3] == "+": hasil = [chr(ord(i)+n) for i in text] hasil1 = "".join(hasil) return hasil1 elif sys.argv[3] == "-": hasil = [chr(ord(i)-n) for i in text] hasil1 = "".join(hasil) return hasil1 for rot in range(int(sys.argv[2])): print(ROT(rot))
772841e9812d286aff348f1b083d040596ccac51
Dyfeomorfizm/pdfApp
/db_setup.py
1,036
3.578125
4
import sqlite3 from sqlite3 import Error def create_connection(db_file): try: conn = sqlite3.connect(db_file) return conn except Error as e: print e return None def create_table(conn, create_table_sql): try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print e def run(): database = 'pdf.db' sql_create_pdf_table = """ CREATE TABLE IF NOT EXISTS pdf_info ( id integer PRIMARY KEY, text_box text NOT NULL, x0 float NOT NULL, x1 float NOT NULL, y0 float NOT NULL, y1 float NOT NULL );""" conn = create_connection(database) if conn is not None: create_table(conn, sql_create_pdf_table) else: print "Connection Error" if __name__ == '__main__': run()
09ac2411c4ab5a675d4bd478b4c76dd70e9c7a44
juancamilo840/Taller-estructuras-de-control-secuenciales
/Taller de estructuras secuenciales/ejercicio13.py
606
3.609375
4
numero_billetes = 8 total = numero_billetes billetes = [float() for ind0 in range(numero_billetes)] billetes[0] = 50.000 billetes[1] = 20.000 billetes[2] = 10.000 billetes[3] = 5.000 billetes[4] = 2.000 billetes[5] = 1.000 billetes[6] = 500 billetes[7] = 100 cantidad_bill_mon = [str() for ind0 in range(total)] indice_billetes = 0 print("Dame una cantidad de billetes mayor a 0") cantidad = float(input()) if cantidad>1: cantidad_entera = int(cantidad) cantidad_decimal = int((cantidad-cantidad_entera)*100) for i in range(total): else: print("La cantidad de billetes mayor a 0")
daacdc0089feccde08146ea17f5ccdf4726c7205
juancamilo840/Taller-estructuras-de-control-secuenciales
/Taller de estructuras secuenciales/ejercicio7.py
306
4
4
# 1 metro a pies = 12 # 1 metro a pulgadas = 39.27 metro = float() pulgada = float() pies = float() print("Escribe los metros") metro = float(input()) pulgada = metro*39.27 pies = metro*12 print(metro,"metros convertidos a pulgadas es: ",pulgada) print(metro,"metros convertidos a pies es: ",pies)
4e2560f2c51492fd9570b6dfcfa6da6ec706eacd
juancamilo840/Taller-estructuras-de-control-secuenciales
/main.py
416
3.75
4
if __name__ == '__main__': print("Escribe la cantidad invertida") cantidad = float(input()) print("Escribe la tasa de interes") tasa = float(input()) intereses = cantidad*tasa if intereses>100000: print("Los intereses ganados son $",intereses," superan los $100000") else: print("Los intereses ganados son $",intereses," no superan los $10000") print("El sado total en la cuenta es: ",cantidad+intereses)
184af18b52ad0074b0f6326c9fbaf0f4c08a7fac
juancamilo840/Taller-estructuras-de-control-secuenciales
/Taller de estructuras secuenciales/ejercicio15.py
286
3.765625
4
print("Ingrese el precio del producto:") precio = float(input()) print("Ingrese la cantidad de productos a comprar:") cantidad = float(input()) print("Ingrese su Precio de venta al publico:") pvp = float(input()) compra = precio*cantidad*pvp print("el total a pagar es:",compra)
b456c2de95435a83162b4729138702ac80fab821
Faye-HuihuiChen/Python
/Investigating Texts and Calls/Task3.py
3,582
4.28125
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixed line telephones in Bangalore. Fixed line numbers include parentheses, so Bangalore numbers have the form (080)xxxxxxx.) Part A: Find all of the area codes and mobile prefixes called by people in Bangalore. - Fixed lines start with an area code enclosed in brackets. The area codes vary in length but always begin with 0. - Mobile numbers have no parentheses, but have a space in the middle of the number to help readability. The prefix of a mobile number is its first four digits, and they always start with 7, 8 or 9. - Telemarketers' numbers have no parentheses or space, but they start with the area code 140. Print the answer as part of a message: "The numbers called by people in Bangalore have codes:" <list of codes> The list of codes should be print out one per line in lexicographic order with no duplicates. Part B: What percentage of calls from fixed lines in Bangalore are made to fixed lines also in Bangalore? In other words, of all the calls made from a number starting with "(080)", what percentage of these calls were made to a number also starting with "(080)"? Print the answer as a part of a message:: "<percentage> percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore." The percentage should have 2 decimal digits """ def get_telephone_type(tel_num): if tel_num.startswith('(0') and tel_num.find(')') != -1: return 'fixed' elif (tel_num.startswith('7') or tel_num.startswith('8') or tel_num.startswith('9')) and ' ' in tel_num: return 'mobile' elif tel_num.startswith('140'): return 'telemarketers' else: return None def extract_area_code(tel_num, tel_type): if tel_type == 'fixed': return tel_num[1:tel_num.find(')')] elif tel_type == 'mobile': return tel_num[0:4] elif tel_type == 'telemarketers': return '140' else: return None def extract_receiver_area_codes(calls, caller_prefix, duplicates=False): area_codes = [] for call in calls: if call[0].startswith('{}'.format(caller_prefix)): # telephone callers tel_type = get_telephone_type(call[1]) area_code = extract_area_code(call[1], tel_type) if area_code: if duplicates: area_codes.append(area_code) else: if area_code not in area_codes: area_codes.append(area_code) return area_codes def get_number_of_calls(calls, caller_prefix, receiver_area_code): number_of_calls = 0 area_codes = extract_receiver_area_codes(calls, caller_prefix, duplicates=True) for area_code in area_codes: if area_code == receiver_area_code: number_of_calls += 1 return (number_of_calls, len(area_codes)) # tuple returned (number of calls for specific area code, total number of calls) def calc_percentage(ratio): return round(ratio[0] / ratio[1] *100, 2) def get_percentage_of_calls(calls, caller_prefix, receiver_area_code): return calc_percentage(get_number_of_calls(calls, caller_prefix, receiver_area_code)) print('The numbers called by people in Bangalore have codes: \n{}'.format('\n'.join(extract_receiver_area_codes(calls, '(080)')))) print('{} percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore.'.format(get_percentage_of_calls(calls, '(080)', '080')))
4ddfbf5cf2ae8a5f3916f15995edc7791e7d2741
akriti8692/Python
/PS4_Q2.py
967
3.84375
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 4 18:47:09 2020 @author: 16509 """ input1=0 C=0 F=0 A=0 z=0 #User input : Farenheit to Celsius def display_menu(): input1=input("Indicate which temperature conversion you would like to perform, by entering 1 or 2,1. Fahrenheit to Celsius2. Celsius to Fahrenheit") return input1 def convert_temp(A): if (A=='1'): F=int(input("Enter Fahrenheit value")) C= (5/9*(F - 32)) print(C) elif (A=='2'): C=int(input("Enter Celcius Value")) F = C*9/5 + 32 print(F) else: print("Invalid Input") def ask(): z=str(input("Do you want to reiterate the conversion? answer yes or y")) if ((z=='yes') or (z=='y')): main() else: print("we are good to end") def main(): A = display_menu() convert_temp(A) ask() 4 main()
1a06651d7f569ee946e116e7e0cd1918b15e6f32
akriti8692/Python
/PS4_Q3.py
1,518
3.90625
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 4 20:43:10 2020 @author: 16509 """ dict1={} list1=[] list2=[] assignment=['Homework','Midterm','FinalExam'] def enter_grade(assignment,amount,max_grade): for i in assignment: if i=='Homework': while z in range(1,4): a=input("Enter your Homework marks {}".format(z)) list1.append(a) if i=='Midterm': while z in range(1,3): a=input("Enter your Midterm marks {}".format(z)) list2.append(a) if i=='FinalExam': val1=input("Enter your final Grade") def setup_grade(dict1): enter_grade() def display_grade(): #this need not be called from main def average_grade(list1,list2): averagehw=(list1[0]+list1[1]+list1[2])/3 averagemt=(list2[0]+list2[1])/2 return averagehw return averagemt def course_grade(list1,list2,val1): hwa=average_grade() mida=average_grade() CourseGrade= .25*hwa+.50*mida+.25*val1 #For Printing Course GRade def letter_grade(CourseGrade): if CourseGrade>=90 and CourseGrade<=100: print("A") elif CourseGrade>=80 and CourseGrade<=89: print("B") elif CourseGrade>=70 and CourseGrade<=79: print("C") elif CourseGrade>=60 and CourseGrade <=69: print("D") elif CourseGrade>=0 and CourseGrade<=59: print("F") def main()
56bb2d591702c721ed9891e9c60e2fabb0cf80ff
danmorales/Python-Pandas
/pandas-ex19.py
358
4.125
4
import pandas as pd array = {'A' : [1,2,3,4,5,4,3,2,1], 'B' : [5,4,3,2,1,2,3,4,5], 'C' : [2,4,6,8,10,12,14,16,18]} df_array = pd.DataFrame(data=array) print("Arranjo original") print(df_array) print("\n") print("Removendo linhas cuja coluna B tenha valores iguais a 3") df_array_new = df_array[df_array.B != 3] print("Novo arranjo") print(df_array_new)
d8418624bde68e75ac2edbbcf1d56830d6b9c75e
helloimyames/PythonEssentials3
/syntax_strings.py
214
3.640625
4
def main(): n = 40 print("this is a {}".format(n)) print('this is a {}'.format(n)) print('''this is a string text text ''') if __name__=="__main__": main()
e6afd3612c19a356fa9c4ef6215a0846a04193b1
xuan2020/teamlearn
/productrecommendation.py
9,657
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sep 24 @author: cheryl Programming Project: Recommendation Examine item co-purchasing. Assignment: working with data on purchases from retail stores. The task will be to create recommendations for someone who has just bought a product, based on which items are often bought together with the product. """ import os import numpy as np import pandas as pd from astroid.__pkginfo__ import description ''' Function fillPeopleProducts() with one parameter of type DataFrame, storing the purchasing data. The function should create and return a new data frame, which will summarize which products were bought by which customer. The new data frame must be indexed by the customer ids (presented in USER_ID column of the purchasing data) with column titles corresponding to product ids (PRODUCT_ID column of the purchasing data). ''' def fillPeopleProducts (purchaseDF): userProductArray = purchaseDF.iloc[:,:2].values userProductDict = {} for item in userProductArray: userProduct = userProductDict.get(item[0],[]) userProduct.append(item[1]) userProductDict[item[0]] = userProduct #print(userProductDict) userList = list(set(purchaseDF['USER_ID'])) userList.sort() productList = list(set(purchaseDF['PRODUCT_ID'])) productList.sort() outList = [] innerList = [] for user in userList: innerList = [] for product in productList: if product in userProductDict.get(user): innerList.append(1) else: innerList.append(0) outList.append(innerList) frame = pd.DataFrame(outList, columns = productList,index = userList) #pd.set_option('display.max_columns', 1000) #pd.set_option('display.max_rows', 1000) #pd.set_option('display.width', 1000) return frame ''' Function fillProductCoPurchase () with one parameter of type DataFrame, storing the purchasing data. The function should create a data frame representing the co-purchasing matrix. To do it, it must first call function fillPeopleProducts() to obtain the data frame with the summary of purchases by customer, let’s call this data frame peopleProducts. Recall, that for each row, representing a customer and column representing a product, peopleProducts[i,j] stores 1 if customer i bought product j, and 0 otherwise. ''' def fillProductCoPurchase (purchaseDF): peopleProducts = fillPeopleProducts(purchaseDF) productList = list(set(purchaseDF['PRODUCT_ID'])) productList.sort() #allZero = np.zeros((len(productList),len(productList)), dtype = int) copurchaseDF = pd.DataFrame(columns = productList, index = productList) pd.set_option('display.max_columns', 1000) pd.set_option('display.max_rows', 1000) pd.set_option('display.width', 1000) #print(copurchaseDF) for product1 in productList: for product2 in productList: if product1 != product2: vector1 = peopleProducts.loc[:,product1].values vector2 = peopleProducts.loc[:,product2].values copurchase = np.dot(vector1,vector2) copurchaseDF[product1][product2] = copurchase else: copurchaseDF[product1][product2] = 0 return (copurchaseDF,peopleProducts) ''' Function findMostBought(), which will be passed the peopleProducts data frame as a parameter, and must return a list of items that have been purchased by more customers than any other item. ''' def findMostBought(peopleProducts): ''' productList = [] boughtMost = 0 productDict = {} for product in peopleProducts.columns: numberOfBought = peopleProducts[product].sum() products = productDict.get(numberOfBought,[]) products.append(product) productDict[numberOfBought] = products if numberOfBought > boughtMost: boughtMost = numberOfBought ''' mostBoughtProducts = [] maxNumberOfBought = peopleProducts.sum().max() for product in peopleProducts.columns: if peopleProducts[product].sum() == maxNumberOfBought: mostBoughtProducts.append(product) #print('mostBought:', mostBoughtProducts) return mostBoughtProducts # return productDict.get(boughtMost) ''' Function reformatProdData(), which will be passed the product data frame as a parameter. The product data contains a combination of the product name and category in the DESCRIPTION column. This function must separate the name from the category, leaving only the name in the DESCRIPTION column and creating a new CATEGORY column, with the category name. For example, from the original product DESCRIPTION value Colorwave Rice Bowl (Dinnerware), Colorwave Rice Bowl should be stored under DESCRIPTION and Dinnerware under CATEGORY. ''' def reformatProdData(productDF): description = productDF.DESCRIPTION.str.split("(").str.get(0) category1 = productDF.DESCRIPTION.str.split("(").str.get(1) category = category1.str.split(")").str.get(0) productDF.DESCRIPTION = description productDF['CATEGORY'] = category # print(productDF) return '''the list of recommended product ids''' def recommendedProductID (boughtProduct, copurchaseDF): mostBoughtProducts = [] maxNumberOfBought = copurchaseDF[boughtProduct].max() # can find recommended products withut looping, using pandd=as functions for product in copurchaseDF.columns: if copurchaseDF[boughtProduct][product] == maxNumberOfBought: mostBoughtProducts.append(product) # print('mostBought:', mostBoughtProducts) return mostBoughtProducts, maxNumberOfBought ''' Function printRecProducts(), which will be passed the product data frame and the list of recommended product ids. The function must produce a printout of all recommendations passed in via the second parameter, in alphabetical order by the category. Make sure to examine the sample interactions and implement the formatting requirements. The function should return no value. ''' def printRecProducts(productDF, recommendProductsLists): #productDF = productDF.sort_values(by=['CATEGORY']) #print(productDF) #print(recommendProductsLists) selected=productDF[ productDF['PRODUCT_ID'].isin (recommendProductsLists) ] selected = selected[['CATEGORY', 'DESCRIPTION', 'PRICE']] selected.sort_values(by=['CATEGORY'], inplace=True) rowNum, columnNum = selected.values.shape selected.index = range(1, rowNum+1) # print(selected) currentCategory = '' printCategory = '' for i in range(1, rowNum+1): if printCategory != selected['CATEGORY'][i]: currentCategory = selected['CATEGORY'][i] printCategory = currentCategory else: currentCategory = '' maxLehgth = selected['CATEGORY'].str.len().max() if pd.isna(selected['PRICE'][i]): print('IN', currentCategory.upper().ljust(maxLehgth), '--', selected['DESCRIPTION'][i]) else: print('IN', currentCategory.upper().ljust(maxLehgth), '--', selected['DESCRIPTION'][i]+', $'+format(selected['PRICE'][i],'.2f')) return '''Function main(), which will be called to start the program and works according to design.''' def main (): cwd = os.getcwd() folder = input("Please enter name of folder with product and purchase data files: (prod.csv and purchases.csv):") # folder = 'pdata-tiny' folderpath = os.path.join(cwd,folder) productPath = os.path.join(folderpath, 'prod.csv') productCSV = pd.read_csv(productPath) productDF = pd.DataFrame(productCSV) purchasePath = os.path.join(folderpath, 'purchases.csv') purchaseCSV = pd.read_csv(purchasePath) purchaseDF = pd.DataFrame(purchaseCSV) print('\nPreparing the co-purchasing matrix...\n') (copurchaseDF,peopleProducts) = fillProductCoPurchase (purchaseDF) findMostBought(peopleProducts) reformatProdData(productDF) #print(productDF) boolean = True while boolean: boughtProduct = input('Which product was bought? Enter product id or press enter to quit.') if boughtProduct == "": boolean = False else: mostBoughtProducts = findMostBought(peopleProducts) recommendProducts, maxNumberOfBought = recommendedProductID (boughtProduct, copurchaseDF) print('[Maximum co-purchasing score', maxNumberOfBought, ']') if maxNumberOfBought ==0 : print("Recommend with", boughtProduct.upper(), ":", mostBoughtProducts) print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print('Suggest one of our most popular products:') printRecProducts(productDF, mostBoughtProducts) else: print("Recommend with", boughtProduct.upper(), ":", recommendProducts) print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print('People who bought it were most likely to buy:') printRecProducts(productDF, recommendProducts) print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') pd.set_option('display.max_columns', 1000) pd.set_option('display.max_rows', 1000) pd.set_option('display.width', 1000) main()
c53aa430dfa5da2ceeb01bc5e9ad1e5ab4f3da3d
shashwatrathod/CompetitiveCoding
/Arrays/SortColors.py
919
3.6875
4
#https://leetcode.com/problems/sort-colors/ #O(1) space req; O(n) time; only one pass in the array class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ zero_pointer = -1 two_pointer = len(nums) i = 0 while i<two_pointer: if(nums[i]==0): if(i==zero_pointer+1): zero_pointer+=1 i += 1 else: temp = nums[zero_pointer+1] nums[zero_pointer+1] = nums[i] nums[i] = temp zero_pointer += 1 elif(nums[i]==2): temp=nums[two_pointer-1] nums[two_pointer-1] = nums[i] nums[i] = temp two_pointer -= 1 elif(nums[i]==1): i += 1
96133f56fdadf80059d2b548a3ae485dee91f770
suhaslucia/Pythagoras-Theorem-in-Python
/Pythagoras Theorem.py
1,114
4.40625
4
from math import sqrt #importing math package print(" ----------Pythagoras Theorem to Find the sides of the Triangle---------- ") print(" ------------ Enter any one side as 0 to obtain the result -------------- ") # Taking the inputs as a integer value from the user base = int(input("Enter the base of the Triangle: ")) perpendicular = int(input("Enter the perpendicular of the Triangle: ")) hypotenuse = int(input("Enter the hypotenuse of the Triangle: ")) # Calculating the Hypotenuse value and printing it if hypotenuse == 0: b = base ** 2 p = perpendicular ** 2 hyp = b + p result = sqrt(hyp) print(f'\n Hypotenuse of Triangle is {result}') # Calculating the Perpendicular value and printing it elif perpendicular == 0: b = base ** 2 hyp = hypotenuse ** 2 p = hyp - b result = sqrt(p) print(f'\n Perpendicular of Triangle is {result}') # Calculating the Base value and printing it else: p = perpendicular ** 2 hyp = hypotenuse ** 2 b = hyp - p result = sqrt(b) print(f'\n Base of Triangle is {result}')
1fa756ca401e6b49f5d05608771ec788ae4f6324
RakshaAchuth/Python-in-PYCharm
/oopsproject/book.py
389
3.5625
4
#book class Book: #pass #constructor def __init__(self, name): # print(name) self.name = name # print('book instance created') # boo1 = Book('gggggggggggg') strybook = Book('yyyyyyb hh') pythonbook = Book('hey hello') boo1.name = 'gggggggggggg' strybook.name='yyyyyyb hh' pythonbook.name = 'hey hello' print(boo1.name) print(strybook.name)
27cb0a98236f95d0c146c34574fb954d1bf03878
RakshaAchuth/Python-in-PYCharm
/exceptionhandling/tryexceptionerror.py
623
3.78125
4
#open file/resource # just try and finally are allowed # try eith except are allowed #try eith else and finally are not allowed # try is mandatory try: #try business logic to read i = 1 #input from user j = 10/i values = [1, '2'] sum(values) except TypeError: print('TypeError') j = 10 except ZeroDivisionError: print('ZeroDivisionError') j = 0 except: print('other error') j = 5 else: #operation when next block does not throw exception print('Else') finally: #close file here(else resource leakage will occure print('finally') print(j) print("End")
a1c99d43da0be47d5bf14e0ce3dbafe24cce88b1
CypherPandaGit/Sorter
/sorter.py
2,245
3.5
4
import os import sys from pathlib import Path # This will be new directories HTML, IMAGES, AUDIO etc. dirs = { 'Web': ['.html', '.htm'], 'Zips': ['.exe', '.zip', '.rar'], 'Documents': ['.docx', '.doc', '.pdf', '.xls', '.odt'], 'Images': ['.jpg', '.jpeg', '.gif', '.bmp', '.png', '.psd', '.heif'], 'Videos': ['.mp4', '.avi', '.flv', '.mov', '.mpeg'], 'Audio': ['.mp3', '.aac', '.wav']} # Only verification if directories in dictionary are created # for value in dirs.items(): # print(value) # Remapping dirs to file_formats; for example: '.doc': 'DOCUMENTS' file_formats = {file_extension: directory for directory, file_formats in dirs.items() for file_extension in file_formats} # Just check if everything is OK # for value in file_formats.items(): # print(value) # # print(os.listdir('.\\')) def organize_files(): # Main sorting function. It will check if directory exists. If yes; continune. # If not; new directory will be created print('Do you want to organize your files automatically?\nYes or No') answer = input() if answer.lower() == 'yes' or answer.lower() == 'y': for entry in os.scandir(): if entry.is_dir(): continue file_path = Path(entry) file_extension = file_path.suffix.lower() if file_extension in file_formats: directory_path = Path(file_formats[file_extension]) directory_path.mkdir(exist_ok=True) file_path.rename(directory_path.joinpath(file_path)) for dir in os.scandir(): try: os.rmdir(dir) except: pass print('---------------') print('-----DONE!-----') print('---------------') print('THAT WAS SIMPLE') print('---------------') elif answer.lower() == 'no' or answer.lower() == 'n': print('----------------') print('You answered No.') print('----------------') sys.exit() else: print('--------------------') print('Something went wrong') print('--------------------') if __name__ == '__main__': organize_files()
4f984ed69a9607d47938b77c3ae8c00ba719d2c5
Azuromalachite/KVIS-student-former-school
/visualization/bubble_plot.py
1,777
3.515625
4
import seaborn as sns import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv("KVIS student dataset.csv") dataset.columns = ['thai', 'region', 'english', 'income', 'expense', 'students'] def show_plot(dataset, region = 'all', show_none = False): __dataset = dataset if show_none == False: dataset = dataset[dataset['students'] != 0] print(dataset.iloc[:, 1:]) plt.figure() if region == 'all': dataset = dataset elif region == 'northern': dataset = dataset[dataset.region == "Northern"] elif region == 'central': dataset = dataset[dataset.region == "Central"] elif region == 'northeastern': dataset = dataset[dataset.region == "Northeastern"] elif region == 'southern': dataset = dataset[dataset.region == "Southern"] else: dataset = dataset ax = sns.scatterplot(data = dataset, x = 'income', y = 'expense', hue = 'region', size = 'students', sizes = (0, 100*__dataset.students.max()), legend = False, alpha = 0.7) for line in dataset.index: ax.text(dataset.income[line], dataset.expense[line], dataset.english[line], horizontalalignment = 'center', verticalalignment = 'bottom', size = 4, color = 'black', weight = 'regular') plt.xlabel("Average Monthly Income Per Household (2015)") plt.ylabel("Average Monthly Expenditure Per Household (2015)") plt.title("Correlation of Income-Expense per Household and Number of Qualified Students to KVIS") plt.show() show_plot(dataset, region = "all")
e37c016452aeb9b50db48a86974732a9b33ccbcf
Kumar1998/github-upload
/code19.py
89
3.8125
4
arr=[1,2,3,4] if arr[3]<arr[2]: print(1 and 0 or 1) else: print(1 or 0 and 0)
68e32356ee24ab2bbfc87c4ca3508e89eacd3a0b
Kumar1998/github-upload
/scratch_4.py
397
4.25
4
d1={'Canada':100,'Japan':200,'Germany':300,'Italy':400} #Example 1 Print only keys print("*"*10) for x in d1: print(x) #Example 2 Print only values print ("*"*10) for x in d1: print(d1[x]) #Example 3 Print only values print ("*"*10) for x in d1.values(): print(x) #Example 4 Print only keys and values print ("*"*10) for x,y in d1.items(): print(x,"=>",y)
ac00f76da12e449ceb5bf58d199945845ac67d89
Kumar1998/github-upload
/scratch_40.py
183
3.671875
4
"""Implement quick sort in Python. Input a list. Output a sorted list.""" def quicksort(array): return [] test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14] print(quicksort(test))
f13e3676b62ae860663a9603762471b5cc440741
Kumar1998/github-upload
/scratch_28.py
53
3.59375
4
a='1' a=a*3 print(a) b='44' b=b*4 print(b)
29f77abbba42434a5afab1d3f4dd4ad7460e6674
Kumar1998/github-upload
/code14.py
51
3.671875
4
x=2 for count in range(3): x=x**2 print(x)
dbb4af95e9b603a6383c6a0e9b72f3cac2a824ad
Kumar1998/github-upload
/scratch_27.py
399
3.890625
4
print(True or False) print(True and False) n=5 #number of levels for free for level in range(1,n+1): print(level * '*') for level in range(1,n+1): print(''*(n-level)+ level* '*') print(len("Hello")+len("World")) a={'d':3} print(a.get('d')) a['d']+=2 print(a.get('d')+3) temp=35 if temp>30: print("Hot!") elif temp>10: print("Warm") else: print("cold")
f38bd5b4882bd3787e78bcb653ca07d48b1f7093
Kumar1998/github-upload
/python1.py
573
4.3125
4
height=float(input("Enter height of the person:")) weight=float(input("Enter weight of the person:")) # the formula for calculating bmi bmi=weight/(height**2) print("Your BMI IS:{0} and you are:".format(bmi),end='') #conditions if(bmi<16): print("severly underweight") elif(bmi>=16 and bmi<18.5): print("underweight") elif(bmi>=18.5 and bmi>=25): print("underweight") elif(bmi>=18.5 and bmi<25): print("healthy") elif(bmi>=25 and bmi<30): print("overweight") elif(bmi>=30): print("severly overweight") import time time.sleep(30)
ba3603dc23513b718bba58232878c5b12125c894
Kumar1998/github-upload
/code27.py
67
3.640625
4
num=[8,8,8,8] x=1 for i in range (1,len(num)): x=1 print(x)
0ef75de1d6af5a7988a1a3ea683b3769e986bc12
septhiono/redesigned-meme
/Day 2 add two numbers in a single input.py
284
3.890625
4
import random word_list = ["aardvark", "baboon", "camel"] chosen_word = random.choice(word_list) print(f'Pssst, the solution is {chosen_word}.') display=["_"]*len(chosen_word) print(display) print(chosen_word) guess = input("Guess a letter: ").lower() print("weong")
98f763bd336731f8fa0bd853d06c059dd88d8ca7
septhiono/redesigned-meme
/Day 2 Tip Calculator.py
316
4.1875
4
print('Welcome to the tip calculator') bill = float(input('What was the total bill? $')) tip= float(input('What percentage tip would you like to give? ')) people = float(input("How many people split the bill? ")) pay= bill*(1+tip/100)/people pay=float(pay) print("Each person should pay: $",round(pay,2))
ee3eea76d3b3f21ddc5a8e037185a25fadef7e08
space-isa/profitable-app-profiles
/src/clean_data.py
2,315
3.640625
4
import numpy as np def find_duplicates(dataset, app_name_index, tag, use_array=True): """Find duplicate app names""" if use_array: dataset = np.asarray(dataset) app_names = dataset[:,app_name_index] unique_apps = set(app_names) duplicate_apps = len(dataset) - len(unique_apps) print("Out of {:,} {} apps, there are {:,} duplicates.".format(len(dataset), tag, duplicate_apps)) else: # Do the same thing without numpy arrays (less efficient!) duplicate_apps = [] unique_apps = [] for app in dataset: name = app[app_name_index] if name in unique_apps: duplicate_apps.append(name) else: unique_apps.append(name) duplicate_apps = len(duplicate_apps) print("Out of {:,} {} apps, there are {:,} duplicates.".format(len(dataset), tag, duplicate_apps)) return duplicate_apps, unique_apps def find_highest_reviews(dataset, duplicate_apps, app_reviews_index, app_name_index): if duplicate_apps > 0: reviews_max = {} for app in dataset: name = app[app_name_index] n_reviews = float(app[app_reviews_index]) if name in reviews_max and reviews_max[name] < n_reviews: reviews_max[name] = n_reviews elif name not in reviews_max: reviews_max[name] = n_reviews if len(dataset) - duplicate_apps == len(reviews_max): print("There are {:,} unique apps as expected.".format(len(reviews_max))) return reviews_max else: print("The lenghts do not match.") else: return "No duplicates." def clean_dataset(dataset, reviews_max, app_name_index, app_reviews_index): clean_data = [] already_added = [] for app in dataset: name = app[app_name_index] n_reviews = float(app[app_reviews_index]) if (reviews_max[name]==n_reviews) and (name not in already_added): clean_data.append(app) already_added.append(name) return clean_data
107a1c4635a7c78576af5dd5d99a70112a8afd4a
rugbyprof/4443-2D-PyGame
/Resources/R02/Pygame_Introduction/008_pyglesson.py
2,999
3.71875
4
""" Pygame 008 Description: Writing out the new colors file Randomly picking ball and screen colors New Code: None """ # Import and initialize the pygame library import pygame import random import json import pprint def fix_colors(infile): """ One time fix of original json file with only names and hex values. See previous lesson for commented function """ new_colors = {} with open(infile,'r') as f: data = f.read() colors = json.loads(data) for name,hex in colors.items(): new_colors[name] = {} new_colors[name]['hex'] = hex red = int(hex[1:3],16) green = int(hex[3:5],16) blue = int(hex[5:],16) rgb = (red,green,blue) new_colors[name]['rgb'] = rgb f = open("colors2.json","w") f.write(json.dumps(new_colors)) f.close() def load_colors(infile): """load_colors Params: infile <string> : path to color json file Returns: colors <json> ToDo: Exception handling for bad json and bad file path. """ with open(infile,'r') as f: data = f.read() colors = json.loads(data) return colors config = { 'title' :'006 Pygame Lesson', 'window_size' : (500,500) } # Calling the load_colors function turns "colors" # into a python dictionary just like the "config" # variable above (different structure but same idea) colors = load_colors('colors2.json') def main(): pygame.init() # Pull the "keys" (color names in this case) out of # the colors dictionary names = list(colors.keys()) # print them nice and pretty pprint.pprint(names) # sets the window title pygame.display.set_caption(config['title']) # Set up the drawing window screen = pygame.display.set_mode(config['window_size']) # initial circle location x = 50 y = 50 # random.choice pulls a random value from # a list. If the list had 100 different # color names, then each name would have a # 1 percent change of being chosen. # Unless your name is Austin, then you would # bitch about the effectiveness of he random # implementation and your program would crash # blaming php for its issues :) Long story. # disregard after the 1 percent sentence. bcolor = random.choice(names) fcolor = random.choice(names) # Run until the user asks to quit # Basic game loop running = True while running: screen.fill(colors[bcolor]['rgb']) # Did the user click the window close button? for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.draw.circle(screen, colors[fcolor]['rgb'], (x, y), 50) x += 10 y += 10 pygame.display.flip() # Done! Time to quit. pygame.quit() if __name__=='__main__': #colors = fix_colors("colors.json") #pprint.pprint(colors) main()
ed4ed381cbe55ce33e621a12426d9fb41e3f2981
rugbyprof/4443-2D-PyGame
/Resources/R02/Pygame_Introduction/011_pyglesson.py
1,985
3.734375
4
""" Pygame 011 Description: Fixing our Ball Class Part 2 New Code: None """ # Import and initialize the pygame library import pygame import random import json import pprint import sys def load_colors(infile): with open(infile,'r') as f: data = f.read() colors = json.loads(data) return colors config = { 'title' :'006 Pygame Lesson', 'window_size' : (500,500) } colors = load_colors('colors2.json') class Ball: def __init__(self,screen,color,x,y,r): self.screen = screen self.color = color self.x = x self.y = y self.radius = r self.dx = random.choice([-1,1]) self.dy = random.choice([-1,1]) self.speed = 15 def Draw(self): pygame.draw.circle(self.screen, self.color, (self.x, self.y), self.radius) def Move(self): w, h = pygame.display.get_surface().get_size() self.x += (self.speed * self.dx) self.y += (self.speed * self.dy) if self.x <= 0 or self.x >= w: self.dx *= -1 if self.y <= 0 or self.y >= h: self.dy *= -1 def main(): pygame.init() # sets the window title pygame.display.set_caption(config['title']) # Set up the drawing window screen = pygame.display.set_mode(config['window_size']) # set circle location x = 20 y = 250 # construct the ball b1 = Ball(screen,colors['rebeccapurple']['rgb'],x,y,30) # Run until the user asks to quit # game loop running = True while running: screen.fill(colors['white']['rgb']) # Did the user click the window close button? for event in pygame.event.get(): if event.type == pygame.QUIT: running = False b1.Draw() b1.Move() pygame.display.flip() # Done! Time to quit. pygame.quit() if __name__=='__main__': #colors = fix_colors("colors.json") #pprint.pprint(colors) main()
fea4e23725b61f8dd4024b2c52065870bbba6da1
rugbyprof/4443-2D-PyGame
/Resources/R02/Python_Introduction/PyIntro_05.py
548
4.15625
4
# import sys # import os # PyInto Lesson 05 # Strings # - Functions # - Input from terminal # - Formatted Strings name = "NIKOLA TESLA" quote = "The only mystery in life is: why did Kamikaze pilots wear helmets?" print(name.lower()) print(name.upper()) print(name.capitalize()) print(name.title()) print(name.isalpha()) print(quote.find('Kamikaze')) print(quote.find('Kamikazsdfe')) new_name = input("Please enter a name: ") print(new_name) print(len(quote)) print(f"Hello {new_name}, you owe me 1 million dollars!") print(f"{quote.strip('?')}")
71d354053e21a975844f104a914148533322ad43
rugbyprof/4443-2D-PyGame
/Resources/R02/Python_Introduction/PyIntro_22.py
1,616
3.703125
4
import math import os,sys import json # PyIntro Lesson 22 # Classes Part 3 class Data: @staticmethod def validJson(jdata): try: json_object = json.loads(jdata) return True except ValueError as e: pass return False @staticmethod def readJson(loc_path): if os.path.isfile(loc_path): f = open(loc_path,"r") data = f.read() if Data.validJson(data): jdata = json.loads(data) if jdata: return jdata else: return None return None class Point: def __init__(self,x=0,y=0): self.x = x self.y = y def __str__(self): return f"(x:{self.x},y:{self.y})" def __add__(self,other): return Point(self.x + other.x , self.y + other.y) def __sub__(self,other): return Point(self.x - other.x , self.y - other.y) def distance(self,other): return math.sqrt(((self.x-other.x)**2)+((self.y-other.y)**2)) def get(self): return self.x, self.y def set(self,x,y=None): if not y: if type(x) == list or type(x) == tuple: self.x = x[0] self.y = x[1] else: self.x = x self.y = y if __name__=='__main__': data_folder = "./data/" file_name = 'player2Data.json' p1 = Point(6,8) print(p1) x,y = p1.get() print(x,y) p1.set(12,12) print(p1) p1.set([78,45]) print(p1) p1.set((99,99)) print(p1)
bb50a982bb5f4da46a09b714c1d37a52d43c778f
rugbyprof/4443-2D-PyGame
/Resources/R02/Pygame_Introduction/005_pyglesson.py
1,497
4.09375
4
""" Pygame 005 Description: Simple config starter And drawing a ball New Code: - pygame.draw.circle(screen, (red, green, blue), (250, 250), 75) """ config = { 'title' :'005 Pygame Lesson' } colors = { 'magenta':(255, 0, 255, 100), 'cyan':(0, 255, 255, 100), 'background':(0,130,200,100) } # Import and initialize the pygame library import pygame import random def main(): pygame.init() # sets the window title pygame.display.set_caption(config['title']) # Set up the drawing window screen = pygame.display.set_mode([500, 500]) # Run until the user asks to quit # game loop running = True while running: screen.fill(colors['background']) # Did the user click the window close button? for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Generate three random integers and assign between 0-255 # them to three vars red = int(random.random() * 255) green = int(random.random() * 255) blue = int(random.random() * 255) # Draw a circle on the screen using the random variables # This results in crazy color changes since the color vars # are updated in the game loop. pygame.draw.circle(screen, (red, green, blue), (250, 250), 75) # refresh display pygame.display.flip() # Done! Time to quit. pygame.quit() if __name__=='__main__': main()
e054d55058159c95b35621f682a3a2bb0594dbd8
ehbjarnason/motion
/motion.py
21,674
3.828125
4
import numpy as np import matplotlib.pyplot as plt class MotionProfile: """An abstract class, which other motion profiles should inherit and implement.""" def __init__(self): self.n = None # Number of data points self.dist = None # Total distance self.time = None # Time duration self.v_max = None # Max velocity self.accel = None # (Max) acceleration self.v_avg = None # dist/time # Arrays self.t = None # Time array of size n + 1 self.pos = None # Position array of size n + 1 self.vel = None # Velocity array of size n + 1 self.acc = None # Acceleration array of size n + 1 self.jerk = None # Jerk array of size n + 1 self.d = {'Vmax': 0, 'Vavg': 0, 'A': 0, 'time': 0, 'dist': 0, 't': None, # time array 'j': None, # jerk array 'a': None, # acceleration array 'v': None, # velocity array 'p': None} # position array def calc(self, n): """Create the t, p, v, a and j arrays with sizes n + 1.""" return self.d def trapezoidal(dist, time, accel, n=100): """Returns a trapezoidal motion profile; 2nd order polynomial dist -- the displacement distance (movement length) time -- the time duration of the displacement, cannot be zero. accel -- the acceleration and deceleration parts of the trapezoid n -- the number of ponts to return If the 'accel' is too small relative to 'time' and 'dist', it will be scaled down to form a triangular motion profile. The max speed of a trapezoid is always lower than on a triangular motion. """ accel_triangular = dist / (time / 2)**2 print('accel_triangular: ', str(accel_triangular)) if accel > accel_triangular: # known: x, t, a # unknown: t_a, t_c # t = t_a + t_c + t_a = 2 t_a + t_c # t_c = t - 2 t_a # The distance travelled is the area under the curve: # x = v_max * (t_a + t_c) # a = v_max / t_a # v_max = a t_a # x = a t_a (t_a + (t - 2 t_a)) # x = a t_a (t - t_a) # x = (a t) t_a - (a) t_a^2 # (-a) t_a^2 + (a t) t_a - x = 0 # (a) t_a^2 + (-a t) t_a + x = 0 # [a x^2 + b x + c = 0 => x = (-b +/- sqrt(b^2 - 4 a c)) / 2 a] # # t_a = (a t +/- sqrt((a t)^2 - 4 a x)) / 2a s1 = accel * time s2 = 4 * accel * dist if s1**2 > s2: # The square root is not negative. # t_a1 = (accel * time + np.sqrt((accel * time)**2 - 4 * accel * dist)) / (2 * accel) # t_a2 = (accel * time - np.sqrt((accel * time)**2 - 4 * accel * dist)) / (2 * accel) # print(time, dist, accel, t_a1, t_a2) t_a = (s1 - np.sqrt(s1**2 - s2)) / (2 * accel) t_c = time - 2 * t_a # print('time: ', time, ', t_a: ', t_a, ', t_c: ', t_c) d = {'Vmax': accel * t_a, 'Vavg': dist / time, 'A': accel, 'time': time, 'dist': dist, 't': np.arange(n + 1) * time / n, 'jerk': np.zeros(n + 1), 'acc': np.zeros(n + 1), 'vel': np.zeros(n + 1), 'pos': np.zeros(n + 1)} for i, t in zip(range(n + 1), d['t']): if 0 <= t < t_a: d['pos'][i] = 1 / 2 * d['A'] * t ** 2 d['vel'][i] = d['A'] * t d['acc'][i] = d['A'] elif t_a <= t < t_a + t_c: d['pos'][i] = d['Vmax'] * t - (1 / 2 * d['A'] * t_a ** 2) d['vel'][i] = d['Vmax'] d['acc'][i] = 0 elif t_a + t_c <= t <= time: d['pos'][i] = d['Vmax'] * t - (1 / 2 * d['A'] * t_a ** 2)\ - 1 / 2 * d['A'] * (t - (t_a + t_c)) ** 2 d['vel'][i] = d['Vmax'] - (t - (t_a + t_c)) * d['A'] d['acc'][i] = -d['A'] else: d = triangular(dist, time, n) print('(a t)^2 - 4 a x = ', str(s1**2), ' - ', str(s2)) print('distance, time, acceleration combination is not possible') else: d = triangular(dist, time, n) print('The acceleration is to small: triangular accel = ', str(d['A']), ', accel = ', str(accel)) print('returning a triangular motion profile with the specified distance and time.') return d def triangular(dist, time=None, vel=None, accel=None, n=100): """Returns a triangular motion profile, 2nd order polynomial dist -- the displacement distance (movement length) time -- the time duration of the displacement, cannot be zero. n -- the number of ponts to return one of three: time, vel or accel must be non-None and two of three must be None. """ if not time: if vel and not accel: time = 2 * dist / vel elif accel and not vel: time = 2 * np.sqrt(dist / accel) else: return None d = {'Vmax': dist / (time / 2), 'Vavg': dist / time, 'A': 0, 'time': time, 'dist': dist, 't': np.arange(n+1) * time / n, 'jerk': np.zeros(n+1), 'acc': np.zeros(n+1), 'vel': np.zeros(n+1), 'pos': np.zeros(n+1)} d['A'] = d['Vmax'] / (time / 2) for i, t in zip(range(n+1), d['t']): if 0 <= t < time / 2: d['pos'][i] = 1 / 2 * d['A'] * t ** 2 d['vel'][i] = d['A'] * t d['acc'][i] = d['A'] elif time / 2 <= t <= time: d['pos'][i] = -dist / 2 + d['Vmax'] * t - 1 / 2 * d['A'] * (t - time / 2) ** 2 d['vel'][i] = d['Vmax'] - (t - time / 2) * d['A'] d['acc'][i] = -d['A'] return d class Trapezoidal(MotionProfile): def __init__(self, dist, time=None, v_max=None, accel=None, n=None): """Two of time, v_max or accel must be given. Necessary argument combinations: accel, time accel, v_max time, v_max """ MotionProfile.__init__(self) self.dist = dist self.n = n self.is_triangular = False self.is_trapezoidal = False self.t_a = None # The acceleration and deceleration time. self.t_c = None # The time at constant speed. self.tri = None if dist > 0: if accel: if time and not v_max: self.time = time self.accel = accel s1 = accel * time s2 = 4 * accel * dist accel_triangular = dist / (time / 2) ** 2 if (s1**2 < s2) or (accel < accel_triangular): self.t_c = 0 self.tri = Triangular(dist, time, accel, n) if n: self.d = self.tri.calc(n) else: self.is_trapezoidal = True self.t_a = s1 - np.sqrt(s1**2 - s2) self.t_c = self.time - 2 * self.t_a self.v_max = accel * self.t_a elif v_max and not time: self.v_max = v_max self.accel = accel self.t_a = v_max / accel self.t_c = dist / v_max - v_max / accel if self.t_c <= 0: # Keep the acceleration fixed and lower the speed self.v_max = np.sqrt(dist * accel) self.t_a = self.v_max / accel self.t_c = 0 self.time = 2 * self.t_a self.tri = Triangular(dist, v_max=self.v_max, accel=accel) if n: self.d = self.tri.calc(n) else: self.time = 2 * self.t_a + self.t_c self.is_trapezoidal = True elif time and v_max: self.time = time self.v_max = v_max self.t_a = time / 3 self.t_c = time / 3 self.accel = v_max / self.t_a self.is_trapezoidal = True if self.is_triangular: self.t_c = 0 self.tri = Triangular(dist, time, v_max, accel, n) if n: self.d = self.tri.calc(n) elif self.is_trapezoidal: self.v_avg = self.dist / self.time self.d['Vmax'] = self.v_max self.d['Vavg'] = self.v_avg self.d['A'] = self.accel self.d['time'] = self.time self.d['dist'] = self.dist if n: # Calculate if the number of points n, are specified. self.d = self.calc(self.n) def calc(self, n): self.n = n # print(self.time) if self.tri: return self.tri.calc(n) else: self.d['t'] = np.arange(n + 1) * self.time / n self.d['j'] = np.zeros(n + 1) self.d['a'] = np.zeros(n + 1) self.d['v'] = np.zeros(n + 1) self.d['p'] = np.zeros(n + 1) for i, t in zip(range(n + 1), self.d['t']): if 0 <= t < self.t_a: self.d['p'][i] = 1 / 2 * self.d['A'] * t ** 2 self.d['v'][i] = self.d['A'] * t self.d['a'][i] = self.d['A'] elif self.t_a <= t < self.t_a + self.t_c: self.d['p'][i] = self.d['Vmax'] * t - (1 / 2 * self.d['A'] * self.t_a ** 2) self.d['v'][i] = self.d['Vmax'] self.d['a'][i] = 0 elif self.t_a + self.t_c <= t: self.d['p'][i] = self.d['Vmax'] * t - (1 / 2 * self.d['A'] * self.t_a ** 2) \ - 1 / 2 * self.d['A'] * (t - (self.t_a + self.t_c)) ** 2 self.d['v'][i] = self.d['Vmax'] - (t - (self.t_a + self.t_c)) * self.d['A'] self.d['a'][i] = -self.d['A'] return self.d class Triangular(MotionProfile): def __init__(self, dist, time=None, v_max=None, accel=None, n=None): """One of time, v_max or accel must be given.""" MotionProfile.__init__(self) self.dist = dist self.n = n if not time: if v_max and not accel: # Calc time and acceleration self.v_max = v_max self.time = 2 * dist / v_max self.accel = self.v_max / (self.time / 2) elif accel and not v_max: # Calc time and max speed self.accel = accel self.time = 2 * np.sqrt(dist / accel) self.v_max = self.dist / (self.time / 2) elif v_max and accel: # Calc time self.v_max = v_max self.accel = accel self.time = 2 * v_max / accel else: # Calc max speed and acceleration self.time = time self.v_max = self.dist / (self.time / 2) self.accel = self.v_max / (self.time / 2) self.v_avg = self.dist / self.time self.d['Vmax'] = self.v_max self.d['Vavg'] = self.v_avg self.d['A'] = self.accel self.d['time'] = self.time self.d['dist'] = self.dist # Calculate if the number of points n, are specified if n: self.d = self.calc(self.n) def calc(self, n): self.n = n self.d['t'] = np.arange(n + 1) * self.time / n self.d['j'] = np.zeros(n + 1) self.d['a'] = np.zeros(n + 1) self.d['v'] = np.zeros(n + 1) self.d['p'] = np.zeros(n + 1) for i, t in zip(np.arange(n + 1), self.d['t']): if 0 <= t < self.time / 2: self.d['p'][i] = 1 / 2 * self.d['A'] * t ** 2 self.d['v'][i] = self.d['A'] * t self.d['a'][i] = self.d['A'] elif self.time / 2 <= t: self.d['p'][i] = -self.dist / 2 + self.d['Vmax'] * t - 1 / 2 * self.d['A'] * (t - self.time / 2) ** 2 self.d['v'][i] = self.d['Vmax'] - (t - self.time / 2) * self.d['A'] self.d['a'][i] = -self.d['A'] self.t = self.d['t'] self.pos = self.d['p'] self.vel = self.d['v'] self.accel = self.d['a'] self.jerk = self.d['j'] return self.d def scurve(dist, time, n=100): """Returns S-curve motion profile, 3rd order polynomial. dist -- the displacement distance (movement length) time -- the time duration of the displacement, cannot be zero. n -- the number of ponts to return """ d = { 'Vs': dist / (time / 2), 'A': 0, 'As': 0, 'J': 0, 't': np.arange(n+1) * time / n, 'jerk': np.zeros(n+1), 'acc': np.zeros(n+1), 'vel': np.zeros(n+1), 'pos': np.zeros(n+1), 'trivel': np.zeros(n+1) } d['A'] = d['Vs'] / (time / 2) d['As'] = 2 * d['A'] d['J'] = d['Vs'] / (time / 4) ** 2 j = d['J'] v = d['Vs'] s = d['As'] a = d['A'] for i, t in zip(range(n+1), d['t']): if 0 <= t < time / 4: d['jerk'][i] = j d['acc'][i] = j * t d['vel'][i] = 1 / 2 * j * t ** 2 d['pos'][i] = 1 / 6 * j * t ** 3 d['trivel'][i] = a * t elif time / 4 <= t < time / 2: d['jerk'][i] = -j d['acc'][i] = s - j * (t - time / 4) d['vel'][i] = v / 2 + s * (t - time / 4) - 1 / 2 * j * (t - time / 4) ** 2 d['pos'][i] = 1 / 6 * j * (time / 4) ** 3 + v / 2 * (t - time / 4) + 1 / 2 * s * ( t - time / 4) ** 2 - 1 / 6 * j * (t - time / 4) ** 3 d['trivel'][i] = a * t elif time / 2 <= t < 3 / 4 * time: d['jerk'][i] = -j d['acc'][i] = -j * (t - time / 2) d['vel'][i] = v - 1 / 2 * j * (t - time / 2) ** 2 d['pos'][i] = v / 2 * time / 4 + s / 2 * (time / 4) ** 2 + v * ( t - time / 2) - 1 / 6 * j * (t - time / 2) ** 3 d['trivel'][i] = v - (t - time / 2) * a elif 3 / 4 * time <= t <= time: d['jerk'][i] = j d['acc'][i] = -s + j * (t - 3 / 4 * time) d['vel'][i] = v / 2 - s * (t - 3 / 4 * time) + 1 / 2 * j * (t - 3 / 4 * time) ** 2 d['pos'][i] = 3 / 2 * v * time / 4 + s / 2 * (time / 4) ** 2 - j / 6 * ( time / 4) ** 3 + v / 2 * (t - 3 / 4 * time) - 1 / 2 * s * ( t - 3 / 4 * time) ** 2 + 1 / 6 * j * (t - 3 / 4 * time) ** 3 d['trivel'][i] = v - (t - time / 2) * a return d def const_speed_profile(time, numpoints, speed, filename='constspeed'): # time = 0.250 # s # numpoints = 2500 # speed = 250 # mm/s t = np.arange(numpoints) * time / numpoints pos = speed * t save_datapoints(t, pos, filename + '.txt') def const_move(velocity, time, n=100): """returns positon vs time""" d = {} d['t'] = np.arange(n) * time / n d['p'] = velocity * d['t'] return d def replace_range(x, y, i0): """ Replace part of x with y, beginning at position i0. x -- array y -- array i0 -- initial value The values in x at position i0 and above, up to the length of y, will get the values of y. The values in x at position i0+len(y), will all get the value of y[-1]. Example: x = [1 2 3 4 5 6 7 8 9] y = [a b c] i0 = 3 Returns: x = [1 2 3 a b c c c c] """ # For loop example: # x = [1 2 3 4 5 6 7 8 9] # y = [a b c] # i0 = 3 # Results in: x = [1 2 3 a b c 7 8 9] for i, j in zip(range(i0, i0 + len(y)), range(len(y))): x[i] = y[j] # The iterator i, has reached the last position of the replaced values. # The upper part of x, above the replaced values from y, is replaced with # the last value of y. Example: # Returned result: x = [1 2 3 a b c c c c]. # xout = np.concatenate((x[0:i], y[-1] * np.ones(len(x) - i))) # plt.plot(xout) # plt.show() # plt.clf() return np.concatenate((x[0:i], y[-1] * np.ones(len(x) - i))) def add_scurve_segment(p, t0, time, displace, t, neg=False): """ Returns a position array p, with an added S-curve array. p -- Position array t0 -- The moment in time to start adding the S-curve to p. time -- The time it takes to displace. displace -- A value giving the displacement range t -- Time array neg -- Bool, Return a negative S-curve or not. The arrays, p and t have the same length. The positon values in p take place at time values in t, at index i in t and p. """ # The number of points, the S-curve should return n = int(time * len(p) / (np.max(t) + t[1])) d = scurve(displace, time, n) if neg: d['p'] = displace - d['p'] # The index of the start time in the t time array. i0 = np.where(t >= t0)[0][0] return replace_range(p, d['p'], i0) def ind(expr): """Returns the first index in an array, where the expression is true""" return np.where(expr)[0][0] def save_datapoints(time, pos, filename): """Creates a file containing two columns; time and position""" with open(filename, 'w') as f: for t, p in zip(time, pos): f.write(str(t) + ',' + str(p) + '\n') def plot_motion_profile(d): """Plots pos, vel, acc and jerk. The argument is a tuple of dictionaries. """ f, ax = plt.subplots(2, 2) # print(d) ax[0, 0].set_title('Pos') ax[0, 1].set_title('Vel') ax[1, 0].set_title('Acc') ax[1, 1].set_title('Jerk') if isinstance(d, tuple): j = 1 for i in d: if i is not None: ax[0, 0].plot(i['t'], i['p'], label=str(j)) ax[0, 1].plot(i['t'], i['v']) ax[1, 0].plot(i['t'], i['a']) if 'jerk' in i: ax[1, 1].plot(i['t'], i['j']) j += 1 ax[0, 0].legend() else: if d is not None: ax[0, 0].plot(d['t'], d['p']) ax[0, 1].plot(d['t'], d['v']) ax[1, 0].plot(d['t'], d['a']) if 'j' in d: ax[1, 1].plot(d['t'], d['j']) plt.show() def shift(x, x0, s=0): """Shift the first elements in the array x, to position x0, x0 <= len(x). Example: x0 = 4 x = a b c d e f g h i j 0 1 2 3 4 5 6 7 8 9 y = s s s s a b c d e f """ # y = s * np.ones(len(x)) # # i = x0 # j = 0 # while i < len(x): # y[i] = x[j] # i += 1 # j += 1 # # return y return np.concatenate((s * np.ones(x0), x[:len(x) - x0])) if __name__ == '__main__': # s = scurve(0.090, 0.1) # print('scurve accel:', d['acc'].max()) # plt.plot(d['t'], d['jerk']) # plt.plot(d['t'], d['acc']) # plt.plot(d['t'], d['vel']) # plt.plot(d['t'], d['pos']) # plt.plot(d['t'], d['trivel']) # d = const_move(0, 0.1) # plt.plot(d['t'], d['p']) # z = trapezoidal(0.090, 0.1, 40) # plot_motion_profile((z,)) # d = triangular(0.090, 0.1) # print('triangular accel:', d['acc'].max()) # plot_motion_profile((d,)) # plot_motion_profile((s, z, d)) # const_speed_profiles(time=0.250, numpoints=2500, speed=400, # filename='constspeed400') # plt.show() # print(data) # shift([1, 2, 3, 4, 5, 6, 7, 8, 9], 4) # d1 = triangular(10, 2*0.0155+0.0528, n=1000) # d2 = trapezoidal(10, 2*0.0155+0.0528, 10000, n=1000) # # Distance and acceleretaion are known: x, a. Time is unknown: t # # x = v (t/2), a = v / (t/2) => x = a (t/2) (t/2) # # => t = 2 sqrt(x/a) # d3 = triangular(10, 2 * np.sqrt(10 / 10000), n=1000) # # Distance and velocity is known: x, v. Time is unknown: t # # v = x / t => t = x / v # d4 = triangular(10, 2 * 10 / 148, n=1000) # tri5 = Triangular(10, v_max=148) # d5 = tri5.calc(1000) # # print('d1 vavg', d1['Vavg']) # print('d2 vavg', d2['Vavg']) # print('d3 vavg', d3['Vavg']) # print('d4 vavg', d4['Vavg']) # print('d5 vavg', d5['Vavg']) # # plot_motion_profile((d1, d2, d3, d4, d5)) # Trapezoidal 1: accel and time # d = [] # for i in range(1000, 16000, 2000): # tra = Trapezoidal(10, accel=i, v_max=200, n=1000) # d.append(tra.d) # plot_motion_profile(tuple(d)) # Trapezoidal 2: accel and v_max # d = [] # for i in range(1000, 50000, 1000): # tra = Trapezoidal(10, accel=i, v_max=200, n=1000) # d.append(tra.d) # plot_motion_profile(tuple(d)) # Trapezoidal 3: time and v_max d = [] # tra = Trapezoidal(10, time=0.05, v_max=200, n=1000) # d.append(tra.d) # tra = Trapezoidal(10, time=0.05, v_max=100, n=1000) # d.append(tra.d) # tra = Trapezoidal(10, time=0.05, v_max=100, n=1000) # tra.d['p'] = -tra.d['p'] # tra.d['v'] = -tra.d['v'] # tra.d['a'] = -tra.d['a'] # d.append(tra.d) tra = Trapezoidal(5, accel=10000, v_max=143, n=3000) d.append(tra.d) plot_motion_profile(tuple(d))
69c2148bb3dbf711184fa5f4c2fee5dec138add4
zrj1236/bnlearn
/bnlearn/inference.py
3,414
3.5625
4
"""Techniques for inference. Description ----------- Inference is same as asking conditional probability questions to the models. """ # ------------------------------------ # Name : inference.py # Author : E.Taskesen # Contact : erdogant@gmail.com # Licence : See licences # ------------------------------------ # %% Libraries from pgmpy.inference import VariableElimination import bnlearn import numpy as np # %% Exact inference using Variable Elimination def fit(model, variables=None, evidence=None, to_df=True, verbose=3): """Inference using using Variable Elimination. Parameters ---------- model : dict Contains model. variables : List, optional For exact inference, P(variables | evidence). The default is None. * ['Name_of_node_1'] * ['Name_of_node_1', 'Name_of_node_2'] evidence : dict, optional For exact inference, P(variables | evidence). The default is None. * {'Rain':1} * {'Rain':1, 'Sprinkler':0, 'Cloudy':1} to_df : Bool, (default is True) The output is converted to dataframe output. Note that this heavily impacts the speed. verbose : int, optional Print progress to screen. The default is 3. 0: None, 1: ERROR, 2: WARN, 3: INFO (default), 4: DEBUG, 5: TRACE Returns ------- query inference object. Examples -------- >>> import bnlearn as bn >>> >>> # Load example data >>> model = bn.import_DAG('sprinkler') >>> bn.plot(model) >>> >>> # Do the inference >>> query = bn.inference.fit(model, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1}) >>> print(query) >>> query.df >>> >>> query = bn.inference.fit(model, variables=['Wet_Grass','Rain'], evidence={'Sprinkler':1}) >>> print(query) >>> query.df >>> """ if not isinstance(model, dict): raise Exception('[bnlearn] >Error: Input requires a object that contains the key: model.') adjmat = model['adjmat'] if not np.all(np.isin(variables, adjmat.columns)): raise Exception('[bnlearn] >Error: [variables] should match names in the model (Case sensitive!)') if not np.all(np.isin([*evidence.keys()], adjmat.columns)): raise Exception('[bnlearn] >Error: [evidence] should match names in the model (Case sensitive!)') if verbose>=3: print('[bnlearn] >Variable Elimination..') # Extract model if isinstance(model, dict): model = model['model'] # Check BayesianModel if 'BayesianModel' not in str(type(model)): if verbose>=1: print('[bnlearn] >Warning: Inference requires BayesianModel. hint: try: parameter_learning.fit(DAG, df, methodtype="bayes") <return>') return None # Convert to BayesianModel if 'BayesianModel' not in str(type(model)): model = bnlearn.to_bayesianmodel(adjmat, verbose=verbose) try: model_infer = VariableElimination(model) except: raise Exception('[bnlearn] >Error: Input model does not contain learned CPDs. hint: did you run parameter_learning.fit?') # Computing the probability P(class | evidence) query = model_infer.query(variables=variables, evidence=evidence, show_progress=(verbose>0)) # Store also in dataframe query.df = bnlearn.query2df(query) if to_df else None if verbose>=3: print(query) # Return return(query)
0f8c07d4970004e3d3c0236a88c9d759f9cfcb78
rtl019/MLpractice
/regression_analysis/CSV_Reader.py
286
3.53125
4
import csv def Reader(fileName): file=open(fileName) dicr=csv.DictReader(file) for row in dicr: size=[] size.append(row['sq__ft']) price=[] price.append(row['price']) return price,size
5b6b94900cf1b9de14b11d743d1e553c326ad6bd
ulankford/python
/MIT_6.00.1x_EDX_Code/python.py
212
3.71875
4
name = raw_input('What is your name?') if name == 'bob': print 'Why hello,', name elif name == 'ultan': print name ,'you are fired' else: print 'You are not allowed to access this system.'
edb7bb5311d88228d4dcb8bf107a1dc6781af8b7
weilingu/Brand-Logo-Feature-Analysis
/CNN_Letter_Recog_Model.py
3,930
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 17 13:33:52 2019 @author: emily.gu """ from mnist import MNIST import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D from keras.layers.advanced_activations import LeakyReLU from keras.utils import to_categorical from sklearn.model_selection import train_test_split ''' This script trains a Convoluted Neural Network Model - The model uses emnist data that contains letters - The model is based on a datacamp CNN tutorial: https://www.datacamp.com/community/tutorials/convolutional-neural-networks-python - The accuracy rate based on test dataset is about 94% ''' # create path to the emnist dataset: emnist_data_path="[path to mnist dataset]" # create path to save the model architecture cnn_model_path='[path to save the model]' emnist_data = MNIST(path=emnist_data_path+"train", return_type='numpy') emnist_data.select_emnist('letters') x_train, y_train = emnist_data.load_training() emnist_data = MNIST(path=emnist_data_path+"test", return_type='numpy') emnist_data.select_emnist('letters') x_test, y_test = emnist_data.load_testing() train_X=x_train.reshape(-1,28,28,1) test_X=x_test.reshape(-1,28,28,1) train_X=train_X.astype('float32') train_X=train_X/255.0 test_X=test_X.astype('float32') test_X=test_X/255.0 # convert the y labels to categorical data y_train_softmax=to_categorical(y_train) y_test_softmax=to_categorical(y_test) # Split the training dataset into train and validation datasets train_X,valid_X, train_label, valid_label = train_test_split(train_X,y_train_softmax, test_size=0.2, random_state=13) # train the CNN batch_sizes=128 # can change the batch_size to 256 epoch=20 num_classes=27 letter_reg_model=Sequential() letter_reg_model.add(Conv2D(32,kernel_size=(3,3),activation='linear',input_shape=(28,28,1),padding='same')) letter_reg_model.add(LeakyReLU(alpha=0.1)) letter_reg_model.add(MaxPooling2D((2,2),padding='same')) letter_reg_model.add(Dropout(0.25)) letter_reg_model.add(Conv2D(64,kernel_size=(3,3),activation='linear',padding='same')) letter_reg_model.add(LeakyReLU(alpha=0.1)) letter_reg_model.add(MaxPooling2D(pool_size=(2,2),padding='same')) letter_reg_model.add(Dropout(0.25)) letter_reg_model.add(Conv2D(128,kernel_size=(3,3),activation='linear',padding='same')) letter_reg_model.add(LeakyReLU(alpha=0.1)) letter_reg_model.add(MaxPooling2D(pool_size=(2,2),padding='same')) letter_reg_model.add(Dropout(0.4)) letter_reg_model.add(Flatten()) letter_reg_model.add(Dense(128,activation='linear')) letter_reg_model.add(LeakyReLU(alpha=0.1)) letter_reg_model.add(Dropout(0.3)) letter_reg_model.add(Dense(num_classes, activation='softmax')) letter_reg_model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adam(),metrics=['accuracy']) letter_reg_model.summary() # Train the model: letter_reg_model_train=letter_reg_model.fit(train_X,train_label,batch_size=batch_sizes, epochs=epoch,verbose=1,validation_data=(valid_X,valid_label)) #evaluate the model test_eval = letter_reg_model.evaluate(test_X, y_test_softmax, verbose=1) print('Test loss:', test_eval[0]) print('Test accuracy:', test_eval[1]) # Save the model architecture letter_reg_model.save(cnn_model_path+"letter_recog_model.h5py") letter_reg_model.save_weights(cnn_model_path+"letter_recog_model.h5") with open(cnn_model_path+"CNN_letter_model.json", 'w') as f: f.write(letter_reg_model.to_json()) ''' # letter-number lookup letter = { 0: 'non', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'} '''
b006e4dc55b7188a241efcf979b94328bbc53a42
mingyuea/pythonLeetcodeMed
/maxNumAsRoot.py
1,992
3.59375
4
''' Given a list of integers with no duplicates, find the max and set it as the root of a tree The left subtree is then a tree built from the left partition of the list (list[0:max]) The right subtree is a tree build from the right partition of the remaining list (list[max+1:]) Return the root node ''' class TreeNode(): def __init__(self, num): self.val = num self.left = None self.right = None class Solution: def constructMaxRoot(self, nums): """ :type nums: List[int] :rtype: TreeNode """ def maxInd(arr): currMax = arr[0] maxInd = 0 leftArr = None rightArr = None for ind, val in enumerate(arr): if val > currMax: currMax = val maxInd = ind if maxInd != 0: leftArr = arr[0:maxInd] if maxInd != len(arr) - 1: rightArr = arr[maxInd + 1:] return (currMax, leftArr, rightArr) def buildTree(node, val): if val < node.val: if node.left: return buildTree(node.left, val) else: node.left = TreeNode(val) return else: if node.right: return buildTree(node.right, val) else: node.right = TreeNode(val) return maxRoot, leftList, rightList = maxInd(nums) self.root = TreeNode(maxRoot) if leftList: leftList.sort() self.root.left = TreeNode(leftList.pop(len(leftList) - 1)) if rightList: rightList.sort() self.root.right = TreeNode(rightList.pop(len(rightList) - 1)) while leftList: newVal = leftList.pop(len(leftList) - 1) buildTree(self.root.left, newVal) while rightList: newVal = rightList.pop(len(rightList) - 1) buildTree(self.root.right, newVal) return self.root newS = Solution() print(newS.constructMaxRoot([3,2,1,6,0,5]).left.left.val)
429289861e6299df2f7cb5b197c9c7d813a7e4f9
nidhinp/Anand-Chapter2
/problem30.py
177
3.59375
4
""" Write a python function parse_csv to parse csv files. """ def parse_csv(file): return [line.split()[0].split(',') for line in open(file)] print parse_csv('a.csv')
7b69e5ceb600a18a3f9d9c8bae52ec41ed24f145
nidhinp/Anand-Chapter2
/problem3.py
240
3.640625
4
""" Sum function that works for a list of string as well """ def my_sum(x): sum = x[0] for i in x: if i == x[0]: continue else: sum += i return sum print my_sum([1, 2, 3, 4]) print my_sum(['c', 'java', 'python'])
79d70dca2e86013310ae0691b9a8e731d26e2e75
nidhinp/Anand-Chapter2
/problem36.py
672
4.21875
4
""" Write a program to find anagrams in a given list of words. Two words are called anagrams if one word can be formed by rearranging letters to another. For example 'eat', 'ate' and 'tea' are anagrams. """ def sorted_characters_of_word(word): b = sorted(word) c = '' for character in b: c += character return c def anagram(list_of_words): a = {} for word in list_of_words: sorted_word = sorted_characters_of_word(word) if sorted_word not in a: d = [] d.append(word) a[sorted_word] = d else: d = a[sorted_word] d.append(word) a.update({sorted_word:d}) print a.values() anagram(['eat', 'ate', 'done', 'tea', 'soup', 'node'])
a1b103fb6e85e3549090449e71ab3908a46b2e9c
nidhinp/Anand-Chapter2
/problem29.py
371
4.25
4
""" Write a function array to create an 2-dimensional array. The function should take both dimensions as arguments. Value of element can be initialized to None: """ def array(oneD, twoD): return [[None for x in range(twoD)] for x in range(oneD)] a = array(2, 3) print 'None initialized array' print a a[0][0] = 5 print 'Modified array' print a
fd5a09d770cd5f632c2897dab06b4b9e7e5b6af7
mo/project-euler
/python/problem2.py
401
3.921875
4
def fibonacci(n): if n == 1 or n == 0: return 1 return fibonacci(n-1) + fibonacci(n-2) special_sum = 0 i = 0 ith_fibonacci_number = fibonacci(i); while ith_fibonacci_number < 1000000: if ith_fibonacci_number % 2 == 0: special_sum += ith_fibonacci_number i += 1 ith_fibonacci_number = fibonacci(i); print "special_sum ==", special_sum
2044f47081263d56813e4a2068a167c339c23ae2
MarufurRahman/URI-Beginner-Solution
/Solutions/URI-1011.py
233
3.625
4
# URI Problem Link: https://www.urionlinejudge.com.br/judge/en/problems/view/1011 # Programmed by Marufur Rahman. radius = int(input()) pi = 3.14159 volume = float(4.0 * pi * (radius* radius * radius) / 3) print("VOLUME = %0.3f" %volume)
4cbcb6d66ee4b0712d064c9ad4053456e515b14b
SandipanKhanra/Sentiment-Analysis
/tweet.py
2,539
4.25
4
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] #This function is used to strip down the unnecessary characters def strip_punctuation(s): for i in s: if i in punctuation_chars: s=s.replace(i,"") return s # lists of words to use #As part of the project this hypothetical .txt file was given positive_words = [] with open("positive_words.txt") as pos_f: for lin in pos_f: if lin[0] != ';' and lin[0] != '\n': positive_words.append(lin.strip()) #This function returns number of positive words in the tweet def get_pos(s): count=0 s=s.lower() x=[] x=s.split() for i in x: i=strip_punctuation(i) if i in positive_words: count+=1 return count #As part of the project this hypothetical .txt file was given negative_words = [] with open("negative_words.txt") as pos_f: for lin in pos_f: if lin[0] != ';' and lin[0] != '\n': negative_words.append(lin.strip()) #This function returns number of negitive words in the tweet def get_neg(s): count=0 s=s.lower() x=[] x=s.split() for i in x: i=strip_punctuation(i) if i in negative_words: count+=1 return count #This hypothetical .csv file containing some fake tweets was given for analysi filedName = None file = open("project_twitter_data.csv") lines = file.readlines() fieldName = lines[0].strip().split(',') #print(fieldName) '''here we are iterating over each line, considering only the tweet then processing it with the previous functions storing positive word count, negative word count, net score(how much positiive or negative) ''' ans = [] for line in lines[1:]: tweet= line.strip().split(',') tempTweet = strip_punctuation(tweet[0]) posCount = get_pos(tempTweet) negCount = get_neg(tempTweet) net = posCount - negCount #Making a tuple containing Number of retweets,number of replies,posCount,negCount,Net score t = (int(tweet[1]),int(tweet[2]),posCount,negCount,net) ans.append(t) #print(ans[4]) #Making the header of the new csv file outputHeader = "{},{},{},{},{}".format('Number of Retweets','Number of Replies', 'Positive Score','Negative Score','Net Score') #writing data in the new csv file output = open('resulting_data.csv','w') output.write(outputHeader) output.write('\n') for i in ans: raw = '{},{},{},{},{}'.format(i[0],i[1],i[2],i[3],i[4]) output.write(raw) output.write('\n')
d48f24d89a3c5cba1d45022da76173afc90843e7
CaptClox/py-promedio
/Clases-python/ejemplo2.py
308
3.90625
4
#ejemplificaar uso de funcion MAP palabras = ["hola","juan","curso","programacion","universidad"] #tarea: contar cantidad de caracteres de cada palabra """ conteo_cars = [] for p in palabras: cnt_cars = len(p) conteo_cars.append(cnt_cars) """ conteo_cars = list(map(len,palabras)) print(conteo_cars)
7fc0742a90d95abd67ac4ce3669285cd345e3410
CNchence/Python_learning
/hello_world/hello_world/hello_world/hello_world.py
85
3.90625
4
x=[3,2,6,5,1,2,5,4,8,7,6] y=x[:] x.sort(); print(x); y.sort(reverse = True); print(y)
5f1b71da8c2e15598cbcceb65c1b0869728f2c2c
tvdstorm/exercises-in-programming-style
/02-go-forth/tf-02.py
3,630
4.03125
4
#!/usr/bin/env python import sys, re, operator, string # # The all-important data stack # stack = [] # # The new "words" of our program # def read_file(): """ Takes a path to a file and returns the entire contents of the file as a string. Path to file expected to be on the stack """ path_to_file = stack.pop() f = open(path_to_file) # Push the result onto the stack stack.append([f.read()]) f.close() def filter_chars(): """ Takes a string and returns a copy with all nonalphanumeric chars replaced by white space. The data is assumed to be on the stack. """ str_data = stack.pop() # This is not in style. RE is too high-level, but using it # for doing this fast and short. stack.append(re.compile('[\W_]+')) pattern = stack.pop() # Push the result onto the stack stack.append([pattern.sub(' ', str_data[0]).lower()]) def scan(): """ Takes a string and scans for words, returning a list of words. The data is assumed to be on the stack. """ str_data = stack.pop() # Push the result onto the stack # Again, split() is too high-level for this style, but using it # for doing this fast and short. Left as exercise. stack.append(str_data[0].split()) def remove_stop_words(): """ Takes a list of words and returns a copy with all stop words removed. The data is assumed to be on the stack. """ word_list = stack.pop() f = open('../stop_words.txt') stack.append([f.read().split(',')]) f.close() # add single-letter words stack[0][0].extend(list(string.ascii_lowercase)) stop_words = stack.pop()[0] # Again, this is too high-level for this style, but using it # for doing this fast and short. Left as exercise. stack.append([w for w in word_list if not w in stop_words]) def frequencies(): """ Takes a list of words and returns a dictionary associating words with frequencies of occurrence. The word list is assumed to be on the stack. """ word_list = stack.pop() word_freqs = {} i = len(word_list) # A little flavour of the real Forth style here... for wi in range(0, len(word_list)): stack.append(word_list[wi]) # Push the word, stack[0] # ... but the following line is not in style, because the naive implementation # would be too slow, or we'd need to implement faster, hash-based search if stack[0] in word_freqs: stack.append((word_freqs[stack[0]], word_freqs[stack[0]])) # (w, f) in stack[1] stack[1] = (stack[0], stack[1][1] + 1) # Swap the tuple the stack with a new one word_freqs[stack[-1][0]] = stack[-1][1] # Load the updated freq back onto the heap else: stack.append((stack[0], 1)) # Push the tuple (w, 1) word_freqs[stack[-1][0]] = stack[-1][1] # Load it back to the heap stack.pop() # Pop (w, f) stack.pop() # Pop word # Push the result onto the stack stack.append(word_freqs) def sort(): """ Takes a dictionary of words and their frequencies and returns a list of pairs where the entries are sorted by frequency """ word_freq = stack.pop() # Not in style, left as exercise stack.append(sorted(word_freq.iteritems(), key=operator.itemgetter(1), reverse=True)) # # The main function # stack.append(sys.argv[1]) read_file(); filter_chars(); scan(); remove_stop_words() frequencies(); sort() word_freqs = stack.pop() for i in range(0, 25): stack.append(word_freqs[i]) print stack[0][0], ' - ', stack[0][1] stack.pop()
6c12e09f840a8e2fa23904b1dee0215600f35831
ScottD61/Thinkful
/Unit1/join1.py
744
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 19 17:05:52 2015 @author: scdavis6 """ import sqlite3 as lite import pandas as pd con = lite.connect('/Users/scdavis6/getting_started.db') join_query = "SELECT name, state, year, warm_month, cold_month FROM cities INNER JOIN weather ON name = city;" joined = pd.read_sql(join_query, con) joined_july = joined[joined['warm_month'] == 'July'] joined_july.columns z = zip(joined_july['name'], joined_july['state']) together = joined_july.apply(lambda x:'%s, %s' % (x['name'],x['state']),axis=1) print("cities that are warmest in July are:", ', '.join(together.tolist())) #cities that are warmest in July are: New York City, NY, Boston, MA, Chicago, IL, #Dallas, TX, Seattle, WA, Portland, O
8c79d7caeb39a173173de7e743a8e2186e2cfc0a
osirisgclark/python-interview-questions
/TCS-tataconsultancyservices2.py
344
4.46875
4
""" For this list [1, 2, 3] return [[1, 2, 3], [2, 4, 6], [3, 6, 9]] """ list = [1, 2, 3] list1 = [] list2 = [] list3 = [] for x in range(1, len(list)+1): list1.append(x) list2.append(2*x) list3.append(3*x) print([list1, list2, list3]) """ Using List Comprehensions """ print([[x, 2*x, 3*x] for x in range(1, len(list)+1)])
7cc58e0ee75580bc78c260832e940d0fd07b9e2a
minerbra/Temperature-converter
/main.py
574
4.46875
4
""" @Author: Brady Miner This program will display a temperature conversion table for degrees Celsius to Fahrenheit from 0-100 degrees in multiples of 10. """ # Title and structure for for table output print("\nCelsius to Fahrenheit") print("Conversion Table\n") print("Celsius\t Fahrenheit") for celsius in range(0, 101, 10): # loop degrees celsius from 0 to 100 in multiples of 10 fahrenheit = (celsius * 9 / 5) + 32 # Formula to convert celsius to fahrenheit print("{}\t\t {}".format(celsius, round(fahrenheit))) # Format the data to display in the table
147dbdbb81dc3fd47a93f30882c169529b969f99
Ricardop123/python-kmmx
/generadores.py
151
3.578125
4
def getNumbers(n): for x in range(n): yield x print(getNumbers(9)) g = getNumbers(10) print(g.__next__()) print(g.__next__()) print(g.__next__())
35bf98ba27b4d40061a72d9b7b9f996831faddbf
Nahia9/COMP301-Python-Assignment04
/generator.py
2,501
4.0625
4
""" File Name: generator.py Name:Nahia Akter Student#: 301106956 Date: 23/08/2020 File description: Generates and displays sentences chooding random words from files """ import random def getWords(filename): files = open(filename) temp_list = list() for each_line in files: each_line = each_line.strip() temp_list.append(each_line) # list will converted to tuple words = tuple(temp_list) files.close() # returning the tuple return words """Getting words from the text files using getWords function""" articles = getWords('articles.txt') nouns = getWords('nouns.txt') verbs = getWords('verbs.txt') prepositions = getWords('prepositions.txt') conjunctions = getWords('conjunctions.txt') adjectives = getWords('adjectives.txt') def sentence(): """Builds and returns a sentence.""" x = random.randint(0,1) if x == 0: return nounPhrase() + " " + verbPhrase() else: return nounPhrase() + " " + verbPhrase() + " " + conjunctionPhrase() + " " + nounPhrase() + " " + verbPhrase() def nounPhrase(): """Builds and returns a noun phrase.""" x = random.randint(0,1) if x == 0: return random.choice(articles) + " " + random.choice(nouns) else: return random.choice(articles) + " " + adjectivePhrase() + " " + random.choice(nouns) def verbPhrase(): """Builds and returns a verb phrase.""" x = random.randint(0,1) if x == 0: return random.choice(verbs) + " " + nounPhrase() + " " else: return random.choice(verbs) + " " + nounPhrase() + " " + prepositionalPhrase() def prepositionalPhrase(): prephrase = "" prechance = random.randrange(100) + 1 if (prechance > 50): prephrase = prepositionalPhrase() return random.choice(prepositions) + " " + nounPhrase() def adjectivePhrase(): """Builds and returns a adjective phrase.""" adjphrase = "" adjchance = random.randrange(100)+1 if (adjchance > 60): adjphrase = adjectivePhrase() return random.choice(adjectives) + " " + nounPhrase() def conjunctionPhrase(): conjphrase = "" conjchance = random.randrange(100)+1 if (conjchance > 70): conjphrase = conjunctionPhrase() return random.choice(conjunctions) + " " + nounPhrase() def main(): """Allows the user to input the number of sentences to generate.""" number = int(input("Enter the number of sentences: ")) for count in range(number): print(sentence()) main()
6da72bf5cc9c6faf6032a114897ee1ee8dfa88e7
fayiz/python
/chocolates_by_numbers.py
224
3.703125
4
def find_gcd(a, b): if b == 0: return a else: #print(find_gcd(b, a % b)) return find_gcd(b, a % b) def solutions(N, M): return N // find_gcd(N, M) print(solutions(10, 4))
cc2da260abc8ba0bb81ad5946349a3d32ba26448
ardinur03/belajar_python
/pembelajaran_dalam_yt/parentclass.py
1,027
3.96875
4
# class parent class Person: # constructor def __init__(self, name = "Anonymouse", umur = 0): self.__umur = umur self.__name = name # ambil nama def getName(self): return self.__name # ambil umur def getUmur(self): return self.__umur def perkenalkan_diri(self): return "Saya adalah " + self.__name + ", berumur " + str(self.__umur) + " tahun" # class child 1 class Student(Person): # constructor parent def __init__(self, name = "Anonymouse", umur = 0, jk = "parameter kosong"): super().__init__(name=name, umur=umur) self.__jk = jk def perkenalkan_diri(self): return super().perkenalkan_diri() + " jenis kelamin " + self.__jk # class child 2 class Teacher(Person): def __init__(self, name = "Anonymouse", umur = 0): super().__init__(name=name, umur=umur) def main(): c = Student("Ardi", 17, "Laki laki") print(c.perkenalkan_diri()) t = Teacher("Bu Ibu", 27) print(t.perkenalkan_diri()) main()
04a85c04f42f4253ca93966eaa54ae2f6ead145d
ardinur03/belajar_python
/belajar_di_sekolah_koding/basic/belajar.py
4,619
4
4
print("\t WELCOME TO LEARN PYTHON") # identitas about me Nama = "Muhamad Ardi Nur Insan" Kelas = "11 RPL 1" print("Nama :", Nama +"\nKelas :", Kelas) print("----------------\"-----\"-----------------") # aplikasi sederhana penanyaan Nama # concatinetion (penggabungan string) """ nama = input("\nSiapa nama anda bosqu?? ") umur = input("\nUmur berapa anda?? ") print("Wihh..salam kenal! boss " + nama + " Umur anda " + umur + " Tahun") """ # boolean """ x = "ardi" print(x.isalnum()) #mengecek apakah ini nomber atau bukan """ #if else """ angka1 = 90 angka2 = 100 if angka1 > angka2: print("Horee benar!!!") else: print("Oow! salah!") """ # aplikasi sederhana hitung hutang if-elif-else """ uang = input("Uang anda berapa? ") hutang = 10000 if int(uang) < hutang: print("Hutang anda : ", hutang) print("Uangnya kurang bos!!!:)") elif int(uang) == hutang: print("Hutang anda : ", hutang) print("Terimakasih sudah membayar :)") else: hasil = int(uang)-hutang print("Hutang anda : ", hutang) print("Uang lebih bos!!! Kembaliannya : ", hasil) """ # contoh if else bercabang """ Putri raja ingin menikah dengan syarat baik dan rajin tamu = "cwe" baik = True rajin = True if baik & rajin: if tamu == "cwo": print("Nikah yuk!!!") else: print('kita sodaraan saja!!!') else: print("hush! sana!!!") """ #perulangan while """ hitung = 0 while hitung < 5: print("Halloo Ardi!!!") hitung = hitung+1 """ # for in """ orang = ['Ardi', 'Ahmad', 'Bujank', 'Naufal', 'Diaz'] #judul = "YT Ardi Hydra" for nama in orang: print("Nama orangnya adalah : ", nama) """ # loop bercabang while """ a = 1 while a < 5: b = 0 while b < a: print("*", end="") b += 1 print() a += 1 """ # loop bercabang while """ for a in range(1,5): for b in range(1,5): c = a*b print(c, end=" ") print() """ # list """ orang = ['Ardi', 'Ahmad', 'Diaz', 'Naufal'] umur = [18, 17, 17, 19, 36] mixed = ['text', 78, 9.7] # menampilkan semua dalam lis->var # print(orang) # mengedit list # orang[0]= "Muhamad Ardi Nur Insan" # tambah data list # orang.append('nur insan') # hapus data list # del orang [4] print(orang) """ """ # dictionary orang = {'Nama' : 'Muhamad Ardi Nur Insan', 'kelas' : 'XI RPL 1', 'Umur' : '17 Tahun', 'Jenis Kelamin' : 'Laki-laki' } # memanggil hasil print("Namanya adalah : ", orang['Nama']) print("Umurnya adalah : ", orang['Umur']) # menambah data orang['Sekolah'] = 'SMK Negeri 11 Bandung' # mengedit data orang['Nama'] = 'Ardi Hydra' # menghapus data del orang['Umur'] print("Sekolahnya adalah : ", orang) # mengeluarkan sesuai data dictionary for key, value in orang.items(): print(key + " - " + value) """ # list = [] - dictionary {} - tuples () # nested dictionary data = { 1:{'nama':'ardi', 'kelas':'XI RPL 1', 'sekolah':'SMK Negeri 11 Bandung'}, 2:{'nama':'mad', 'kelas':'XI MM 1', 'sekolah':'SMK Negeri 11 Bandung'} } # print(data[1]['nama']) = untuk memanggil sallah satu key awal """ for key, value in data.items(): print("\nKeynya : ", key) for key2 in value: print(key2 + "-", value[key2]) """ """ #FUNCTION = PARAMETER, RETURN, KEYWORD ARGUMEN 1. tanpa berparameter 2. ada parameter 3. parameter default parameter = argumen """ # 1 parameter """ def printArdi(teks = 'Parameter belum di isi'): print("----------") print(teks) print("----------") printArdi("Muhamad Ardi Nur Insan") printArdi("XI RPL 1") """ # 2 parameter """ def printTeks(nama = 'Parameter nama kosong!!!', kelas = 'Parameter kelas kosong!!!'): print("----------------------") print(nama) print(kelas) print("----------------------") printTeks("Muhamad Ardi Nur Insan", "XI RPL 1") """ # fungsi menggunakan return """ def hitung(a,b,c): return (a*b)+c print("Hasil perkalian : ", hitung(4,5,1)) """ # fungsi menggunakan keyword argumen """ def data(nama, kelas): print("Nama "+nama + " Kelas "+ kelas) data(kelas = "XI RPL 1", nama = "Muhamad Ardi Nur Insan") """ # percobaan """def coba(nama, kelas, sekolah, noHp = "nope kosong"): print("Nama : "+nama) print("Kelas : "+kelas) print("Sekolah : "+sekolah) print("No Hp : "+noHp) coba("Muhamad Ardi Nur insan", "XI RPL 1", "SMK Negeri 11 Kota Bandung", "08953288984") """ # *args """def benda(*args): for nama in args: print(nama) benda("pulpen", "pensil", "penggaris", "penghapus")""" # **kwargs def jurusan(**jrs): for nama, nilai in jrs.items(): print(nama, " - ", nilai) jurusan(MM = "Multimedia", RPL = "Rekayasa Perangkat Lunak", TKJ = "Teknik Komputer dan Jaringan") print(" ")
83df1810e8a994862571c510473e77c305bc479e
josbex/HS-detection_in_social_media_posts
/util/vocab_parser.py
641
3.5625
4
def file_to_list(path): #completeName = r"C:\Users\josef\Desktop\exjobb-NLP\\" + filename + ".txt" completeName = path f = open(completeName, "r") vocab_list = [] while True: word = f.readline() vocab_list.append(word.rstrip()) if not word: break f.close() return vocab_list #read_file("bad-words") #read_file("google-10000-english-usa") #read_file("vocab") #this contains 3000 english words plus 1300 bad words #dict_to_list() #print(lst) #big_vocab = file_to_list(r"C:\Users\josef\Desktop\exjobb-NLP\big_vocab.txt") #big_vocab.sort(key=len) #print(big_vocab[10000:15000])
ec2ffda93473b99c06258761740065801e017162
saimkhan92/data_structures_python
/llfolder1/linked_list_implementation.py
1,445
4.28125
4
# add new node in the front (at thr root's side) import sys class node(): def __init__(self,d=None,n=None): self.data=d self.next=n class linked_list(node): def __init__(self,r=None,l=0): self.length=l self.root=r def add(self,d): new_node=node() new_node.data=d if (self.root==None): self.root=new_node new_node.next=None self.length=1 else: self.length+=1 new_node.next=self.root self.root=new_node def display(self): i=self.root while i: print(str(i.data)+" --> ",end="") i=i.next print("None") def delete(self,i): if self.root.data==i: self.root=self.root.next else: current_node=self.root.next previous_node=self.root while current_node: if current_node.data==i: previous_node.next=current_node.next return True print(2) else: previous_node=current_node current_node=current_node.next print("3") #lnk=linked_list() #lnk.add(10) #lnk.add(20) #lnk.add(30) #lnk.add(25) #lnk.display() #lnk.delete(30) #lnk.display()
d7fb7ba1b47eb9787dc45de53dd221d75d52a05f
catterson/python-fundamentals
/challenges/02-Strings/C_interpolation.py
1,063
4.78125
5
# Lastly, we'll see how we can put some data into our strings # Interpolation ## There are several ways python lets you stick data into strings, or combine ## them. A simple, but very powerful approach is to us the % operator. Strings ## can be set up this way to present a value we didn't know when we defined the ## string! s = 'this string is %d characters long' ## We can apply values to a string with an expression that goes: ## string % value(s) ## if there's more than one, put them in ()'s with commas between! ## Go ahead and compute the length of s and substitute it into the string: d = len(s) print s%d # conversion ## Adding a string and a number together doesn't make sense... for example, ## what's the right thing to do for '1.0' + 2? Let's explore both ways that ## could go. First, we need to do the conversion ourselves. Remember, you can ## use the type functions to do that, in this case, str() and float() - int() ## would lose the decimal point that is clearly there for a reason! print '1.0' + str(2) print float('1.0') + float(2)
e2ad159e8c2c563784f23a62df878149c4a99ed1
Vihaanmaster/Jarvis
/helper_functions/database.py
3,947
3.96875
4
from os.path import isfile from sqlite3 import connect file_name = 'tasks.db' class Database: """Connector for ``Database`` to create and modify. >>> Database ``create_db`` - creates a database named 'tasks.db' with table as 'tasks' ``downloader`` - gets item and category stored in the table 'tasks' ``uploader`` - adds new item and category to the table 'tasks' and groups with existing category if found ``deleter`` - removes items from the table 'tasks' when the item or category name is matched. """ def __init__(self): self.file_name = file_name self.table_name = self.file_name.replace('.db', '') def create_db(self) -> str: """Creates a database with the set ``filename: tasks.db`` and a ``table: tasks``. Returns: str: A success message on DB and table creation. """ if isfile(self.file_name): return f"A database named, {self.file_name}, already exists." else: connection = connect(self.file_name) connection.execute(f"CREATE TABLE {self.table_name} (category, item, id INTEGER PRIMARY KEY )") connection.commit() return "A database has been created." def downloader(self) -> list: """Downloads the rows and columns in the table. Returns: list: The downloaded table information. """ connection = connect(self.file_name) connector = connection.cursor() connector.execute(f"SELECT category, item from {self.table_name}") response = connector.fetchall() connector.close() return response def uploader(self, category: str, item: str) -> str: """Updates the table: tasks with new rows. Args: category: Category under which a task falls. (Eg: Groceries) item: Item which has to be added to the category. (Eg: Water can) Returns: str: A string indicating the item and category that it was added to. """ connection = connect(self.file_name) response = Database().downloader() for c, i in response: # browses through all categories and items if i == item and c == category: # checks if already present and updates items in case of repeated category return f"Looks like the table: {self.table_name}, already has the item: {item} in, {category} category" connection.execute(f"INSERT INTO {self.table_name} (category, item) VALUES ('{category}','{item}')") connection.commit() return f"I've added the item: {item} to the category: {category}." def deleter(self, item: str) -> str: """Deletes a particular record from the table. Args: item: Takes the item that has to be removed as an argument. Returns: str: On success, returns a string indicating the item has been deleted. On failure, returns a string indicating the item was not found. """ connection = connect(self.file_name) response = Database().downloader() check = 0 for c, i in response: # browses through all categories and items if i == item or c == item: # matches the item that needs to be deleted check += 1 # if check remains 0 returns the message that the item or category wasn't found if check == 0: return f"Looks like there is no item or category with the name: {item}" connection.execute(f"DELETE FROM {self.table_name} WHERE item='{item}' OR category='{item}'") connection.commit() return f"Item: {item} has been removed from {self.table_name}." if __name__ == '__main__': data = Database().downloader() for row in data: result = {row[i]: row[i + 1] for i in range(0, len(row), 2)} print(result)
541e5f2ac9427538751cbfca1c3b9c54e8d17cc8
MohammedRiyaz-au7/w3d1d2-cc-assign
/w3d1d2 assign q1.py
357
3.859375
4
import operator d = {'a': 100, 'b': 200, 'c': 300, 'd': 400, } print('Original dictionary :' ,d) sorted_d = sorted(d.items(), key=operator.itemgetter(1)) print('Dictionary in ascending order by value : ',sorted_d) sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True)) print('Dictionary in descending order by value : ',sorted_d)
cc70dde013a71d8672a7d3cf7341d87083897078
gmurr20/CollegeTVDevice
/PythonWebApp/News.py
1,261
3.703125
4
import requests import json import properties ''' News article object to contain all relevant information from api ''' class newsArticle: imageUrl = "" title = "" description = "" author = "" def __init__(self, imageUrl, title, description, author): self.imageUrl = imageUrl self.title = title self.description = description self.author= author ''' Parse the JSON response from api and get relevant information for each source ''' def pullArticle(articleList, source): business = requests.get("https://newsapi.org/v1/articles?source="+source+"&sortBy=top&apiKey="+properties.newsApiKey) data = json.loads(business.text) source = data['source'] articles = data['articles'] article = articles[0] imageUrl = article['urlToImage'] description = article['description'] title = article['title'] if article['author'] != None: author = source+"- "+article['author'] else: author = source+"- "+"No author" newArticle = newsArticle(imageUrl, title, description,author) articleList.append(newArticle) return articleList ''' Pull all the news from the three sources ''' def pullNews(): articleList = [] pullArticle(articleList, "business-insider") pullArticle(articleList, "ign") pullArticle(articleList, "recode") return articleList
3eeeae8a44a57ef5d8e76240db823cfc5e4284f3
citisy/Algorithms
/tree/Heap.py
3,452
4.0625
4
"""堆,一颗完全二叉树,宜采用顺序存储,这里使用链式存储 基本特征:小根堆:根<左孩子or右孩子,大根堆:根>左孩子or右孩子 """ from BinaryTree import BinaryTree # 小根堆 class Heap(BinaryTree): """ functions: insert(item, bn): insert an item delete(item, bn): delete an item """ def init(self, arr): for i in arr: self.insert(i) def insert(self, item): """插入一个叶子结点""" # 堆为空,作为根结点插入 if self.is_empty(): if not self.p: self.p.append(self.node(None)) self.p.append(self.node(item)) # 非空 else: n = len(self.p) # 把元素插到堆尾 self.p.append(self.node(item)) # compared with the parent, if the item is small, swap them, then, repeat the action while n != 1 and item < self.p[n // 2].data: self.p[n].data, self.p[n // 2].data = self.p[n // 2].data, self.p[n].data n = n // 2 self.mid = self.get_mid(self.p) def get_data(self): """删除堆顶结点,并返回堆顶元素""" n = len(self.p) - 1 # index 0 of tree is None, so tree's real length must sub 1 if n == 0: # heap is empty bn_data = None elif n == 1: # only have mid node bn_data = self.p.pop().data self.mid = None else: bn_data = self.p[1].data if n % 2 == 0: # delete the tail of heap self.p[n // 2].left = None else: self.p[n // 2].right = None self.p[1].data = self.p.pop().data # tail of heap move to head i = 1 while i < n and self.p[i]: if i * 2 + 1 < n: # have right children if self.p[i * 2].data < self.p[i * 2 + 1].data: # 左孩子的值小于右孩子的值,取左孩子 p = self.p[i * 2] j = i * 2 else: # 否则取右孩子 p = self.p[i * 2 + 1] j = i * 2 + 1 elif i * 2 < n: # have left children p = self.p[i * 2] # 因为没有右孩子了,所以只需要跟左孩子比较就可以了。 j = i * 2 else: break if self.p[i].data > p.data: self.p[i].data, p.data = p.data, self.p[i].data else: break i = j self.mid = self.get_mid(self.p) return bn_data if __name__ == '__main__': import random random.seed(0) arr = list(range(1, 11)) random.shuffle(arr) print("输入序列:", arr) bt = Heap() bt.init(arr) # bt.draw(bt.mid) print('广义表形式:', bt.generalized(bt.mid)) print('树形结构形式:\n', end=bt.tree(bt.mid) + '\n') print('从小到大出队:', end=' ') while 1: bn_data = bt.get_data() if bn_data is None: break print(bn_data, end=' ') """ 输入序列: [8, 9, 2, 6, 4, 5, 3, 1, 10, 7] 广义表形式: 1(2(4(9,10),6(7)),3(8,5)) 树形结构形式: 1-->2-->4-->9 └-->10 └-->6-->7 └-->3-->8 └-->5 从小到大出队: 1 2 3 4 5 6 7 8 9 10 """
092e6fad0c66413d23ce81ac354881cb212e7f50
citisy/Algorithms
/tree/BinaryTree.py
11,059
3.796875
4
""" 根据数组创建一个应用双链表的二叉树 二叉树的种类: 满二叉树:每一层都是满的 完全二叉树:除最后一层或包括最后一层,其余层全满,最后一层在右边缺若干个结点 理想平衡二叉树:除最后一层或包括最后一层,其余层全满,最后一层的结点任意分布 种类包含情况: 理想平衡二叉树>完全二叉树>满二叉树 二叉树的一些特征: 叶子结点n0,单分支n1,双分支n2 => n0+n1+n2=n1+2n2+1 => n0=n2+1 => 叶子结点比双分支结点多1个 根结点:i 左孩子:2i 右孩子:2i+1 n个结点的完全二叉树的深度:lb(n)+1(下取整) """ from BLinkList import BLinkList import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.collections as plc class BinaryTree(BLinkList): """ functions: init(arr): 初始化树 print_(bn): 打印出二叉树的广义表 inorder(bn): 中序遍历 preorder(bn): 前序遍历 postorder(bn): 后序遍历 depth(bn): 返回树的深度 find(item, bn): 查找某一元素是否存在 get_bn(): 获取当前结点 update(item, change_item, bn): 更新一个结点 """ def init(self, dic): assert self.is_empty(), 'The present tree is not empty!' max_len = max(dic) arr = [None for _ in range(max_len + 1)] for k, v in dic.items(): arr[k] = v self.mid = self.node(arr[1]) # 二叉链表的存储映象 # even is left child, odd is right child, and 1 is mid node p = [self.node(None) for _ in range(len(arr))] # don't use `[BNode(None)] * len(arr)` for i in range(1, len(arr)): if arr[i] is not None: p[i].data = arr[i] self.p = p self.mid = self.get_mid(p) self.array = [_.data for _ in p] def init_by_order(self, in_order: list, pre_order: list = None, post_order: list = None): """输入中序序列以及先序或后序序列,还原二叉树""" assert in_order, 'You must input in_order!' assert (pre_order or post_order), 'You input neither pre_order nor post_order!' assert self.is_empty(), 'The present tree is not empty!' order = pre_order or post_order[::-1] assert len(in_order) == len(order), 'Input order must have the same length!' self.mid = self.node(order[0]) flag = [0] * len(in_order) # 标记数组 p = [self.node(None) for _ in range(len(in_order))] # 存储映像 idx = in_order.index(order[0]) flag[idx] = 1 p[idx] = self.mid for d in order[1:]: idx = in_order.index(d) p[idx].data = d if not sum(flag[:idx]): # 最左边 f_idx = flag.index(1) p[f_idx].left = p[idx] elif not sum(flag[idx + 1:]): # 最右边 f_idx = -flag[::-1].index(1) - 1 p[f_idx].right = p[idx] else: # 两标记元素的中间 l_idx = idx - flag[:idx][::-1].index(1) - 1 # 最靠近当前节点左边的节点 r_idx = idx + flag[idx + 1:].index(1) + 1 # 最靠近当前节点右边的节点 if pre_order: if not p[l_idx].right: # 不存在右子树 p[l_idx].right = p[idx] else: # 存在右子树 p[r_idx].left = p[idx] else: if not p[r_idx].left: # 不存在右子树 p[r_idx].left = p[idx] else: # 存在右子树 p[l_idx].right = p[idx] flag[idx] = 1 self.array = self.get_array(self.mid) self.p = [self.node(_) for _ in self.array] def generalized(self, bn): """返回二叉树的广义表""" def recursive(bn): if bn: stack.append(str(bn.data)) if bn.left or bn.right: stack.append('(') # 存在左或右孩子时打印'(' recursive(bn.left) if bn.right: stack.append(',') # 存在右孩子时打印',' recursive(bn.right) stack.append(')') # 左右孩子都遍历完,打印')' stack = [] recursive(bn) return ''.join(stack) def tree(self, bn): """返回二叉树的树形结构""" def recursive(bn, dep=0, length=[]): if bn: stack.append(str(bn.data)) if bn.left or bn.right: if dep >= len(length): length.append(len(str(bn.data))) else: length[dep] = max(length[dep], len(str(bn.data))) dep += 1 stack.append('-->') recursive(bn.left, dep, length) if bn.right: s = '' for i in range(dep): s += ' ' * (length[i] + 3) stack.append('\n%s└-->' % s[:-4]) recursive(bn.right, dep, length) else: stack.pop(-1) if bn: stack = [] recursive(bn) return ''.join(stack) def draw(self, bn): """图像可视化""" array = self.get_array(bn) fig, ax = plt.subplots() r = 1 max_depth = self.height(bn) max_width = 2 ** (max_depth - 1) * 3 * r circles, lines = [], [] get_xy = lambda depth, i: (max_width * (2 * i + 1) / 2 ** (depth + 1), -max_width * depth / max_depth / 2) for depth in range(max_depth): for i, data in enumerate(array[2 ** depth: 2 ** (depth + 1)]): if data is not None: x, y = get_xy(depth, i) circles.append(mpatches.Circle((x, y), r)) ax.text(x, y, data, ha='center', va='center', size=15) if 2 ** (depth + 1) + 2 * i < len(array) and array[2 ** (depth + 1) + 2 * i] is not None: # 有左子树 lines.append(((x, y), get_xy(depth + 1, 2 * i))) if 2 ** (depth + 1) + 2 * i + 1 < len(array) and array[2 ** (depth + 1) + 2 * i + 1] is not None: # 有右子树 lines.append(((x, y), get_xy(depth + 1, 2 * i + 1))) pc = plc.PatchCollection(circles) lc = plc.LineCollection(lines) ax.add_collection(pc, autolim=True) ax.add_collection(lc, autolim=True) ax.autoscale_view() ax.set_axis_off() plt.axis('equal') plt.show() def inorder(self, bn): """中序遍历 先访问左孩子,再打印根结点,最后访问右孩子 first, access the left node then, access the root node finally, access the right node left -> mid -> right """ def recursive(bn): if bn: recursive(bn.left) order.append(bn.data) recursive(bn.right) order = [] recursive(bn) return order def postorder(self, bn): """后序遍历 先依次访问左右孩子,再打印根结点 first, access the left and right node respectively then, access the mid node left -> right -> mid """ def recursive(bn): if bn: recursive(bn.left) recursive(bn.right) order.append(bn.data) order = [] recursive(bn) return order def preorder(self, bn): """前序遍历(深度优先) 先打印根结点,再依次访问左右孩子 first, access the mid node then, access the left and right node respectively mid -> left -> right """ def recursive(bn): if bn: order.append(bn.data) recursive(bn.left) recursive(bn.right) order = [] recursive(bn) return order def levelorder(self, bn): """按层遍历(广度优先) 队列思想,根结点先入队,其附属左右孩子依次入队,最后按出队顺序打印即可 queue: [m, l, r, ll, rl, lr, rr, lll, ...] """ q = [] # 队列数组 q.append(bn) # 根结点入队 order = [] while q: # 队列为非空时 # 依次出队 p = q.pop(0) order.append(p.data) # 附属的左右孩子依次入队 # 左孩子入队 if p.left: q.append(p.left) # 右孩子入队 if p.right: q.append(p.right) return order def find(self, item): """查找某一元素是否存在""" for i in self.p: if item == i.data: return i return None def update(self, item, change_item): """更新一个结点""" b = self.find(item) if b: b.data = change_item if item in self.array: self.array[self.array.index(item)] = change_item if __name__ == '__main__': index_item = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 13: 'j'} bt = BinaryTree() bt.init(index_item) print('树的深度为:', bt.height(bt.mid)) print('顺序表形式:', bt.array) print('广义表形式:', bt.generalized(bt.mid)) print('树形结构形式:\n', end=bt.tree(bt.mid) + '\n') print('前序遍历:', bt.preorder(bt.mid)) print('中序遍历:', bt.inorder(bt.mid)) print('后序遍历:', bt.postorder(bt.mid)) print('按层遍历:', bt.levelorder(bt.mid)) print('找到的结点:', bt.find('g')) bt.draw(bt.mid) bt.update('a', 'z') print('替换 a 后广义表示:', bt.generalized(bt.mid)) bt2 = BinaryTree() bt2.init_by_order(bt.inorder(bt.mid), pre_order=bt.preorder(bt.mid), post_order=bt.postorder(bt.mid), ) print('树形结构形式:\n', end=bt2.tree(bt2.mid) + '\n') """ 树的深度为: 4 顺序表形式: [None, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', None, None, None, 'j'] 广义表形式: a(b(d(h,i),e),c(f(,j),g)) 树形结构形式: a-->b-->d-->h └-->i └-->e └-->c-->f └-->j └-->g 前序遍历: ['a', 'b', 'd', 'h', 'i', 'e', 'c', 'f', 'j', 'g'] 中序遍历: ['h', 'd', 'i', 'b', 'e', 'a', 'f', 'j', 'c', 'g'] 后序遍历: ['h', 'i', 'd', 'e', 'b', 'j', 'f', 'g', 'c', 'a'] 按层遍历: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 找到的结点: g 替换 a 后广义表示: z(b(d(h,i),e),c(f(,j),g)) """
e554812faf2fc21c4597c7e161847760a611a173
omar00070/Search-Algorithm-Vesualiser
/test.py
185
3.78125
4
a = {move: 1 for move in ['K', 'U']} # print(a) a = 3 #integer b = 'string' # string c = True # boolean print(a, b, c) a = 3 # a a value of 3 if a == 3: print('a value is ', a)
7a0de5eaa89ae4b9e63c0c0b6ba1bbece71d1631
RomainTOMINE2/Romain
/Sapin2.py
556
3.703125
4
def printTriangle(incr, base, a_center): for y in range(4): etoiles = base + (y*incr) print((etoiles*"*").center(a_center)) def printSapin(height): center = ((1+(( height-1)*2))+( height*2)) + 2*( height*2) for y in range(1, height+1): printTriangle(y*2, 1+((y-1)*2), center) printBottom(center) def Bottom(): return "*" def printBottom(aligne): for colo in range(3): result = "" for esp in range(5): result += Bottom() print(result.center(aligne)) printSapin(3)
edef5c4ef9472a6b9c380fc5baee59bdc56556d1
rmartinez5748/CursoPython
/WorkingREGEX.py
266
3.71875
4
import re cadena = 'Estoy trabajando con Python en domingo y Semana Santa' busqueda = 'domingo' if print(re.search(busqueda, cadena)) is not None: print(f'Se ha encontrado el termino {busqueda}') else: print(f'No se ha encontrado el termino {busqueda}')
2a00e265a8f1b4f850e2c3f7aed7575dc486adfd
rmartinez5748/CursoPython
/RandomExercise.py
214
3.578125
4
import random class Dice: def roll(self): dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) result = (dice1, dice2) return result game = Dice() print(game.roll())
2a3051f823f33587a585ea1f037e8673105fefc5
sindhu819/Competitive-Coding-10
/Problem-129.py
751
3.90625
4
''' Leetcode- 122. Best Time to Buy and Sell Stock II - https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ Time complexity - O(N) Space complexity - O(1) Approach - We need to find the peak and valleys in an given array ''' class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices)==0: return 0 i=0 peak=prices[0] valley=prices[0] maxprofit=0 while i<len(prices)-1: while i<len(prices)-1 and prices[i]>=prices[i+1]: i=i+1 valley=prices[i] while i<len(prices)-1 and prices[i]<=prices[i+1]: i=i+1 peak=prices[i] maxprofit+= peak-valley return maxprofit
8dbf93ca05e34953aeb02f90441141cda89c210f
Krokette29/LeetCode
/Python/3. Longest Substring Without Repeating Characters.py
3,617
3.796875
4
class Solution(object): """ Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. """ def __checkRepeat(self, substring: str) -> bool: mySet = [] for i in substring: if i in mySet: return False else: mySet.append(i) return True def lengthOfLongestSubstring(self, s: str) -> int: """ My solution. Using lots of time when executing large repeated strings. Almost like brute-force. TLE (Time Limit Exceed) on LeetCode. Time: O(n^3) Space: O(min(m, n)) # for checkRepeat, m is the size of charset """ total_length = len(s) for windowSize in reversed(range(1, total_length + 1)): for i in range(total_length - windowSize + 1): res = self.__checkRepeat(s[i:i + windowSize]) if res: return windowSize return 0 def solution1(self, s: str) -> int: """ Brute Force Check all the substring one by one to see if it has no duplicate character. Almost like my solution. TLE. Time: O(n^3) Space: O(min(m, n)) """ return 0 def solution2(self, s: str) -> int: """ Sliding Window Use a queue. Loop over all chars in the string. If the char is not in the queue, append it. Otherwise pop the queue. Time: O(n) Space: O(min(m, n)) # for queue """ queue = [] max_length = 0 index = 0 # loop over all chars in the string while index < len(s): char = s[index] # if char not in the queue, append it if char not in queue: queue.append(char) index += 1 # otherwise check the result, add pop the queue else: if len(queue) > max_length: max_length = len(queue) del queue[0] return max_length if max_length > len(queue) else len(queue) def solution3(self, s: str) -> int: """ Sliding Window Optimized using Hash Table/Dictionary Like the sliding window. If found repeated char, start index jumps to the next index of the last repeated char. Time: O(n) # half as solution 2 Space: O(min(m, n)) """ dict = {} # key: char, value: last index max_length = 0 start_index = 0 for end_index in range(len(s)): char = s[end_index] # if found repeated char, update the start index if char in dict.keys(): start_index = max(dict[char] + 1, start_index) length = end_index - start_index + 1 # current length max_length = max(length, max_length) # maximum length dict[char] = end_index # update dictionary return max_length def main(): solution = Solution() input = "dvdf" res = solution.solution3(input) print(res) if __name__ == '__main__': main()
bdb0a9bb90ee4c686bbfc66f42ef0368caaff0f7
Kozmoz1983/bootcamp_08122018
/zadanie 4.py
314
3.953125
4
# przykłady input x = int(input("Podaj wartość x: ")) y = int(input("Podaj wartość y: ")) print("Suma: ", x + y) # przykłady wartości logiczne # operatory porównania # ==, <, >, <=, >=, != # ctr + alt + L - pep8 #ctr + / import datetime y = (datetime.datetime.now().year) print (2000 < year)
00809250f83280daac47985b059b773728819074
errai-/euler
/hundredandbelow/prob7.py
310
3.65625
4
# -*- coding: cp1252 -*- def isprime(laavaa): for kamal in range(2, int(laavaa**.5 + 1)): if laavaa%kamal == 0: return False laavaa = 0 break if laavaa != 0: return True jouno = [] qwerty = 2 while len(johno) < 10001: if isprime(qwerty): johno.append(qwerty) qwerty += 1 print johno[10000]
a5ef192661b50bd86878986510e700e5d2f4b615
errai-/euler
/hundredandbelow/prob46.py
632
3.71875
4
# -*- coding: cp1252 -*- import time aika = time.time() #hidastuu oddprimen vuoksi, jos joukko alkulukuja laskettaisiin heti alkuun, vältyttäisiin toistoilta def oddprime(luumu): k = 1 if luumu%2 == 0: k = 0 for a in range(3,int(luumu*0.5+1),2): if luumu%a == 0: k = 0; break return k eitulosta,roadrunner = 1,9 while eitulosta: if oddprime(roadrunner)==1: roadrunner+=2 else: kaa = 1 for ii in range(1,int((roadrunner)**0.5+1)): ahaa = roadrunner-2*(ii**2) if ahaa < 3: break if oddprime(ahaa)==1: kaa = 0; break if kaa == 1: eitulosta = 0 break roadrunner += 2 print roadrunner,time.time()-aika
ce4222854adfff6915cb465dbe0351571bd7fc68
NataliVynnychuk/Python_Hillel_Vynnychuk
/Lesson/Lesson 9.2.py
1,172
3.75
4
import random MIN_LIMIT = -1 MAX_LIMIT = 1 def create_point(min_limit=MIN_LIMIT, max_limit=MAX_LIMIT): point = {"x": random.randint(min_limit, max_limit), "y": random.randint(min_limit, max_limit)} return point def create_triangle(points_name_str: str) -> dict: return {key: create_point() for key in points_name_str} def print_triangles_list(triangles_list): print("---------------------------------------------") for triangle in triangles_list: print(triangle) print("---------------------------------------------") triangles_list = [] names = ["ABC", "MNK", "QWE", "ASD"] for name in names: triangle = create_triangle(name) triangles_list.append(triangle) print_triangles_list(triangles_list) # print(triangles_list) # triangle_ABC = create_triangle("ABC", -100, 100) # triangle_MNK = create_triangle("MNK", -10, 10) # triangle_QWE = create_triangle("QWE", -5, 23) # triangle_ABC = {key: create_point() for key in "ABC"} # triangle_ABC = {"A": create_point(), # "B": create_point(), # "C": create_point()} # print(triangle_ABC) # print(triangle_MNK) # print(triangle_QWE)
7d2beba8951d3f799ebd1bdfce8cc7fc5dceac65
NataliVynnychuk/Python_Hillel_Vynnychuk
/Lesson/Lesson 9 - 17.07.py
1,655
4.25
4
# Стандартные библиотеки python # Функции, область видимости, параметры, параметры по умолчанию, типизация import string import random # import random as rnd # print(string.ascii_lowercase) value = random.randint(10, 20) my_list = [1, 2, 3, 10, 20, 30] # my_list = [True, False] my_str = 'qwerty' choice_from_list = random.choice(my_str) print(value, choice_from_list) from random import randint, choice my_str = 'qwerty' choice_from_list = choice(my_str) value = randint(100, 200) print(value, choice_from_list) new_list = random.shuffle(my_list) #стандартная ошибка!!! print(new_list) new_list = my_list.copy() #shuffle меняет объект!!! поэтому нужен copy random.shuffle(new_list) print(my_list, new_list) ######################################################################## #Dry point_A = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} point_B = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} point_C = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} triangle_ABC = {"A": point_A, "B": point_B, "C": point_C} print(triangle_ABC) point_M = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} point_N = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} point_K = {"x": random.randint(-10, 10), "y": random.randint(-10, 10)} triangle_MNK = {"M": point_M, "N": point_N, "K": point_K} print(triangle_MNK)
43d3766d0badef020984eb062c19463dcd898e61
NataliVynnychuk/Python_Hillel_Vynnychuk
/Lesson/lesson5 - 23.06.py
3,146
3.546875
4
# my_list = [1, 2, 3] # new_list = [my_list.copy(), my_list.copy(), my_list.copy()] # print(new_list) # new_list[0].append(4) # print(my_list) # print(new_list) # # tmp_value = 5 # # go_game = True # text_message = "Введи число от 1 до 10" # # while go_game: # try: # value = int(input(text_message)) # if tmp_value > value: # text_message = "Попробуй больше" # elif tmp_value < value: # text_message = ("Попробуй меньше") # else: # go_game = False # print("Ура, угадал!") # except ValueError: # text_message = "Введи число от 1 до 10" # # # my_str = "blablacarblablacar" #условие # my_symbol = "bla" # # my_symbol_count = my_str.count(my_symbol) # print(my_symbol_count) # # #################################### # # print(f"{my_symbol}\n" * my_symbol_count) #2 вариант # # for _ in range(my_symbol_count): #1 вариант # # print(my_symbol) # # res_msg = f"{my_symbol}\n" * my_symbol_count #3 вариант # print(res_msg.strip()) # ################################### # my_str = "bla BLA car" # my_str = my_str.lower() # symbols_heap = [] # for symbol in my_str: # if symbol not in symbols_heap: # symbols_heap.append(symbol) # res_len = len(symbols_heap) # print(res_len) # # ################################### # my_str = "qwerty" # my_list = [] # for index in range(len(my_str)): # if not index % 2: # symbol = my_str[index] # my_list.append(symbol) # print(my_list) # # 2 подход # # my_str = "qwerty" # my_list = [] # # for index, symbol in enumerate(my_str): # if not index % 2: # my_list.append(symbol) # # print(my_list) # # #################################### # for value in enumerate(my_str): # print(value) # # ##################################### # my_str = "qwerty" # my_list = [] # str_index = [3, 2, 5, 5, 1, 0, 5, 0, 3, 2, 1] # # for index in str_index: # symbol = my_str[index] # my_list.append(symbol) # print(my_list) # # #################################### # my_number = 45678087654567808765456999780876545678 # digit_count = len(str(my_number)) # print(digit_count) # # #################################### # # number_str = str (my_number) # max_symbol = max(number_str) # print(max_symbol) # # #################################### # number_str = str(my_number) # new_number_str = number_str[::-1] # new_number = int(new_number_str) # print(new_number) # # new_number = int(str(my_number)[::-1]) # print(new_number) # #################################### # # my_list = [1, 2, 5, 3, -8 ,4] # sorted_list = sorted(my_list, reverse=True) # print(sorted_list) # # my_list = [1, 2, 5, 3, -8 ,4] # my_str = 'qwerty' # sorted_list = sorted(my_str) # print(sorted_list) # # #################################### # # number_str = str(my_number) # sorted_number_symbols_list = sorted(number_str, reverse=True) # new_number_str = ''.join(sorted_number_symbols_list) # new_number = int(new_number_str) # print(new_number) # # записать одной строкой
b49f67102e945f8e3974411b47590967c0f90e62
Qiiu/MyPython
/FP.py
574
3.546875
4
import os fo=open("Test.txt","w") fo.write("Create a file") fo.flush() fo.close() print("done") mid=input(":") fo=open("Test.txt","r") str=fo.read(5) print("read the line : ",str) fo.close() print("done") mid=input("change the file name right?:") os.rename("Test.txt","change.txt") fo=open("change.txt","r") print("file name : ",fo.name) print("done") mid=input("deleta the file right?:") try: os.remove("Test.txt") print("del done") except OSError: print("Error : No sach file") else: print("done") print("catched the error") pos=os.getcwd() print(pos)
25f7ea6aa88445177bbe8939b893b70527fe32e5
glennlopez/Python.Playground
/Lessons/Introduction/4 - Control Flow/modify_username_with_range.py
189
3.609375
4
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] # write your for loop here for i in range(len(usernames)): usernames[i] = usernames[i].lower().replace(' ', '_') print(usernames)
6577dc8d52ba60ad9ad4fc3069b43b4ad5718df9
glennlopez/Python.Playground
/Lessons/Introduction/6 - Scripting/handling_errors_no_handling.py
287
3.515625
4
def party_planner(cookies, people): num_each = cookies // people leftovers = cookies % people return(num_each, leftovers) num_each, leftover = party_planner(100,'g') print("Number of cookies each: {}".format(num_each)) print("Number of cookies left: {}".format(leftover))
7baa266ef62038c068ba23aa925dc517664fb204
glennlopez/Python.Playground
/SANDBOX/python3/4_dictionary/dictionary_practice2.py
740
4.0625
4
a = {"Name": "Glenn", "DOB": 1987} b = [] c = () d = {0, 1} print(type(a)) print(type(b)) print(type(c)) print(type(d)) myDict = {} print(myDict) myDict["Name"] = "Glenn" myDict["DOB"] = 1987 myDict["Age"] = 2019 - myDict["DOB"] print(myDict) def get_data(): name = input("What is your name: ") year = input("What year were you born: ") month = input("What month were you born: ") day = input("What day were you born: ") return name, int(year), int(month), int(day) contact_info = get_data() usr_name, usr_dob_year, usr_dob_month, usr_dob_day = contact_info person = {0: {"name": usr_name, "year": usr_dob_year, "month": usr_dob_month, "day": usr_dob_day}} print(person[0]["name"], "is", 2019 - person[0]["year"])
e5bae08d87894645b3553505b1a407ed8b83f92c
glennlopez/Python.Playground
/Lessons/Introduction/6 - Scripting/handling_errors.py
504
3.640625
4
def party_planner(cookies, people): leftovers = None num_each = None try: num_each = cookies // people leftovers = cookies % people except ZeroDivisionError: print("Oops, you entered 0 people will be attending.") print("Please enter a good number of people for a party.") return(num_each, leftovers) num_each, leftover = party_planner(100,0) print("Number of cookies each: {}".format(num_each)) print("Number of cookies left: {}".format(leftover))
dc0755a55ce75ca7b9b98acb9d32c4c04663b834
glennlopez/Python.Playground
/SANDBOX/python3/5_loops_branches/break_continue.py
332
4.28125
4
starting = 0 ending = 20 current = starting step = 6 while current < ending: if current + step > ending: # breaks out of loop if current next step is larger than ending break if current % 2: # skips the while loop if number is divisible by 2 continue current += step print(current)
3549002a69657d11af6c5cbabd75fc53b79eccb6
kolasau/python_work_book
/countries.py
338
4.09375
4
countries = ['India', 'Germany', 'France', 'Thailand', 'Georgia'] print(countries) print(sorted(countries)) print(countries) x = sorted(countries) x.reverse() print(x) print(countries) countries.reverse() print(countries) countries.reverse() print(countries) countries.sort() print(countries) countries.sort(reverse=True) print(countries)
55e8154d08832f8b68cefdd005694e542377ae5d
kolasau/python_work_book
/files and exceptions /guest_book.py
260
3.609375
4
name = "\nPlease enter a name: " guests_book = 'guests_book.txt' with open(guests_book, 'a') as gs: while True: names = input(name) if names == 'stop': break else: print(f"Hello, {names.title()}!") gs.write(f"Hello, {names.title()}!\n")()
230e31175a23e817b0d317c46cbf368da5e5cd63
kolasau/python_work_book
/while/toppings.py
565
3.671875
4
cl_topping = "\n( введите 'жирнюка' чтобы закончить оформление заказа)" cl_topping += "\nДобавьте топпинг к пицце: " ctl = [] while True: message = input(cl_topping) if message == 'жирнюка': print("Добавленные топпинги: ") for t in ctl: print(f"\t{t.title()}") break else: ctl.append(message) for t2 in ctl: print(f"Вы добавили: {t2.title()}") print("Ваша пицца никогда не будет готова... лоооооооол")
672003e9de2aa2f932ef7bf57cf73562a94d7fd6
kolasau/python_work_book
/pizza.py
502
3.953125
4
pizzas = ['Cheese', 'Barbeque', 'Lisitsa'] for pizza in pizzas: print("I like " + pizza + " pizza") print("I really love pizza!\n") animals = ['dog', 'cat', 'cow'] for animal in animals: print("A " + animal.title() + " gives a milk to its babies!") print("Any of these animals would make a great pet!\n") friend_pizzas = pizzas[:] pizzas.append('Mashroom') friend_pizzas.append('Potato') print(f"My favorite pizzas are: {pizzas}\n") print(f"My friend's favorite pizzas are: {friend_pizzas}\n")