blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a8f58bbaccee37ba773ffa4d414c92748d052fd5
yiswang/LeetCode
/two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.py
2,072
3.859375
4
#!/usr/bin/python # -*- coding: utf-8 -*- ############################################################################### # # Author: Yishan Wang <wangys8807@gmail.com> # File: two-sum-ii-input-array-is-sorted.py # Create Date: 2017-02-09 # Usage: two-sum-ii-input-array-is-sorted.py # Description: # # LeetCode problem 167. Two Sum II - Input array is sorted # # Difficulty: Easy # # Given an array of integers that is already sorted in ascending order, find # two numbers such that they add up to a specific target number. # # The function twoSum should return indices of the two numbers such that they # add up to the target, where index1 must be less than index2. Please note that # your returned answers (both index1 and index2) are not zero-based. # # You may assume that each input would have exactly one solution and you may # not use the same element twice. # # Input: numbers={2, 7, 11, 15}, target=9 # Output: index1=1, index2=2 # ############################################################################### # # Use two pointers, traverse from two sides of the array respectively. # Time complexity: O(n) # Run time on LeetCode: 39 ms, beat 95.88% # class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ low = 0 high = len(numbers) - 1 while low < high: temp = numbers[low] + numbers[high] if temp == target: return [low+1, high+1] elif temp > target: high -= 1 else: low += 1 return None if __name__ == "__main__": test_cases = [ ([], None), ([], 2), ([1], 1), ([1], 2), ([1,2], 2), ([1,2], 3), ([1,2,3,4], 3), ([1,2,3,4], 6), ([1,2,3,4], 9), ] solu = Solution() for numbers, target in test_cases: print numbers, target res = solu.twoSum(numbers, target) print res print "\n"
3490ac65deeef61c66b7f060469ade6e59f1a6f3
eryilmazysf/assignments-
/specialmethods.py
518
3.75
4
class book(): def __init__(self,name,author,totalpages,kind): self.name=name self.author=author self.totalpages=totalpages self.book_kind=kind def __str__(self): return "name:{} \nauthor:{} \ntotal_pages:{} \nkind:{}".format(self.name,self.author,self.totalpages,self.book_kind) def __len__(self): return self.totalpages def __del__(self): return book1=book("honey","jeny",210,"action") print(book1) print(len(book1)) del book1
eb8a3bd50ee2c2ea86afc3fcd6c8a467dc8f263f
amenson1983/2-week
/_2_week/Homework_2_week/Algoritmic_tranee_6.py
600
3.8125
4
znamen_ = int(input("Введите конечное число ряда знаменателя (целое):")) nach_chisl = int(input("Введите начальное число ряда числителя (целое):")) kon_chisl = int(input("Введите конечное число ряда числителя (целое):")) shag_chisl = int(input("Введите шаг ряда числителя (целое):")) sum_ = 0 if znamen_ > 0: for x in range(nach_chisl,kon_chisl+1,shag_chisl): sum_ += x/znamen_ znamen_ -=1 print(sum_) else: print("Zero divizion")
433dfa693d511e7b6b2ca63d1a7e88ea605dec37
jingong171/jingong-homework
/孙林轩/2017310392 孙林轩 py第二次作业/字典.py
395
3.890625
4
cities={ "Beijing":{"Country":"China","Populations":2.173e7,"fact":"Used to be called Beiping"}, "Baotou":{"Country":"China","Populations":2.8777e6,"fact":"Used to be called City of deer"}, "Shanghai": {"Country": "China", "Populations": 2.42e7, "fact": "There is a Disneyland"}, } for keys in cities: print(keys,":") for key in cities[keys]: print(cities[keys][key])
47bf2372e97f97b20d309b3f70c19af904239171
JordSter5/511
/ok.py
212
3.515625
4
response = input('Enter File: ') fhand = open(response) count = 0 for line in fhand: words = line.split() if len(words) == 0 or len(words[0:-1]) == 0 or words[0] != 'From' : continue print(words[2])
ee95bbcb558c41484cbce1a36c08dc43c8c2c7c3
kooshanfilm/Python
/Exercise/max_end3.py
332
4.34375
4
# Given an array of ints length 3, figure out which is larger, # the first or last element in the array, and set all the other elements to be that value. # Return the changed array. # def max_end3(nums): if nums[0] > nums[-1]: return [nums[0]] * 3 else: return [nums[-1]] * 3 print (max_end3([1,2,3]))
f77318b267a53148e75bf32c0d564a25c250db34
Zerl1990/python_essentials
/examples/module_1/06_inputs.py
211
4.40625
4
# Input will show a message in the console, and return what the used types # The return value can be store in a variable age = input("What is your age?") # Print the user input print("Your age is: " + age)
29c98c2f10ed618339920526dbbda23535227cb0
ReDI-School/redi-python-intro
/theory/Lesson5-Files/code/file_read_whole.py
152
3.515625
4
# Lesson5: reading all the file at once # source: code/file_read_whole.py f = open('file_for_reading.txt', 'r') text = f.read() print(text) f.close()
05fbd4a0c69570ee04cbec163a0cce43750ec648
Ryc1x/advent-of-code-2018
/day2-inventory-management-system/puzzle1.py
715
3.53125
4
def puzzle1(): f = open('input.txt', 'r') inputs = f.read().strip().split() f.close() totalrep2 = 0 totalrep3 = 0 for s in inputs: # print(s) length = len(s) rep2 = False rep3 = False for c in s: repeats = 0 for i in range(0, length): if (c == s[i]): repeats += 1 if (repeats == 2): rep2 = True if (repeats == 3): rep3 = True if (rep2): totalrep2 += 1 if (rep3): totalrep3 += 1 # print("TWO: ", totalrep2, "THREE: ", totalrep3) return totalrep2 * totalrep3 print(puzzle1())
65550b4414d2335c67158a764224fb65aebf1afa
LENAYL/pysublime
/intersection_349.py
1,602
3.59375
4
class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ # method 2 if len(nums1) == 0 or len(nums2) == 0: return [] nums1.sort() nums2.sort() l1 = len(nums1) l2 = len(nums2) i = 0 j = 0 new_list = [] while (i != l1) and j != l2: if nums1[i] < nums2[j]: i += 1 elif nums1[i] > nums2[j]: j += 1 else: new_list.append(nums1[i]) i += 1 j += 1 return new_list # method 1 # l1 = len(nums1) # l2 = len(nums2) # new_list = [] # if l1 > l2: # for i in nums2: # if i in nums1: # new_list.append(nums1.pop(nums1.index(i))) # else: # for i in nums1: # if i in nums2: # new_list.append(nums2.pop(nums2.index(i))) # return new_list # nums1 = set(nums1) # nums2 = set(nums2) # l1 = len(nums1) # l2 = len(nums2) # new_list = [] # if l1 > l2: # for i in nums1: # if i in nums2: # new_list.append(i) # else: # for i in nums2: # if i in nums1: # new_list.append(i) # return new_list s = Solution() nums1 = [1,2,2,1] nums2 = [2,2] print(s.intersection(nums1, nums2))
280be323a4400ee4df4816cc531808c8c18e6d8d
victorandradee2/Matematica-com-python
/equacao-do-2-grau.py
1,110
3.703125
4
import math equa = (' ============================== EQUAÇÃO DO 2 GRAU ==============================') cores = {'limpa':'\033[m', 'amarelo':'\033[33m'} print('{}{}{}'.format(cores['amarelo'], equa, cores['limpa'])) # OBS : O VALOR DE X É EQUIVALENTE A 1 # EXEMPLO: x² - 5x + 6 = 0 (1² - 5x + 6 = 0) = A B C # t1 = 2 t2 = 1 a = int(input('Digite o número equivalente ao "A" : ')) b = int(input('Digite o número equivalente ao "B" : ' )) c = int(input('Digite o número equivalente ao "C" : ')) # --------------------- FÓRMULA EQUAÇÃO DO SEGUNDO GRAU ------------------- # # delta: b² - 4 * a * c four_d_formula = -4 soma1 = b ** 2 soma2 = four_d_formula * (a) * (c) soma3 = soma1 + soma2 soma4 = math.sqrt(soma3) #print('{}'.format(soma4)) # --------------------- FÓRMULA DE BHÁSKARA ---------------------- # # Considere raíz quadrada: → # Considere delta: ▲ # -b ± →▲/2 * a pontoevirgula = ';' soma5 = - b + soma4 soma6 = soma5/ 2 soma7 = - b - soma4 soma8 = soma7/ 2 print('O valor de sua equação do segundo grau será de {:.0f}{}{:.0f}'.format(soma8,pontoevirgula,soma6))
8e5fbf24a8512be68a53839e51cd5fd2c4965cfc
dvdbng/tuenticontest
/c12.py
855
3.546875
4
#!/bin/env python digits = { '0':(1,3,4,5,6,7), '1':(6,7), '2':(1,2,3,5,6), '3':(1,2,3,6,7), '4':(2,4,6,7), '5':(1,2,3,4,7), '6':(1,2,3,4,5,7), '7':(1,6,7), '8':(1,2,3,4,5,6,7), '9':(1,2,3,4,5,7), } def leds(fromtime,totime): diff = [(fromtime[x],totime[x]) for x in range(len(fromtime)) if fromtime[x]!=totime[x]] total = 0 for fromd,tod in diff: total += len([1 for led in digits[tod] if led not in digits[fromd]]) return total def pad(x): return ("0"+str(x))[-2:] def seconds_to_time(seconds): return pad(((seconds/3600)%24))+pad(((seconds/60)%60))+pad((seconds%60)) def total(seconds): tot = 36 for i in xrange(1,seconds+1): tot += leds(seconds_to_time(i-1),seconds_to_time(i)) return tot import sys for line in sys.stdin: print total(int(line))
eee963a7b994ed1c0cf0d818ac31140a8fbe2873
Ayushi2811/SDP
/Ayushi/list.py
1,056
4.1875
4
#first list l={'python','c','java'} print(l) #neat list l={'python','c','java'} for i in l: print("A nice programing language is",i) #message list l={'Pink','Blue','Black','White'} for i in l: print("Item in the list is",i) #for loop l={'python','c','java'} for i in l: print(i) #working list l=['programmers','doctors','drivers','chef'] l.index('chef') if 'doctors' in l: print("Yes it is present") l.append('teacher') print(l) l.insert(0,'barber') print(l) for i in l: print(i) #starting form empty l=[] l.append('doctor') l.append('author') l.append('detective') l.append('engineer') res=[l[0],l[-1]] print(res) #ordered working list l=['programmers','doctors','drivers','chef'] print("original order:") for i in l: print(i) print("sorted list:") for i in sorted(l): print(i) print("original:") for i in l: print(i) print("Reverse:") l.reverse() for i in l: print(i) print("original") print(l) #alphabet slices l=['a','b','c','d','e','f','g','h'] print(l[0:3]) print(l[4:])
f6bdfa8402adda0cb8fe3b01fa9aa6c73f94b3b0
Hsko-Godol/Study
/python/first_book/ch12/practice12-1.py
806
3.53125
4
dc = {'새우깡': 700, '콘치즈': 850, '꼬깔콘': 750} def problem_1(): print("### The result of problem 1 ###") print("Before", dc, sep='\n') dc['홈런볼'] = 900 print('After', dc, sep='\n') def problem_2(): print("### The result of problem 2 ###") print('Before', dc, sep='\n') for i in dc: dc[i] += 100 print('After', dc, sep='\n') def problem_3(): print("### The result of problem 3 ###") print('Before', dc, sep='\n') price = dc['콘치즈'] del dc['콘치즈'] dc['치즈콘'] = price print('After', dc, sep='\n') def main(): problem_1() print("-----------------------------") problem_2() print("-----------------------------") problem_3() print("-----------------------------") main()
4222badd8fce763ed03b2499ebf8241511d988cd
rohitaswchoudhary/py_projects
/P2/gui_clock.py
411
3.59375
4
from tkinter import * from tkinter.ttk import * from time import strftime dk = Tk() dk.title("Clock") dk.minsize(width=610,height=110) dk.maxsize(width=600,height=100) label = Label(dk, font=("ds-digital",80),background="black",foreground='purple') label.pack(anchor='center') def time(): string = strftime("%H:%M:%S %p") label.config(text=string) label.after(1000,time) time() dk.mainloop()
950617f695b2a814b050aeef1900e38d2793d2d2
riodementa/Python_Michigan-University
/6_1.py
174
3.734375
4
# Exercise 6.1 import numpy as np cadena = raw_input("Introduce una cadena: ") my_length = len(cadena) while my_length>0: my_length -= 1 print cadena[my_length]
d686cb4cb1d28277713ffd6376edd2c7e7ff4bbc
Pasquale-Silv/Improving_Python
/Hacker Rank Python/QuartilesDiff.py
1,735
3.546875
4
""" n = int(input()) array = list(map(int, input().strip().split())) freq = list(map(int, input().strip().split())) """ array = [6, 12, 8, 10, 20, 16] freq = [5, 4, 3, 2, 1, 5] import statistics as st completeList = [] for i in range(len(array)): for j in range(freq[i]): completeList.append(array[i]) print(completeList) completeList.sort() print(completeList) if(len(completeList) % 2 == 0): lowerList = [completeList[i] for i in range((len(completeList) // 2))] upperList = [completeList[i] for i in range((len(completeList) // 2), len(completeList))] else: lowerList = [completeList[i] for i in range((len(completeList) // 2))] upperList = [completeList[i] for i in range((len(completeList) // 2) + 1, len(completeList))] def trovaQ(lista): lung = len(lista) q = 0 if len(lista) % 2 == 0: q = (lista[(lung // 2) - 1] + lista[(lung // 2)]) / 2 else: q = st.median(lista) return q print(lowerList) print(upperList) firstQ = trovaQ(lowerList) thirdQ = trovaQ(upperList) print(round(thirdQ - firstQ, 1)) print("-----------------------") array = [3, 4, 5] freq = [1, 2, 2] completeList = [] for i in range(len(array)): for j in range(freq[i]): completeList.append(array[i]) print(completeList) completeList.sort() print(completeList) if(len(completeList) % 2 == 0): lowerList = [completeList[i] for i in range((len(completeList) // 2))] upperList = [completeList[i] for i in range((len(completeList) // 2), len(completeList))] else: lowerList = [completeList[i] for i in range((len(completeList) // 2))] upperList = [completeList[i] for i in range((len(completeList) // 2) + 1, len(completeList))] print(lowerList) print(upperList)
7a514c80a9b3533b1f315166cda74789766330b0
scalation/data
/code/rolling_window.py
3,668
3.859375
4
import pandas as pd """ rolling_window: A module for displaying daily and weekly predictions from a dataframe on a rolling window basis Functions ---------- daily_rolling_window: def daily_rolling_window(model:str, df: pd.DataFrame, h: int = 14, date:str='date'): weekly_rolling_window: def weekly_rolling_window(model:str, df: pd.DataFrame, h: int = 4, date:str='date'): """ def daily_rolling_window(model:str, df: pd.DataFrame, h: int = 14, date:str='date') -> pd.DataFrame: """ A function used for displaying 14-days ahead predictions on a rolling window basis Arguments ---------- df: pd.DataFrame the daily forecasted data merged according to the dates h: int the future horizons model: str the name of the model date: str the date column name in the dataframe Returned Values ---------- daily: pd.DataFrame """ df.set_index(date, inplace=True) start = 0 end = h daily_pred = [] window = 0 for i in range(len(df.columns)-h): forecast_matrix_temp = df.iloc[start:end] date = forecast_matrix_temp.tail(1).index.item() l_row = forecast_matrix_temp.tail(1) daily_pred.append([date,l_row.iloc[0][window],l_row.iloc[0][window+1],l_row.iloc[0][window+2],l_row.iloc[0][window+3], l_row.iloc[0][window+4],l_row.iloc[0][window+5],l_row.iloc[0][window+6],l_row.iloc[0][window+7], l_row.iloc[0][window+8],l_row.iloc[0][window+9],l_row.iloc[0][window+10],l_row.iloc[0][window+11], l_row.iloc[0][window+12],l_row.iloc[0][window+13]]) window = window + 1 start = end end = end+1 daily_predictions = pd.DataFrame(daily_pred, columns=[ 'Date',str('day14_'+model),str('day13_'+model),str('day12_'+model),str('day11_'+model), str('day10_'+model),str('day9_'+model),str('day8_'+model),str('day7_'+model), str('day6_'+model),str('day5_'+model),str('day4_'+model),str('day3_'+model), str('day2_'+model),str('day1_'+model)]) daily_predictions['Date'] = pd.to_datetime(daily_predictions['Date']) daily = daily_predictions return daily def weekly_rolling_window(model:str ,df: pd.DataFrame, h: int = 4, date:str='date') -> pd.DataFrame: """ A function used for displaying 4-weeks ahead predictions on a rolling window basis Arguments ---------- df: pd.DataFrame the weekly forecasted data merged according to the dates h: int the future horizons model: str the name of the model Returned Values ---------- weekly: pd.DataFrame """ df.set_index(date, inplace=True) start = 0 end = h weekly_pred = [] window = 0 for i in range(len(df.columns)-h): forecast_matrix_temp = df.iloc[start:end] date = forecast_matrix_temp.tail(1).index.item() l_row = forecast_matrix_temp.tail(1) weekly_pred.append([date,l_row.iloc[0][window],l_row.iloc[0][window+1],l_row.iloc[0][window+2],l_row.iloc[0][window+3]]) window = window + 1 start = end end = end+1 weekly_predictions = pd.DataFrame(weekly_pred, columns=[ 'Date',str('week4_'+model),str('week3_'+model),str('week2_'+model), str('week1_'+model)]) weekly_predictions['Date'] = pd.to_datetime(weekly_predictions['Date']) weekly = weekly_predictions return weekly
31248d27c5afda5b6bde79bf212aba6acd9decb6
ArthurBrito1/MY-SCRIPTS-PYTHON
/Desafios/desafio13.py
240
3.671875
4
temperatura = int(input('informe a temperatura em graus celcius:')) converssão = (temperatura*9/5)+32 print('A temperatura em graus celcius é de {}C \nApós de ser convertida para fharenheit fica {}F'.format(temperatura, converssão))
309928b0e1c9e2c5e85e43b4dec27e6f62c03ac4
stay5sec/bibi_code
/other/Record/多线程/5.0 进程间通信.py
2,934
3.609375
4
# coding:utf-8 # author:Super # 多进程编程中不能再使用线程中的queue '''from queue import Queue''' import time from multiprocessing import Process, Queue, Pool '''参数共享的方式''' # def pro(queue): # queue.put("a") # time.sleep(2) # # # def con(queue): # time.sleep(2) # data = queue.get() # print(data) # # # if __name__ == "__main__": # queue = Queue() # my_producer = Process(target=pro, args=(queue,)) # my_consumer = Process(target=con, args=(queue,)) # # my_producer.start() # my_consumer.start() # # my_producer.join() # my_consumer.join() '''共享全局变量''' # # def pro(a): # a += 1 # time.sleep(2) # # # def con(a): # time.sleep(2) # print(a) # # # if __name__ == "__main__": # a = 1 # my_producer = Process(target=pro, args=(a,)) # my_consumer = Process(target=con, args=(a,)) # # my_producer.start() # my_consumer.start() # # my_producer.join() # my_consumer.join() # # # 输出结果仍然是1:多进程中不能使用共享全局变量 '''multiprocessing中的queue不能用于pool进程池通信''' # def pro(queue): # queue.put("a") # time.sleep(2) # # # def con(queue): # time.sleep(2) # data = queue.get() # print(data) # if __name__ == "__main__": # queue = Queue() # # pool = Pool(2) # # pool.apply_async(pro, args=(queue,)) # pool.apply_async(con, args=(queue,)) # # pool.close() # pool.join() # # # 输出为空,多进程这个queue通信失效了 '''使用manager中的queue进行通信''' # from multiprocessing import Manager # # if __name__ == "__main__": # queue = Manager().Queue() # # pool = Pool(2) # # pool.apply_async(pro, args=(queue,)) # pool.apply_async(con, args=(queue,)) # # pool.close() # pool.join() # # # 输出结果为“a” '''通过pipe进行进程间的通信''' # from multiprocessing import Pipe # # def pro(pipe): # pipe.send("a") # # def con(pipe): # print(pipe.recv()) # # if __name__ == "__main__": # rece, send = Pipe() # # # Pipe的参数传入函数 # my_producer = Process(target=pro, args=(send,)) # my_consumer = Process(target=con, args=(rece,)) # # my_producer.start() # my_consumer.start() # # my_producer.join() # my_consumer.join() # # # Pipe的性能,是高于queue的 '''使用全局变量进行进程通信''' from multiprocessing import Manager def add_data(dict1, k, v): dict1[k] = v if __name__ == "__main__": pro_dict = Manager().dict() one = Process(target=add_data, args=(pro_dict, "a", 1)) two = Process(target=add_data, args=(pro_dict, "b", 2)) one.start() two.start() one.join() two.join() print(pro_dict)
c502687062ab89754f1d89a4549890305168497c
Gowtham-M1729/HackerearthPrograms
/python/basics.py
91
3.515625
4
lett="" lst=list() for i in range(7): lst.append('b') print(lst) print(lett.join(lst))
6824853ea85146f8b7fd8e9c1fb1658fe8169b11
FouedDadi/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
374
3.984375
4
#!/usr/bin/python3 """ function that read defined lines """ def read_lines(filename="", nb_lines=0): """ handle conditions of reading lines """ number = 0 with open(filename, encoding="UTF8") as myfile: for line in myfile: number = number + 1 if nb_lines <= 0 or nb_lines >= number: print(line, end="")
c4db7b0b83cd8439dd205f9cdc360958b42db899
MaxNollet/j2_blk4_eindopdracht_flask
/gaps/genelogic/genepanelreader.py
11,206
3.625
4
from dataclasses import dataclass, field from os import path from re import compile, Pattern from typing import List, Tuple, Dict @dataclass class GenepanelContent: """A class used for storing values. The stored values can be used to fill a database and the class can be used by readers/parsers to store values in a nice and structured way. """ all_genes: List[dict] = field(default_factory=list) all_aliases: List[dict] = field(default_factory=list) all_genepanel_symbols: List[dict] = field(default_factory=list) all_genepanels: List[dict] = field(default_factory=list) all_inheritace_types: List[dict] = field(default_factory=list) relation_gene_alias: List[dict] = field(default_factory=list) relation_gene_genepanel: List[dict] = field(default_factory=list) relation_genepanel_inheritance: List[dict] = field(default_factory=list) class GenepanelReader: """A class which has logic to read a file containing genepanel-data. The data read from the file will be made available in a GenepanelContent-object so other functions/methods can access values in a structured way. """ _delimiter: str = "\t" _column_names: Tuple[str] = ("GeneID_NCBI", "Symbol_HGNC", "Aliases", "GenePanels_Symbol", "GenePanel") _table_names = {"alias", "gene", "genepanel", "genepanel_symbol", "inheritance_type"} _pattern_inheritance_fix: Pattern = compile(r"(?<=[a-zA-Z0-9]);(?=[a-zA-Z0-9])") _pattern_find_genepanel_abbreviation: Pattern = compile(r"[a-zA-Z]+?(?=\s)") _pattern_find_inheritance_types: Pattern = compile(r"(?<=\()(.+?)(?=\))") _pattern_variable_splitter: Pattern = compile(r"\W+") def __init__(self, filename: str = None, auto_read: bool = True) -> None: """Constructor of the object, initializes a cache, saves a filename if given and starts automatically reading a file when prompted to. :param filename Name of the file to read (str). :param auto_read Start automatically reading a file or not (bool). """ self._column_indexes: Dict[str, int] = dict() self._cached_values: Dict[str, set] = dict() self._data: GenepanelContent = GenepanelContent() self._filename: str = str() for table_name in self._table_names: self._cached_values[table_name] = set() if filename: self.set_filename(filename) if auto_read and self._filename is not None: self.read_file() def read_file(self, filename: str = None) -> None: """A method which reads a file containing data of genepanels. When done, all values are stored in a GenepanelContent- object which is available through the get_genepanel_data- method. :param filename Name of the file to read (str). """ if filename: self.set_filename(filename) with open(self._filename, "r", encoding="UTF-8") as file: # Skip empty head of file if applicable. line = file.readline().strip() while line == "": line = file.readline().strip() self._get_column_indexes(line) # Extract values from the rest of the file. for line in file: stripped_line = line.strip() if stripped_line != "": values = stripped_line.split(self._delimiter) genepanel_symbol = self._extract_genepanel_symbol(values) gene_symbol = self._extract_gene(values, genepanel_symbol) self._extract_aliases(values, gene_symbol) self._extract_genepanels(values, gene_symbol) def _get_column_indexes(self, line: str) -> None: """A method which column indexes of column names. These indexes are used when extracting values from desired columns. :param line First line of the file containing column names (str). """ values = line.strip().split(self._delimiter) for column_name in self._column_names: try: self._column_indexes[column_name] = values.index(column_name) except ValueError: raise GenepanelColumnNotFound(column_name) return None def _extract_genepanel_symbol(self, values: List[str]) -> str: """A method which extracts the symbol which is used to display the gene for a certain genepanel. :param values One row of all columns from the file (List[str]). :return Symbol used for displaying the gene in a certain genepanel (str). """ genepanel_symbol = values[self._column_indexes["GenePanels_Symbol"]].strip() cache = self._cached_values["genepanel_symbol"] if genepanel_symbol != "" and genepanel_symbol not in cache: cache.add(genepanel_symbol) self._data.all_genepanel_symbols.append({"symbol": genepanel_symbol}) return genepanel_symbol def _extract_gene(self, values: List[str], genepanel_symbol: str) -> str: """A method which extracts all values needed for inserting a gene into the database. :param values One row of all columns from the file (List[str]). :param genepanel_symbol Symbol of the genepanel (str). :return Symbol of the gene (str). """ gene_symbol = values[self._column_indexes["Symbol_HGNC"]].strip() cache = self._cached_values["gene"] if gene_symbol not in cache: cache.add(gene_symbol) gene_id = values[self._column_indexes["GeneID_NCBI"]].strip() self._data.all_genes.append({"ncbi_gene_id": gene_id, "hgnc_symbol": gene_symbol, "genepanel_symbol_id": genepanel_symbol, "in_genepanel": True}) return gene_symbol def _extract_aliases(self, values: List[str], gene_symbol: str) -> None: """A method which extracts all aliases which belong to a specific gene. :param values One row of all columns from the file (List[str]). :param gene_symbol Symbol of the gene which these aliases belong to (str). """ aliases = values[self._column_indexes["Aliases"]].strip() cache = self._cached_values["alias"] if aliases != "": if "|" in aliases: for value in aliases.split("|"): alias = value.strip() if alias != "" and alias not in cache: cache.add(alias) self._data.all_aliases.append({"hgnc_symbol": alias}) self._data.relation_gene_alias.append({"alias_id": alias, "gene_id": gene_symbol}) else: if aliases not in cache: cache.add(aliases) self._data.all_aliases.append({"hgnc_symbol": aliases}) self._data.relation_gene_alias.append({"alias_id": aliases, "gene_id": gene_symbol}) return None def _extract_genepanels(self, values: List[str], gene_symbol: str) -> None: """A method which extracts all genepanels with all inheritance types where a specific gene belongs in. :param values One row of all columns from the file (List[str]). :param gene_symbol Symbol of the gene which these genepanels belong to (str). """ genepanels = values[self._column_indexes["GenePanel"]].strip() cache_genepanel = self._cached_values["genepanel"] cache_inheritance = self._cached_values["inheritance_type"] if genepanels != "": print(genepanels) line_fix = self._fix_delimeter_inconsistency(genepanels) for value in line_fix.split(";"): genepanel = self._pattern_find_genepanel_abbreviation.findall(value)[0] if genepanel != "" and genepanel not in cache_genepanel: cache_genepanel.add(genepanel) self._data.all_genepanels.append({"abbreviation": genepanel}) inheritance_types = self._pattern_find_inheritance_types.findall(value)[0] if inheritance_types != "" and genepanel != "": for inheritance in self._pattern_variable_splitter.split(inheritance_types): if inheritance != "" and inheritance not in cache_inheritance: cache_inheritance.add(inheritance) self._data.all_inheritace_types.append({"type": inheritance}) self._data.relation_genepanel_inheritance.append({"genepanel_id": genepanel, "inheritance_type_id": inheritance}) self._data.relation_gene_genepanel.append({"genepanel_id": genepanel, "gene_id": gene_symbol}) return None @classmethod def _fix_delimeter_inconsistency(cls, values: str): """A method which cleans up human-inconsistencies when specifying inheritance types for genepanels. All inheritance types are delimited by a comma-sign (,) but sometimes a semicolon (;) is used. This messes with the way genepanel abbreviations can be distinguished from one and another. :param values Column containing genepanel abbreviations with inheritance-types to fix (str). :return Fixed-up values (str). """ return cls._pattern_inheritance_fix.sub(",", values) def set_filename(self, filename: str) -> None: """A method which validates a filename and saves the filename for later uses when reading the file. :param filename Name of the file to read (str). :raises FileNotFoundError If the file can't be found. """ filename = filename.strip() if path.exists(filename): self._filename = filename else: raise FileNotFoundError return None def get_genepanel_data(self) -> GenepanelContent: """A method used to retrieve the read values from a file with genepanel-information. :return All read values from a genepanel-file (GenepanelContent). """ return self._data class GenepanelColumnNotFound(Exception): """An exception when a specific column cannot be found in the file that had been uploaded by the user. Instead of providing a 'ValueError' this custom exception aims to help specify which column is missing from the file. """ def __init__(self, column_name: str): super().__init__(f"The column '{column_name}' was not found in the file " f"that had been uploaded! Could not update genepanels.")
422d307a46aa55e955671f973c1858d23aaac944
haya14busa/codeforces
/div2/312/a.py
1,309
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Lala Land has exactly n apple trees Tree number i is located in a position xi and has ai apples growing on it Obj: wants to collect apples from the apple trees Start: Amr currently stands in x = 0 position ''' def solve(n, xas): minus = sorted([xa for xa in xas if xa[0] < 0]) minus_len = len(minus) plus = sorted([xa for xa in xas if xa[0] > 0]) plus_len = len(plus) d = abs(minus_len - plus_len) if d < 2: pass elif minus_len < plus_len: plus = plus[:-(d - 1)] else: minus = minus[d - 1:] return sum(map(lambda x: x[1], minus)) + sum(map(lambda x: x[1], plus)) def getinput(): def getints_line(): return list(map(int, input().split(' '))) n = int(input()) xas = [getints_line() for _ in range(n)] return n, xas def test(): # print(solve(2, [[-1, 5], [1, 5]])) # print(solve(3, [[-2, 2], [1, 4], [-1, 3]])) # print(solve(3, [[1, 9], [3, 5], [7, 10]])) assert solve(2, [[-1, 5], [1, 5]]) == 10 assert solve(3, [[-2, 2], [1, 4], [-1, 3]]) == 9 assert solve(3, [[1, 9], [3, 5], [7, 10]]) == 9 def main(): # test() print(solve(*getinput())) # print('\n'.join(map(str, solve(*getinput())))) if __name__ == '__main__': main()
a6adfa4021acdb324bceb06b0b6f2846e9495417
jaydendrj/gnistudy
/从入门到实践/9类/Car.py
1,685
3.921875
4
class Car(): def __init__(self,make,model,year): self.make=make self.model=model self.year=year self.odometer_reading = 0 def get_descriptive_name(self): long_name=str(self.year)+" "+self.make+' '+self.model return long_name def read_odometer(self): print('This car has '+str(self.odometer_reading)+' miles on it.') def update_odometer(self,mileage): if mileage<self.odometer_reading: print('You can\'t roll back an odometer!') else: self.odometer_reading=mileage def increment_odometer(self,miles): if miles<0: print('You can\'t roll back an odometer!') else: self.odometer_reading+=miles class Battery(): def __init__(self, battery_siz=70): self.battery_size = battery_siz def describe_battery(self): print("This car has a " + str(self.battery_size) + "-Kwh battery.") class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) self.battery=Battery() def fill_gas_tank(self): print('This car doesn\'t need a gas tank!') mytesla=ElectricCar('tesla',"model s",2016) print(mytesla.get_descriptive_name()) mytesla.describe_battery() # my_new_car=Car('audi','a4',2019) # print(my_new_car.get_descriptive_name()) # # my_new_car.odometer_reading=23 # my_new_car.read_odometer() # # my_new_car.update_odometer(90) # my_new_car.read_odometer() # # my_new_car.update_odometer(10) # my_new_car.read_odometer() my_use_car=Car('used','motor',2012) my_use_car.increment_odometer(90) my_use_car.read_odometer()
f60a3bce7ecd964db460e3286c4a9b1d1c67a722
Andxre/Daily-Code-Log
/LinkedList.py
1,228
3.90625
4
''' 1/17/2020 Simple Linked List implementation in python~ ''' class Node(): def __init__(self, val): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None def add(self, data): node = Node(data) if (self.head == None): self.head = node else: tmp = self.head while (tmp.next != None): tmp = tmp.next tmp.next = node def remove(self, data): if (self.head == None): return temp = self.head prev = None while (temp.val != data): prev = temp temp = temp.next if (temp.val == None): return else: prev.next = temp.next def print(self): if (self.head == None): print("The list is empty") return tmp = self.head while (tmp != None): print(tmp.val, end=" ") tmp = tmp.next print("\n") def main(): ll = LinkedList() for i in range(1, 10): ll.add(i) ll.print() ll.remove(2) ll.remove(3) ll.print() main()
dbae721f4d15cc9909c350e15a0ca692877e26e9
ElSnoMan/auto-engineering-101
/chapters/ch4/vowel_count.py
213
3.78125
4
# 3. Refactored logic from test def count_vowels_in_string(string): vowels = 'aeiou' count = 0 for character in string.lower(): if character in vowels: count += 1 return count
2d9d1279bdea37be71b33c52eb84494c79adcf59
rec/test
/python/multi.py
230
3.515625
4
class Multi(object): ITEMS = (1, 3), (5, 8) def __getitem__(self, i): return self.ITEMS[i[0]][i[1]] def __setitem__(self, i, x): self.ITEMS[i[0]][i[1]] = x def __len__(self): return 2, 2
d7030a0c34426c8a48b88c51adfa66f63e210fbd
QuentinDevPython/McGyver2.0
/mcgyver/game.py
8,414
3.6875
4
""" Import the time Import the module 'pygame' for writing video games Import the other classes 'Maze' and 'Player' to manage the all game Import the file 'config' for the constants. """ import time import pygame from mcgyver.maze import Maze from mcgyver.player import Player import config class Game: """class that initiates the game of the maze, updates it according to each action of the player and graphically displays the game. """ def __init__(self): """function that instantiates the class "Game" by loading and resizing the images of the game, defines the width and height of the maze and initializes the grid and the player. """ self.maze = Maze() self.player = Player(self) self.width = config.GAME_WIDTH self.length = config.GAME_HEIGHT self.dimension = config.GAME_SQUARE_DIMENSION self.wall_image = pygame.image.load( 'mcgyver/assets/background/wall.png') self.wall_image = pygame.transform.scale( self.wall_image, (self.dimension, self.dimension)) self.floor_image = pygame.image.load( 'mcgyver/assets/background/floor.png') self.floor_image = pygame.transform.scale( self.floor_image, (self.dimension, self.dimension)) self.player_image = pygame.image.load( 'mcgyver/assets/characters/mac_gyver.png') self.player_image = pygame.transform.scale( self.player_image, (self.dimension-3, self.dimension-3)) self.end_image = pygame.image.load( 'mcgyver/assets/background/end.png') self.end_image = pygame.transform.scale( self.end_image, (self.dimension, self.dimension)) self.guardian_image = pygame.image.load( 'mcgyver/assets/characters/guardian.png') self.guardian_image = pygame.transform.scale( self.guardian_image, (self.dimension-2, self.dimension-2)) self.ether_image = pygame.image.load('mcgyver/assets/items/ether.png') self.needle_image = pygame.image.load( 'mcgyver/assets/items/needle.png') self.plastic_tube_image = pygame.image.load( 'mcgyver/assets/items/plastic_tube.png') self.syringe_image = pygame.image.load( 'mcgyver/assets/items/syringe.png') self.win = pygame.image.load( 'mcgyver/assets/finish_game/win.png') self.win = pygame.transform.scale(self.win, (200, 200)) self.defeat = pygame.image.load( 'mcgyver/assets/finish_game/defeat.png') self.defeat = pygame.transform.scale(self.defeat, (200, 200)) def run_game(self): """function that launches the game window and follows the player’s actions.""" pygame.init() # define the dimensions of the game window number_squares = self.width size_squares = self.dimension screen_size = (number_squares * size_squares, number_squares * size_squares) # generate the game window screen = pygame.display.set_mode(screen_size) pygame.display.set_caption('Escape from the maze') pygame.font.init() myfont = pygame.font.Font(None, 24) self.maze.create_maze(self.width, self.length) self.maze.define_item_square(self.length) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT and self.player.can_move_right(): self.player.move_right() elif event.key == pygame.K_LEFT and self.player.can_move_left(): self.player.move_left() elif event.key == pygame.K_UP and self.player.can_move_up(): self.player.move_up() elif event.key == pygame.K_DOWN and self.player.can_move_down(): self.player.move_down() self.player.take_item() text_items_taken = ( 'You have taken {}/4 items'.format(self.player.number_items_taken)) text = myfont.render(text_items_taken, 1, (255, 255, 255)) self.__update_map(screen, text) running = self.player.is_victorious()[0] if not running: time.sleep(3) def __update_map(self, screen, text): """function that graphically displays the elements of the maze and that updates it with each action of the player. """ map_printed = '' map_in_window = self.maze.create_maze_map( map_printed, self.width, self.length) map_in_window = map_in_window.split(' ') index = 0 for line_maze in range(self.width): for column_maze in range(self.length): if (line_maze, column_maze) != (0, 0): index += 1 if map_in_window[index] == '#': screen.blit(self.wall_image, (column_maze * self.dimension, line_maze * self.dimension)) elif map_in_window[index] == 'x': screen.blit(self.floor_image, (column_maze * self.dimension, line_maze * self.dimension)) screen.blit(self.player_image, (column_maze * self.dimension, line_maze * self.dimension)) elif map_in_window[index] == 'a': screen.blit(self.end_image, (column_maze * self.dimension, line_maze * self.dimension)) screen.blit(self.guardian_image, (column_maze * self.dimension, line_maze * self.dimension)) else: screen.blit(self.floor_image, (column_maze * self.dimension, line_maze * self.dimension)) if map_in_window[index] == 'e': screen.blit(self.ether_image, (column_maze * self.dimension, line_maze * self.dimension)) elif map_in_window[index] == 'n': screen.blit(self.needle_image, (column_maze * self.dimension, line_maze * self.dimension)) elif map_in_window[index] == 'p': screen.blit(self.plastic_tube_image, (column_maze * self.dimension, line_maze * self.dimension)) elif map_in_window[index] == 's': screen.blit(self.syringe_image, (column_maze * self.dimension, line_maze * self.dimension)) screen.blit(text, (20, 10)) if self.player.is_victorious()[1] == 1: screen.blit(self.win, ((self.width * self.dimension) / 3, (self.length * self.dimension)/3)) elif self.player.is_victorious()[1] == 0: screen.blit(self.defeat, ((self.width * self.dimension) / 3, (self.length * self.dimension)/3)) pygame.display.flip() """ # for console game while running: map_printed = '' self.maze.create_maze_map(map_printed, self.width, self.length) bool_direction = False while not bool_direction: direction = input( 'Where do you want to go ? (Q,Z,D,S)') if direction == 'Q' and self.player.can_move_left(): self.player.move_left() bool_direction = True elif direction == 'D' and self.player.can_move_right(): self.player.move_right() bool_direction = True elif direction == 'Z' and self.player.can_move_up(): self.player.move_up() bool_direction = True elif direction == 'S' and self.player.can_move_down(): self.player.move_down() bool_direction = True """
0af87e3cbf29ca61261f733f0ef85213b0fd577b
krishnabojha/Insight_workshop_Assignment3
/Question4.py
175
4.125
4
########## swape first two character of two string a,b=input("Enter two string separated by space : ").split() print("Output : '{}'" .format((b[:2]+a[2:])+' '+(a[:2]+b[2:])))
cd5adf8834d7784dfa612adc82759089063d7020
vishalsood114/pythonprograms
/command0.py
324
3.515625
4
def command(f): def g(filename): lines = read_lines(filename) lines = [f(line) for line in lines] print_lines(lines) return g def read_lines(filenames): return (line for f in filenames for line in open(f)) def print_lines(lines): for line in lines: print line.strip("\n")
251d732a012a96c171ea96b4be21f0ec1d9b63c1
roberto-uquillas/Python-EPN
/06_while-loop.1.py
224
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 19 12:52:45 2019 @author: CEC """ x=input("Enter a number to count to: ") x=int(x) y=1 while y<=x: print(y) y=y+1 if y>x: break
5b3234d123c22a1671c7849b3bfbba8ca427df96
JP9527/Road-to-Dev
/linghu-algorithm-templete-master/令狐老师的算法小抄/sorting.py
2,249
3.796875
4
# sorting # 时间复杂度: # 快速排序(期望复杂度) : O(nlogn) # 归并排序(最坏复杂度) : O(nlogn) # # 空间复杂度: # 快速排序: O(1) # 归并排序: O(n) # quick sort class Solution: def sortIntegers(self, A): self.quickSort(A, 0, len(A)-1) def quickSort(self, A, start, end): if start >= end: return left, right = start, end # pivot is a value not index pivot = A[(start+end)//2] # always left <= right while left <= right: while left <= right and A[left] < pivot: left += 1 while left <= right and A[right] > pivot: right -= 1 if left <= right: A[left], A[right] = A[right], A[left] left += 1 right -= 1 self.quickSort(A, start, right) self.quickSort(A, left, end) # merge sort class Solution2: def sortIntegers(self, A): if not A: return A temp = [0] * len(A) self.merge_sort(A, 0, len(A) - 1, temp) def merge_sort(self, A, start, end, temp): if start >= end: return # left half self.merge_sort(A, start, (start+end)//2, temp) # right half self.merge_sort(A, (start+end)//2+1, end, temp) self.merge(A, start, end, temp) def merge(self, A, start, end, temp): middle = (start+end)//2 left_index = start right_index = middle + 1 index = start while left_index <= middle and right_index <= end: if A[left_index] < A[right_index]: temp[index] = A[left_index] index += 1 left_index += 1 else: temp[index] = A[right_index] index += 1 right_index += 1 while left_index <= middle: temp[index] = A[left_index] index += 1 left_index += 1 while right_index <= end: temp[index] = A[right_index] index += 1 right_index += 1 for i in range(start, end+1): A[i] = temp[i]
a0bc499b3a79acef38d684cde119ccba103dd57c
kstdnl/AaDS_1_184_2021
/1.revise1.py
2,537
3.890625
4
#TASK 1 count = 0 text = "The tiger once ranged widely from the Eastern Anatolia Region in the west to the Amur River basin, and in the south from the foothills of the Himalayas to Bali in the Sunda islands." for i in text: if i == 's' or i == 'a': count += 1 print(count) #TASK 2 from math import * def calc(l): T = 2*pi*sqrt(l/9.8) print(round(T,2)) print("Введите длину математического маятника:") calc(int(input())) #TASK 3 print("1 is for +, 2 is for -, 3 is for *, 4 is for /, 5 is for **") def Calculator(a,x,y): if a == 1: res = x + y print(res) elif a == 2: res = x - y print(res) elif a == 3: res = x * y print(res) elif a == 4 and y != 0: res = x / y print(res) elif a == 5: res = x ** y print (res) else: print("sorry, you put not correct number of operation") a = int(input("Put the number of operation: ")) Calculator(a, int(input("X =" )), int(input("Y =" ))) #TASK 4 from math import * def calc(p, m, n): return p*pow((1+(15/100/(m/12))), m/(12*n)) p = int(input("P =")) m = int(input("m =")) n = int(input("n =")) print(calc(p, m, n)) #TASK 5 from math import * def calc(k): mult = 1 for n in range(k): mult = mult * ((n+pow(3, n))/(n+pow(5, 2*n))) print(mult) calc(int(input("Введите k = "))) #TASK 6 def Func(start, end): sum = 0 numbers = list(range(x,y)) for i in numbers: if i%2 == 1: sum+=i return sum x = int(input("От ")) y = int(input("До ")) print(Func(x, y)) #TASK 7 from math import sqrt def calc(x,y,z): D = y**2 - 4*x*z if D > 0 and x!= 0: f1 = (-y + sqrt(D))/2*x f2 = (-y - sqrt(D))/2*x print(round(f1,2)) print(round(f2,2)) elif D == 0 and x!= 0: f1 = (-y)/2*x print(f1) elif D < 0: print("нет решений") else: print("ошибка") print("Введите x, y, z") calc(int(input()),int(input()),int(input())) #TASK 8 number = int(input('Введите число: ')) if (number > 99999) and (number < 1000000): while True: count = number % 10 number = number // 10 if count: break while number: x = number % 10 if x: count *= x number = number // 10 print(count) else: print('error')
71fa5357f20a76e77d0fd61622ca8841fda4fad5
moshegplay/moshegplay
/lessons_1/targil6.1.py
183
3.984375
4
if 4 or 5>7: print("good") else: print("bad") if (5+3) > 10 and"man" in "mama" or 100 != 3 and 90<91: print("fa") elif true is false: pass else: print("else")
783c9d8f752320c688c667fce0f956c37a75b0d1
finstalex/blackjack---python
/game.py
1,001
3.75
4
koloda = [6,7,8,9,10,2,3,4,11] * 4 import random random.shuffle(koloda) name=input(str("Введите Ваше имя : ")) print("Поиграем в Блекджек "+name+"?") print ("Правила игры: Нужно набрать 21 очко") count = 0 while True: choice = input("Будете брать карту? да/нет\n") if choice == "да": current = koloda.pop() print("Вам попалась карта достоинством %d" %current) count += current if count > 21: print("Извините "+name, "но вы проиграли") break elif count == 21: print("Поздравляю "+name , "вы набрали 21!") break else: print(name+" у вас %d очков." %count) elif choice == 'нет': print(name+" у вас %d очков и вы закончили игру." %count) break print("До новых встреч!")
7cdb3422d7c78aa6dcf5fc9e4916d349a7b91b6d
rishiDholliwar/WorkoutApp
/WorkoutAnalyzer/generate-model-data.py
2,090
3.546875
4
import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt from statsmodels.nonparametric.smoothers_lowess import lowess import os """ This program creates a csv file called exercise-model-data.csv for the workout app to use to train its model. exercise-model-data.csv contains 2 columns. The first is action which contains exercises like walk and the second is t_max_avg which is the highest 5 aT (m/s^2) values averaged for the action. """ """ This function appends the actions and the t_max_avg to exercise-model-data.csv """ def create_exercise_data(inputFiles,exercises_df): for file in inputFiles: #print("Processing: ", file.name) df = pd.read_csv(file) t_max_avg = df.nlargest(5, 'aT (m/s^2)') t_max_avg = t_max_avg['aT (m/s^2)'].mean() file = os.path.basename(file.name) file = ''.join([i for i in file if not i.isdigit()]) action = file[:-4] exercises_df = exercises_df.append({'action': action, 't_max_avg': t_max_avg} , ignore_index=True) return exercises_df """ Function reads in a folder containing the data files for accelerometer data generated by Physics Toolbox Sensor Suite and returns them in a list """ def readFiles(): path = "rawData/" inputFiles = [] for filename in os.listdir(path): #print(filename) file = path + filename inputFiles.append(open(file)) return inputFiles def main(): inputFiles = readFiles() exercises_df = pd.DataFrame(columns=['action', 't_max_avg']) exercises_df = create_exercise_data(inputFiles, exercises_df) #print(exercises_df.groupby(['action']).agg([('average','mean')]),"\n") print("exercise-model-data.csv created") exercises_df.to_csv("exercise-model-data.csv", index=False) if __name__=='__main__': main()
6e1ad785a952612ba16702d4921a9240dabd960e
CaMeLCa5e/Dailyfall2015
/test.py
313
3.734375
4
# x = ["5","A","B","C","D","F","A-B","A-C","B-C","C-D","D-F"] x = [ e.strip('"') for e in raw_input().split(',')] # string_input = [c.strip(',').strip("'") for c in raw_input('Enter something: ').split(',')] # string_input = [c.strip(',').strip('"') for c in raw_input('Please enter values').split()] print x
ede5910efc883cb889451dc28ac162105044a10d
GyeongMukLee/Programming-in-Python
/Chapter07-2/2_tuple/tuple-01.py
699
3.625
4
print("\n1. 샘플 튜플 출력") sampleTuple = (4, 3, 9, 1, 3, 6, 3, 3) print(" sampleTuple= ", sampleTuple) print("\n2. 샘플 튜플의 한 요소의 값의 위치") print(" sampleTuple= ", sampleTuple) print(" sampleTuple.index(4) = ", sampleTuple.index(4)) print(" sampleTuple.index(3) = ", sampleTuple.index(3)) print(" sampleTuple.index(1) = ", sampleTuple.index(1)) # 없는 요소의 값의 위치를 찾고자 할때는 오류(valueError)를 일으킴. 즉, # print(" sampleTuple.index(2) = ", sampleTuple.index(2)) print("\n3. 샘플 튜플의 갯수 카운트( len(샘플튜플) )") print(" sampleTuple= ", sampleTuple) print(" len(sampleTuple) = ", len(sampleTuple))
d5ecfd28acc25800c5e0393109c2dcccf42a0860
yy642/Trumps-Tweets
/ERM.py
5,011
3.640625
4
import numpy as np def ridge(w,xTr,yTr,lmbda): """ INPUT: w : d dimensional weight vector xTr : nxd dimensional matrix (each row is an input vector) yTr : n dimensional vector (each entry is a label) lmbda : regression constant (scalar) OUTPUTS: loss : the total loss obtained with w on xTr and yTr (scalar) gradient : d dimensional gradient at w DERIVATION: Let w, y and gradient g(w) all be column vectors. l(w) = (1/n) (X w - y)^T (X w - y) + lmbda w^T w g(w) = (1/n) X^T (X w - y) + (1/n) ((X w - y)^T X)^T + lmbda w + lmbda (w^T)^T = (1/n) X^T (X w - y) + (1/n) X^T (X w - y) + 2 lmbda w = (2/n) X^T (X w - y) + 2 lmbda w g(w) = 2 ( X^T (X w - y) / n + lmbda w ), where lmbda = sigma^2/(n tau^2) """ n, d = xTr.shape diff = np.dot(xTr, w)-yTr loss = np.dot(diff, diff) / n + lmbda * np.dot(w,w) #assuming lmbda means sigma^2/tau^2 g = 2 * (np.dot(diff, xTr) / n + lmbda * w) return loss, g def logistic(w,xTr,yTr): """ INPUT: w : d dimensional weight vector xTr : nxd dimensional matrix (each row is an input vector) yTr : n dimensional vector (each entry is a label) OUTPUTS: loss : the total loss obtained with w on xTr and yTr (scalar) gradient : d dimensional gradient at w DERIVATION: xi is treated as a row vector below: l(w) = log(1 + exp(-yi xi w)) summed over i g(w) = -( (yi exp(-yi xi w)) / (1 + exp(-yi xi w)) ) xi^T summed over i = -( yi / (exp(yi xi w) + 1) ) xi^T summed over i """ n, d = xTr.shape yxw = np.dot(xTr, w) * yTr loss = np.sum( np.log(1 + np.exp(- yxw)) ) g = - np.sum( (yTr / (np.exp(yxw) + 1)).reshape(n, 1) * xTr, axis=0 ) return loss, g def hinge(w,xTr,yTr,lmbda): """ INPUT: w : d dimensional weight vector xTr : nxd dimensional matrix (each row is an input vector) yTr : n dimensional vector (each entry is a label) lmbda : regression constant (scalar) OUTPUTS: loss : the total loss obtained with w on xTr and yTr (scalar) gradient : d dimensional gradient at w DERIVATION: xi is treated as a row vector below: l(w) = max(1 - yi xi w, 0) summed over i + lmbda w^T w g(w) = fi(w) summed over i + 2 lmbda w, where if 1 - yi xi w > 0, then fi(w) = - yi xi^T else fi(w) = 0 """ n, d = xTr.shape yxw = np.dot(xTr, w) * yTr loss = np.sum( np.maximum(1 - yxw, 0) ) + lmbda * np.dot(w, w) f = - yTr.reshape(n,1) * xTr g = np.sum( f[1 - yxw > 0], axis=0 ) + 2 * lmbda * w return loss, g def adagrad(func,w,alpha,maxiter,eps,delta=1e-02): """ INPUT: func : function to minimize (loss, gradient = func(w)) w : d dimensional initial weight vector alpha : initial gradient descent stepsize (scalar) maxiter : maximum amount of iterations (scalar) eps : epsilon value delta : if norm(gradient)<delta, it quits (scalar) OUTPUTS: w : d dimensional final weight vector losses : vector containing loss at each iteration """ losses = np.zeros(maxiter) d = len(w) z = np.zeros(d) for i in range(maxiter): loss, g = func(w) losses[i] = loss if np.linalg.norm(g) < delta: break z += g * g w -= alpha * g / np.sqrt(z + eps) return w, losses def ERM_classifier(xTr, yTr, lmbda, lossType='hinge'): """ INPUT: xTr : nxd dimensional matrix (each row is an input vector) yTr : n dimensional vector (each entry is a label) lmbda : regression constant (scalar) lossType : type of loss: 'ridge' | 'logistic' | 'hinge' OUTPUTS: classifier (usage: preds = classifier(xTe)) """ if lossType == 'ridge': objective = lambda weight: ridge(weight, xTr, yTr, lmbda) elif lossType == 'logistic': objective = lambda weight: logistic(weight, xTr, yTr) elif lossType == 'hinge': objective = lambda weight: hinge(weight, xTr, yTr, lmbda) else: raise NotImplementedError _, d = xTr.shape eps = 1e-06 w, losses = adagrad(objective, np.random.rand(d), 1, 1000, eps) return ( lambda xTe: np.sign(np.dot(xTe, w)) ) def bagging(xTr, yTr, lmbda, lossType, m): """ INPUT: m: number of classifiers in the bag """ n, d = xTr.shape bag = [] for i in range(m): random_idx = np.random.randint(0,n,size=2 * n) xD = xTr[random_idx] yD = yTr[random_idx] h = ERM_classifier(xD, yD, lmbda, lossType) bag.append(h) return bag def evalbag(bag, xTe, alphas=None): m = len(bag) if alphas is None: alphas = np.ones(m) / m pred = np.zeros(xTe.shape[0]) for i in range(m): pred += alphas[i] * bag[i](xTe) return pred
5cd54160d59ce9a19a661a8fd2d4b02d5f89e8ea
lincolnjohnny/py4e
/2_Python_Data_Structures/Week_4/example_04.py
133
3.6875
4
# Lists can be sliced using ":" t = [0, 1, 2, 3 , 4, 5, 6, 7, 8, 9, 10] print(t[1:3]) print(t[:4]) print(t[5:]) print(t[:]) print(t)
9729e85e8221dded1cf0753a5361d6f6bd8916f7
Keerti-Gautam/PythonLearning
/Functions/Func.py
612
4.5
4
# Use "def" to create new functions """ The syntax for definition is def func_name(argument1, argument2, ...): statements to be executed These functions can be called by writing the function names. """ def add(x, y): # Can use print "x is {0} and y is {1}".format(x, y), print "Addition is", x+y return x+y # Return values with a return statement # Calling functions with parameters print add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 # Another way to call functions is with keyword arguments print add(y=6, x=5) # Keyword arguments can arrive in any order.
571cad4185c8fdd2c0de7c73242ceba7260214e2
benbendaisy/CommunicationCodes
/python_module/examples/product_of_array_except_self.py
660
3.5625
4
from typing import List class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: if not nums: return -1 zero_set = [x for x in range(len(nums)) if nums[x] == 0] if len(zero_set) > 1: return [0 for x in nums] temp = 1 for item in nums: if item != 0: temp *= item if len(zero_set) == 1: return [temp if x == 0 else 0 for x in nums] return [temp//x for x in nums] if __name__ == "__main__": test = Solution() t = [1, 2, 3, 4] print(test.productExceptSelf(t))
50205c05d1f80f0bec76f99143d62899f9025241
UdaySreddy/mobiux-task
/task_mobiUX_2.0.py
9,268
3.796875
4
import csv from datetime import datetime import json date_format = "%b-%Y" def parse_data(file_data): """Parses Data and stores it in proper dictionary :args:\ file_data(list of string lines from file) :returns:\ sales_data(parsed and stored data in form of dictionary) """ iterated_heading = False # to ignore first heading row sales_data = [] columns_data = {} for row in file_data: if not iterated_heading: iterated_heading = True for column_index in range(len(row)): columns_data[row[column_index]] = column_index print(columns_data) else: try: sales_row = {} sales_row["sales_date"] = datetime.strptime( row[columns_data["Date"]], "%Y-%m-%d" ) sales_row["SKU"] = row[columns_data["SKU"]] sales_row["unit_price"] = float( row[columns_data["Unit Price"]] ) sales_row["quantity"] = int(row[columns_data["Quantity"]]) sales_row["total_price"] = float( row[columns_data["Total Price"]] ) sales_data.append(sales_row) except Exception as ex: print( "ERROR: in File Parsing, please check your file to meet " "specified requirements \nMore Info:", ex, ) exit(1) return sales_data def calculate_total_sales(): """Calculates Total Sales in total for all the sales items :returns:\ total_sales(total number of sales => sum of total_price of items) """ total_sales = 0 for sales_object in parsed_sales_data: total_sales += sales_object["total_price"] return total_sales def calculate_month_wise_total_sales(): """Calculates Month wise sum of total sales for all the items""" global month_wise_total_sales month_wise_total_sales = {} for sales_object in parsed_sales_data: # get the date from sales_data for each item parse_date = sales_object["sales_date"].strftime(date_format) # perform sum of total_price for items month wise month_wise_total_sales[parse_date] = ( month_wise_total_sales.get(parse_date, 0) + sales_object["total_price"] ) def calculate_total_sales_for_items_per_month(): """Calculates Month wise total sales of each item :returns:\ month_wise_items: month wise each items total sales """ month_wise_items = {} global month_wise_popular_items month_wise_popular_items = {} for month in month_wise_total_sales.keys(): month_wise_items[month] = {} month_wise_popular_items[month] = {} for sales_object in parsed_sales_data: # get the date from sales_data for each item parse_date = sales_object["sales_date"].strftime(date_format) # perform sum of sales for each item month wise month_wise_items[parse_date][sales_object["SKU"]] = ( month_wise_items[parse_date].get(sales_object["SKU"], 0) + sales_object["quantity"] ) return month_wise_items def calculate_month_wise_popular_items(): """Calculates Month wise most popular item according to quantities sold""" # get total sales of each items month wise month_wise_items_total_sale = calculate_total_sales_for_items_per_month() global month_wise_popular_items for month_key in month_wise_items_total_sale.keys(): # get item with maximum number of total_sales each month popular_item = max( month_wise_items_total_sale[month_key], key=month_wise_items_total_sale[month_key].get, ) # store the item and total_quantity sold in key of month month_wise_popular_items[month_key]["item"] = popular_item month_wise_popular_items[month_key][ "total_quantity" ] = month_wise_items_total_sale[month_key][popular_item] def calculate_month_wise_items_revenue(): """Calculates Month wise item with most revenue according to Sum of total sales """ month_wise_items = {} global month_wise_revenue_of_items month_wise_revenue_of_items = {} # store unique month as keys with empty values for initialization for month in month_wise_total_sales.keys(): month_wise_items[month] = {} month_wise_revenue_of_items[month] = {} # store sum of total_price for each item month wise in month_wise_items for sales_object in parsed_sales_data: parse_date = sales_object["sales_date"].strftime(date_format) month_wise_items[parse_date][sales_object["SKU"]] = ( month_wise_items[parse_date].get(sales_object["SKU"], 0) + sales_object["total_price"] ) # Get the item with maximum revenue and store it in # month_wise_revenue_of_items in key of month for month_key in month_wise_items.keys(): most_revenue_item = max( month_wise_items[month_key], key=month_wise_items[month_key].get, ) month_wise_revenue_of_items[month_key]["item"] = most_revenue_item month_wise_revenue_of_items[month_key][ "total_revenue" ] = month_wise_items[month_key][most_revenue_item] def calculate_month_wise_min_max_avg_popular_item(): """Calculates Min, Max and Average number of quantities sold month wise for most popular item""" # get popular items month wise global min_max_avg_popular_item min_max_avg_popular_item = month_wise_popular_items for sales_object in parsed_sales_data: parse_date = sales_object["sales_date"].strftime(date_format) # check if the current iterating item is most popular item for # the given month or not if sales_object["SKU"] == min_max_avg_popular_item[parse_date]["item"]: # initially store the no_of_order = 1 and min,max = quantity # of item then, increment no_of_order and calculate min,max and # average as most popular items appear in sales_data again if ( min_max_avg_popular_item[parse_date].get("no_of_order", None) is None ): min_max_avg_popular_item[parse_date]["no_of_order"] = 1 min_max_avg_popular_item[parse_date][ "min_quantity" ] = sales_object["quantity"] min_max_avg_popular_item[parse_date][ "max_quantity" ] = sales_object["quantity"] min_max_avg_popular_item[parse_date][ "avg_quantity" ] = sales_object["quantity"] else: # calculate average as total_quantity / total number orders min_max_avg_popular_item[parse_date]["no_of_order"] += 1 min_max_avg_popular_item[parse_date]["avg_quantity"] = ( min_max_avg_popular_item[parse_date]["total_quantity"] / min_max_avg_popular_item[parse_date]["no_of_order"] ) if ( min_max_avg_popular_item[parse_date]["min_quantity"] >= sales_object["quantity"] ): min_max_avg_popular_item[parse_date][ "min_quantity" ] = sales_object["quantity"] if ( min_max_avg_popular_item[parse_date]["max_quantity"] < sales_object["quantity"] ): min_max_avg_popular_item[parse_date][ "max_quantity" ] = sales_object["quantity"] def display_formatted_items(items): """Display Items in dictionary with proper indentation for better view""" print(json.dumps(items, indent=3)) def main(): with open("sales-data2.csv", "r") as sales_data_file: file_content = csv.reader(sales_data_file) global parsed_sales_data parsed_sales_data = parse_data(file_content) # 1. Total Sales of the store print( "\n1. Total Sales of the store: " + str(calculate_total_sales()) + " ₹" ) # 2. Month-wise sales total calculate_month_wise_total_sales() print("\n2.Month wise Total Sales:") display_formatted_items(month_wise_total_sales) # 3. Month wise most popular item (most quantity sold) calculate_month_wise_popular_items() print("\n3.Month wise most popular items:") display_formatted_items(month_wise_popular_items) # 4. Month wise Items with most revenue calculate_month_wise_items_revenue() print("\n4.Month wise items with most revenue: ") display_formatted_items(month_wise_revenue_of_items) # 5. For the most popular item, find the min, max and average number of # orders each month calculate_month_wise_min_max_avg_popular_item() print("\n5. Min, Max and Average sales of Most Popular Item:") display_formatted_items(min_max_avg_popular_item) if __name__ == "__main__": main()
ae578f9b121e006c1f309697c3a74afab90224f5
sidtrip/hello_world
/CS106A/week6/fin_proj/wordguess/word_guess.py
1,338
4.375
4
""" File: word_guess.py ------------------- Fill in this comment. """ import random LEXICON_FILE = "Lexicon.txt" # File to read word list from INITIAL_GUESSES = 8 # Initial number of guesses player starts with def play_game(secret_word): """ Add your code (remember to delete the "pass" below) """ pass def get_word(): """ This function returns a secret word that the player is trying to guess in the game. This function initially has a very small list of words that it can select from to make it easier for you to write and debug the main game playing program. In Part II of writing this program, you will re-implement this function to select a word from a much larger list by reading a list of words from the file specified by the constant LEXICON_FILE. """ index = random.randrange(3) if index == 0: return 'HAPPY' elif index == 1: return 'PYTHON' else: return 'COMPUTER' def main(): """ To play the game, we first select the secret word for the player to guess and then play the game using that secret word. """ secret_word = get_word() play_game(secret_word) # This provided line is required at the end of a Python file # to call the main() function. if __name__ == "__main__": main()
7ec753fdebce80799237ecf10c95f4c2487acb6e
Team-AiK/TT-Thinking-Training
/Week03/hong/1.py
311
3.671875
4
def getMinSum(A,B): answer = 0 size=len(A) while size > 0: num1=min(A) A.remove(num1) num2=max(B) B.remove(num2) size-=1 answer+=num1*num2 return answer #아래 코드는 출력을 위한 테스트 코드입니다. print(getMinSum([1,2],[3,4]))
b52a4712373a5da97c786d67830728dd99940068
joshie-k/exercism-practice
/python/matrix/matrix.py
783
3.6875
4
import unittest class Matrix: def __init__(self, matrix_string): rows = matrix_string.split('\n') row_len = len(rows) col_len = len(rows[0].split(' ')) self.matrix = [[0 for i in range(col_len)]for j in range(row_len)] for i, row in enumerate(rows): values = row.split(' ') for j, value in enumerate(values): self.matrix[i][j] = int(value) print(self.matrix) def row(self, index): return self.matrix[index - 1] def column(self, index): ans = [] for row in range(len(self.matrix)): ans.append(self.matrix[row][index-1]) return ans #matrix = Matrix("1 2\n10 20") matrix = Matrix("1 2 3\n4 5 6\n7 8 9") print(matrix.row(2)) print(matrix.column(3))
bb47dc8dc70060e648d65009cd4427c03ad56d2b
hyo-eun-kim/algorithm-study
/ch08/kio/ch8_3_kio.py
1,503
3.984375
4
''' Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? ''' from typing import * from copy import copy from collections import deque class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: # 내 풀이 (막장) - 40ms, 26.21% def reverseList(self, head: ListNode) -> ListNode: if not head: return head mylist = deque() result = None while head: mylist.append(head.val) head = head.next while mylist: if result is None: result = ListNode(val=mylist.popleft()) continue result.val, result.next = mylist.popleft(), copy(result) return result def reverseList2(self, head: ListNode) -> ListNode: # 책 풀이 (1) 재귀 - 40ms, 26.21% def reverse(head: ListNode, result: ListNode = None) -> ListNode: if not head: return result new, head.next = head.next, result return reverse(new, head) return reverse(head) def reverseList3(self, head: ListNode) -> ListNode: # 책 풀이 (2) 반복 - 32ms, 85.51% node, prev = head, None while node: next, node.next = node.next, prev prev, node = node, next return prev
1602000a994e44f7714d5de895137eee7fb12950
kirillsa/brainbasket_savikrepo
/brainbasket_savikrepo/Pr.set6.py
2,174
3.6875
4
# -*- coding: utf-8 -*- #Savitskiy Kirill #Problem set 3 # #Problem 1 def f(x): import math return 10*math.e**(math.log(0.5)/5.27 * x) def rediationExposure(start, stop, step): sum = 0 while start<stop: sum += f(start)*step start += step return sum # print (rediationExposure(0,5,1)) print (rediationExposure(5,11,1)) print (rediationExposure(0,11,1)) print (rediationExposure(40,100,1.5)) # #Problem 2 def isWordGuessed(secretWord, lettersGuessed): for ch in secretWord: if ch not in lettersGuessed: return 0 return 1 # print (isWordGuessed('apple',['a','p','l','E'])) # #Problem 3 def getGuessedWord(secretWord,lettersGuessed): assert secretWord.islower() #assert c for c in lettersGuessed if c.islower() str = '' for ch in secretWord: if ch in lettersGuessed: str += ch else: str += '_ ' return str # print (getGuessedWord('apple',['e','i','k','p','r','s'])) # #Problem 4 def getAvailableLetters(lettersGuessed): str = '' letters = 'abcdefghijklmnopqrstuvwxyz' for ch in letters: if ch not in lettersGuessed: str += ch return str # print (getAvailableLetters(['e','i','k','p','r','s'])) # #Problem 5 def hangman(secretWord): lettersGuessed = [] while True: guess = '' while guess not in 'qwertyuiopasdfghjklzxcvbnm' or len(guess)>1 or guess is '': guess = input('Enter 1 character: ') guess = guess.lower() if guess not in lettersGuessed: lettersGuessed.append(guess) if isWordGuessed(secretWord, lettersGuessed): print (getGuessedWord(secretWord, lettersGuessed)) print ("You WIN") break else: print (getGuessedWord(secretWord, lettersGuessed)) else: print ('You have entered the letter that you have already entered') print ('enter letter that is in this list', getAvailableLetters(lettersGuessed)) continue # hangman ("kirill")
91b54079555a21d7df62bb4daba55fe8c07c9f69
kimhjong/class2-team3
/20171611_김현지_assignment2.py
349
3.9375
4
n = int(input("Enter a number: ")) + +while n!= -1: + if n>0: + fact=1 + for i in range(1,n+1): + fact=fact*i + print(n,"!=",fact) + elif n==0: + print("0! = 1") + elif n<-1: + print("no answer") + + n = int(input("Enter a number: ")) Lock conversation
6b2a6869c276bb716048d19b1556c38019152fab
Mukulphougat/Python
/functions/revision while loops.py
1,390
3.9375
4
# Printing Even numbers using while loop x = 0 while x <= 10: x += 2 print(x) # Using continue statement current_number = 0 while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number) # Some more while loop print("LOOPS:") y = 1 while y <= 100: print(y) y += 1 prompt = "\nChoose Pizza toppings:" prompt += "\nYour choosen pizza toppings are:" while True: topping = input(prompt) if topping == 'quit': break else: print("\nI'd like to eat that " + topping.title() + " pizza !") # Exercise tickets prompt = "\nInox cinemas." prompt += "\nEnter your age: " while True: age = input(prompt) if age == 'quit': break elif age == 'exit': break elif int(age) <= 3: print("Free of Cost for childs!!") elif int(age) <= 12: print("Ticket cost is $10 ") else: print("Ticket cost is $15") # While loops using list and Dictionaries unconfirmed_users = ['alice','brian','candace'] confirmed_users = [] while unconfirmed_users: current_user = unconfirmed_users.pop() print("Verifying Please wait for response " + current_user.title()) confirmed_users.append(current_user) print("The following has been confirmed for the website.") for confirmed_user in confirmed_users: print(confirmed_user.title())
86c3dba6fedf002f7942d6f52e7f1c4c7b1fd7c9
Debjit337/Python
/7.Tuple.py
1,934
4.46875
4
''' Python Tuple: 1. Tuple nonchange hai, aur list changeable hai. iska systax () 2. Tuple me values na change kar pane ki wajah se isme is tarike ke koi bhi methods nahi milte hai. 3. Single value wale tuple me value ke sath ek comma dena jaruri hai otherwiese wo ek stirng ya int value hi hoga. 4. List ke jaise hi tuple me same to same slicing follow hota hai. Ye posstive and negative dono me hota hia. Tuple me total 2 mehtods milte hain: Note: Example tuple - newtuple = (11,22,33,33) 1. count(): Same list count() method jaisa hi hai. Is ke use se tuple me exist dublicate values ko count kiya jata hai. Example: newtuple.count(33) 2. index(): Same list index jaisa hi hai. Tuple me kisi bhi value ka index posstion find karne ke liye index method ka use kiya jata hai. Example: newtuple.index(33) ''' # new tuple mytuple = ('nikhil','debjit','sushil','debjit','python','debjit') print('\nmytuple type: ', type(mytuple)) print('\nmytuple: ', mytuple) # related mehtods print('\nIndex of python: ', mytuple.index('python')) print('\nCount debjit: ', mytuple.count('debjit')) # slicing print('\nget index vlaue: ', mytuple[2]) print('\nOnly start: ', mytuple[2:]) # find length print('\nFind mytuple length: ', len(mytuple)) print('\nFInd nikhil length: ', len('nikhil')) # convert tuple into list for change or update getTupleDataInList = list(mytuple) print('\nType getTupleDataInList: ', type(getTupleDataInList)) # add 2 more canditates getTupleDataInList.append('Raju') getTupleDataInList.append('Reena') # add bunch of students newstudents = ['Hari','Ram','Seema','Pehu'] getTupleDataInList.extend(newstudents) print('\ngetTupleDataInList: ', getTupleDataInList) print('\nGet last index: ', getTupleDataInList[-1]) # change list into tuple again mytuple = tuple(getTupleDataInList) print('\nCheck type of mytuple: ', type(mytuple)) print('\nmytuple: ', mytuple[0])
1aa79d2605d1be643167509b0b7a88dbaaff3e2d
pooriazmn/KHAFAN_BOT
/a_star.py
2,867
3.65625
4
def add(dic, key, value): dic[key] = value class Node(object): def __init__(self, parent=None, position=None): self.parent = parent self.position = position self.g = 0 self.h = 0 def __eq__(self, other): return self.position == other.position def __hash__(self): return hash(self.position) def __str__(self): return f"({self.x}, {self.y})" @property def x(self): return self.position[0] @property def y(self): return self.position[1] def calc_h(self, position): if self.position is not None: dx = abs(position[0] - self.position[0]) dy = abs(position[1] - self.position[1]) self.h = dx + dy def calc_g(self): if self.parent is None: self.g = 0 else: self.g = 1 + self.parent.g def A_Star_Search(maze, start, end, dont_visit): # print(maze) start_node = Node(None, start) end_node = Node(None, end) if start == end: return start start_node.calc_h(end_node.position) start_node.calc_g() move = [[-1, 0], [0, -1], [1, 0], [0, 1]] to_visit = list() visited = list() to_visit.append(start_node) while len(to_visit) > 0: next_node = to_visit[0] next_node_index = 0 f_next_node = next_node.h + next_node.g for ind, each in enumerate(to_visit[1:], start=1): if each.h + each.g < f_next_node: next_node_index = ind next_node = each f_next_node = next_node.h + next_node.g # print("F is => {} , Min value index: {}".format(dic, min(dic.keys(), key=(lambda k: dic[k])))) current_node = to_visit.pop(next_node_index) visited.append(current_node) # print('current node pos ====> {}'.format(current_node.position)) if end_node == current_node: path = [] while current_node.parent: path.append(current_node) current_node = current_node.parent return path[::-1] for m in move: next_pos = (current_node.x + m[0], current_node.y + m[1]) if next_pos[0] < 0 or next_pos[0] >= len(maze) \ or next_pos[1] < 0 or next_pos[1] >= len(maze): continue if maze[next_pos[0]][next_pos[1]] not in dont_visit: node = Node(current_node, next_pos) if node in visited or node in to_visit: # print(f"duplicate: {node.position}") continue # print(f"adding to A* queue: {node.position}") node.calc_h(end_node.position) node.calc_g() to_visit.append(node)
58e74588f9e56b546847a93ef9abbfbd307c3233
Pragyanshu-rai/p_rai
/even.py
126
3.84375
4
x=int(input("enter the number")) i=0 a=0 while(x!=0): a=x%10 if (a%2==0): i+=a x//=10 print(i)
461b258d769e810d81ed609c75aec6b17cac0bec
karbekk/Python_Data_Structures
/Interview/LC/Trees/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py
1,029
3.671875
4
class NewNode(object): def __init__(self, value): self.val = value self.left = None self.right = None a = NewNode(3) b = NewNode(6) c = NewNode(4) d = NewNode(9) e = NewNode(7) a.left = b a.right = c b.left = d b.right = e class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root is None: return None if root.val == p.val or root.val == q.val: return root.val left = self.lowestCommonAncestor(root.left,p,q) right = self.lowestCommonAncestor(root.right,p,q) if left is not None and right is not None: return root.val if left is None and right is None: return None if left is None and right is not None: return right.val else: return left.val obj = Solution() print obj.lowestCommonAncestor(a, a, c)
2ebe6272c47eaa317b86d2489e036f89a9775592
Veraph/LeetCode_Practice
/cyc/tree/BST/108.py
1,180
4.0625
4
# 108.py -- Convert Sorted Array to Binary Search Tree ''' Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example: Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5 ''' class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def sortedArrayToBST(nums): ''' continually find out the mid index of remaining array to construct the BST ''' def dfs(nums, start, end): # AGAIN! # do not dive into the details # just write the abstraction if start > end: return None mid = (start + end) // 2 root = TreeNode(nums[mid]) root.left = dfs(nums, start, mid - 1) root.right = dfs(nums, mid + 1, end) return root dfs(nums, 0, len(nums) - 1) return root
d16d77746d4cfe60225ea00f1008983a882ef648
mike1130/boot-camp
/week-04/week-04-02.py
1,282
4.15625
4
# Tuesday: For Loops # for num in range(5) : # keyword temp Variable keyword function ending colon # writing your first for loop using range for num in range(5): print('Value: {}'.format(num)) # providing the start, stop, and step for the range function for num in range(2, 10, 2): print('Value: {}'.format(num)) # will print all evens between 2 an 10 # printing all characters in a name using the 'in' keyword name = 'John Smith' for letter in name: print('Value: {}'.format(letter)) # using the continue statement within a foor loop for num in range(5): if num == 3: continue print(num) # breaking out of a loop using the 'break' keyword for num in range(5): if num == 3: break print(num) # setting a placeholder using the 'pass' keyword for i in range(5): # TODO: add code to print number pass # Tuesday Exercises #Divisible by Three for i in range(1, 101): if i % 3 != 0: continue print('Value: {}'.format(i)) # Only Vowels vowels = ['a', 'e', 'i', 'o', 'u'] word = input('Write a word: ').lower() x= [] for letter in word: for i in vowels: if i == letter: x.append(i) break print('{} -> {}'.format(word, x))
3f94255761f5d9b6a36a882c63822774b91ad920
LucasKetelhut/cursoPython
/desafios/desafio075.py
650
3.953125
4
n1=int(input('Digite o 1º número: ')) n2=int(input('Digite o 2º número: ')) n3=int(input('Digite o 3º número: ')) n4=int(input('Digite o 4º número: ')) tupla=(n1,n2,n3,n4) print(f'Você digitou os números: {tupla}') if 9 in tupla: print(f'O valor 9 apareceu {tupla.count(9)} vez(es)') else: print('O valor 9 não apareceu nenhuma vez') if 3 in tupla: print(f'O valor 3 foi digitado pela primeira vez na posição {tupla.index(3)+1}') else: print('O valor 3 não foi digitado nenhuma vez') print('Os valores pares digitados foram:',end = ' ') for c in tupla: if c % 2 == 0: print(c, end=' ') print('\n')
3467bc193aa07ce428377a8ed8543b15f3a1e0b8
Dwomok/python
/get_name.py
99
3.90625
4
# Ask of user's name in python name = raw_input( 'what is your name?: ') print( 'You are' , name )
f6f9ebed50e52d8653e16dc851b67a7d5d897cdd
edsoncpsilva/Curso-Python
/exec06.py
629
3.96875
4
print() print('-'*80) #obtem dados do funcionario nome_func = input('Nome do Funcionario..: ') salario = int(input('Digita Salario Bruto.: ')) pc_desconto = int(input('Digita % de Desconto.: ')) #calcular salario liquido salario_liquido = (salario - ((salario * pc_desconto)/100)) vl_desconto = ((salario * pc_desconto)/100) #exibe resultado print('-'*80) print('Demonstrativo de Pagamento') print('Funcionario.......: ' + nome_func) print('(+)Salario Bruto..: ' + str(salario)) print('(-)' + str(pc_desconto) + '% Desconto...: ' + str(vl_desconto)) print('(=)Salario Liquido: ' + str(salario_liquido)) print('-'*80) print()
6019c9db0a71e23883100fbad5bb28bcc73c7f81
Billiardist94/Billiardist94
/Two largest numbers.py
938
4
4
n = int(input('Введите число > 2: ')) # Вводим количество чисел в списке(>2) lis = [] # Создаем пустой список while len(lis) != n: if n > 2: lis.append(int(input('Введите число в список: '))) # Заполняем список числами, количество чисел равно n else: print('Введено число <= 2') break print(lis) lis.sort() # Сортируем список по возрастанию while lis[-1] == lis[-2]: # В случае повтора чисел в списке lis.pop(-1) if lis[-1] == lis[0]: # Если список состоит из равных чисел print('Список содержит одинаковые значение:', lis[-1]) break print('Два наибольших числа в списке:', lis[-1], 'и', lis[-2])
dd848606c2d3690a58b55afcf70015906d1327eb
Ibramicheal/Onemonth
/Onemonth/tip.py
607
4.21875
4
# this calculator is going to determines the perecentage of a tip. # gets bills from custome bill = float(input("What is your bill? ").replace("£"," ")) print("bill") # calculates the options for tips. tip_one = 0.15 * bill tip_two = 0.18 * bill tip_three = 0.20 * bill # prints out the options avaible. print(f"You bill is {bill} and you have 3 options for a tip, option 1 is {tip_one:.2f}, option 2 is {tip_two:.2f}, option 3 is {tip_three:.2f}. ") option_for_tip = float(input("Which option would you like to choice? ")) print(f"Thank you for choicing option {option_for_tip:.0f} .Please come agian.")
c93218bd652f5da26c651247cc37913a371f5236
fe-sts/curso_em_video
/Python 3 - Mundo 1/2. Usando módulos do Python/Aula 008.py
313
3.859375
4
#from math import sqrt #num = int(input('Digite um numero: ')) #raiz = sqrt(num) #print('A raiz quadrada de {} é: {:.2f}'.format(num, raiz)) #import random #num = random.randint(1, 10) #Randomizar um numero de 1 a 10 #print(num) #import emoji #print(emoji.emojize('Olá, mundo :sunglasses:', use_alises=True))
c50d3267b78fabfb1d19d484ab5d5513b8976109
shashankvishwakarma/Python-Basic
/JSONExample.py
539
3.65625
4
book = {} book['tom'] = { 'name': 'tom', 'address': '1 red street, NY', 'phone': '74185263' } book['bob'] = { 'name': 'bob', 'address': '1 green street, NY', 'phone': '963852741' } import json s = json.dumps(book) print(s) with open('book.json', 'w') as file: file.write(s) with open("book.json", "r") as read_file: s = read_file.read() print(s) json_books = json.loads(s) print(type(json_books)) print(book['bob']) print(book['bob']['phone']) for person in json_books: print(json_books[person])
5e14095f183d548844db70810f1c578f9c2ce35d
nehajagadeesh/stock_order_matching_sytem
/tests/test_stock_model.py
3,945
3.515625
4
from stock_model import Stock from order_model import Order import unittest class StockTest(unittest.TestCase): def setUp(self): pass def test_insert_ascending_order(self): order_list = [ Order("#3 9:45 XAM sell 100 240.10".split(" ")), Order("#2 9:40 XAM sell 100 245.10".split(" ")), Order("#1 9:41 XAM sell 100 240.10".split(" ")), Order("#4 9:41 XAM sell 100 240.10".split(" ")), Order("#5 9:41 XAM sell 100 239.10".split(" "))] stock_obj = Stock("xam") with self.assertRaises(Exception) as exc: stock_obj._insert_in_ascending_order(order_list[0], 0, -1) self.assertIn("Index", str(exc.exception)) stock_obj.sorting_queue = [order_list[0], order_list[1]] with self.assertRaises(Exception) as exc: stock_obj._insert_in_ascending_order(order_list[2], 0, 1) self.assertIn("Index", str(exc.exception)) stock_obj.sorting_queue = [order_list[2], order_list[0], order_list[1]] stock_obj._insert_in_ascending_order(order_list[4], 0, 2) stock_obj._insert_in_ascending_order(order_list[3], 0, 3) compare_list = [order.order_id for order in stock_obj.sorting_queue] self.assertListEqual(compare_list, ["#5", "#4", "#1", "#3", "#2"]) def test_insert_into_queue(self): queue = [] order_list = [ Order("#1 9:41 XAM sell 100 240.10".split(" ")), Order("#2 9:40 XAM sell 100 245.10".split(" ")), Order("#3 9:45 XAM sell 100 240.10".split(" ")), Order("#4 9:41 XAM sell 100 240.10".split(" ")), Order("#5 9:41 XAM sell 100 239.10".split(" ")),] op_order_list = ["#5", "#4", "#1", "#3", "#2"] op_order_list_reverse = ["#5", "#3", "#1", "#4", "#2"] stock_obj = Stock("xam") for order_obj in order_list: stock_obj.insert_into_queue(order_obj, queue) queue_extract = [order.order_id for order in queue] self.assertListEqual(op_order_list, queue_extract) queue = [] stock_obj.reverse_sort = True for order_obj in order_list: stock_obj.insert_into_queue(order_obj, queue) queue_extract = [order.order_id for order in queue] self.assertListEqual(op_order_list_reverse, queue_extract) def test_matched_order_queries(self): order_list = [ "#1 09:45 XAM sell 100 240.10", "#2 09:45 XAM sell 90 237.45", "#3 09:47 XAM buy 80 238.10", "#5 09:48 XAM sell 220 241.50", "#6 09:49 XAM buy 50 238.50", "#8 10:01 XAM sell 20 240.10", "#9 10:02 XAM buy 150 242.70"] op_matched = ['#2 80 237.45 #3', '#2 10 237.45 #6', '#8 20 240.1 #9', '#1 100 240.1 #9', '#5 30 241.5 #9'] stock_obj = Stock("xam") matched_queries = [] for order_str in order_list: order = Order(order_str.split(" ")) stock_obj.match_order_queries(order, matched_queries) self.assertListEqual(matched_queries, op_matched) def test_generate_matched_queries(self): stock_obj = Stock("xam") matched_queries = [] stock_obj.sell_list = [ Order("#2 09:45 XAM sell 50 237.45".split(" ")), Order("#3 09:46 XAM sell 50 237.45".split(" ")), Order("#1 09:45 XAM sell 100 240.10".split(" "))] stock_obj.buy_list = [ Order("#4 09:47 XAM buy 80 238.10".split(" "))] stock_obj.generate_matched_orders("buy", matched_queries) expected_op = ['#2 50 237.45 #4', '#3 30 237.45 #4'] self.assertListEqual(matched_queries, expected_op) formatted_sell_list = [order.order_id for order in stock_obj.sell_list] self.assertListEqual(formatted_sell_list, ['#3', '#1']) self.assertListEqual(stock_obj.buy_list, [])
7f5df2d015c513da572cb406441b843a1d549972
manjeet008/Basic_Programs-Recommended-
/AUGMENTED_OPERATOR.py
144
4.09375
4
#AUGMENTED OPERATOR input1=int(input("ENTER ANY NUMBER HERE.... ")) input1+=10 print("ADDING 10 TO IT ....") print("IT BECOMES... ",input1)
22b766db4565e7fa5c545b6a992376423e9002c5
devesh-bhushan/python-assignments
/concepts/tester.py
429
4.03125
4
""" using decorator function in factorial """ def decorator(facto): d= {} def logic(n): if n not in d: d[n] = facto(n) return d[n] return logic @ decorator def facto(n): if n == 1 or n == 0: return 1 else: return n * facto(n-1) res = facto num = int(input("enter the number upto factorial to be calculated")) for n in range(num): print(res(n), end="\n")
ee945326827a65692f738dce88072c076ab1042c
asperaa/back_to_grind
/bactracking/39. Combination Sum.py
713
3.59375
4
"""We are the captains of our ships, and we stay 'till the end. We see our stories through. """ """39. Combination Sum """ class Solution: def combinationSum(self, nums, target): n = len(nums) self.total_length = n self.ans = [] self.target = target self.helper(nums, [], 0, 0) return self.ans def helper(self, nums, curr_set, curr_summ, index): if curr_summ == self.target: self.ans.append(curr_set) return elif curr_summ > self.target: return else: for i in range(index, self.total_length): self.helper(nums, curr_set + [nums[i]], curr_summ + nums[i], i)
0611bd86aec6cc76d417356c5cf9cf88828238c9
meganzg/Competition-Answers
/CodeQuest2017 - Practice/Prob11.py
578
3.609375
4
f = open(__file__.split(".")[-2] + ".in.txt") ncases = int(f.readline().strip()) key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i in range(ncases): text = f.readline().strip() final = "" for word in text.split(): fword = word word = list(filter(str.isalpha, word)) #print(word) for w, c in zip(word, reversed(word)): #print(w, c) if w.isupper(): final += c.upper() else: final += c.lower() if not fword[-1].isalpha(): final += fword[-1] final += " " print(final)
71e860c9a2b5caf326cd1d3de048b0d1783428e8
Jsevillamol/AIMA
/search/problems/test_problem.py
1,023
3.953125
4
# -*- coding: utf-8 -*- from problems.problem import Problem class Test_problem(Problem): """ Problem for testing. The initial state is 0. Actions are sum 1, sum 2 or sum 3. The goal is reaching a certain number, """ def __init__(self, goal = 21): self.goal_state = goal self.initial_state = 0 def goal_test(self, state)->bool: """ Returns True if state is a goal state """ return state == self.goal_state def actions(self, state): """ Returns a generator over the available actions in state """ return [1,2,3] def result(self, state, action): """ Returns the result of applying action to state """ return state + action def predecessors(self, state): return [(state-1, 1), (state-2, 2), (state-3, 3)] def __repr__(self): return "Test problem: Init={} Goal={}".format(self.initial_state, self.goal_state)
cc9aad138da71d82d8de55f02c4784948f89e567
gudduarnav/ImageProcessingPython
/ImageProcessing/LiveStreamVideo/Video/old/videograyframes.py
916
3.703125
4
# Read a Video stream from file and stream it on screen in Grayscale format import cv2 # Set the Video Filename vidFile = "demo.mp4" # Open the Video File v = cv2.VideoCapture(vidFile) # Check if the file can be opened successfully if(v.isOpened() == "False"): print("ERROR: Cannot open the Video File") quit() print("SUCCESS: Video File opened") # Read one frame from the file while v.isOpened() == True: ret, frame = v.read() # Check if the frame is successfully read if(ret == False): print("ERROR: Cannot read more video frame") break # Convert to grayscale gframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the frame data cv2.imshow("Video Frame", gframe) # Wait for 25 ms for a user key press to exit if(cv2.waitKey(25) != -1): break # Close the video file v.release() # Close all open window cv2.destroyAllWindows()
bfcd8a482db150138e53a2fc957bc1bdd5c8f66e
VamsiMohanRamineedi/Algorithms
/349. Intersection of two arrays.py
481
3.6875
4
# Intersection of two arrays: Time: O(m+n), space:O(m) class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: result = [] hash_map_nums1 = {} for num in nums1: if num not in hash_map_nums1: hash_map_nums1[num] = 1 for num in nums2: if num in hash_map_nums1: del hash_map_nums1[num] result.append(num) return result
35ad15bb061ea9fc9ac4d33d45d7b1adab5a6809
anilsaini06/python
/l.py
172
4.09375
4
print ("what is your age?") age = int(input()) if age<18: print("you cannot drive") elif age ==18: print("we will think about you") else: print("you can drive")
6d5ea5a36d1608288e0503db8598e572a9ae3429
sakurasyaron/educative-ds-and-algos
/StringProcessing/palindrome_permutation.py
568
3.828125
4
def is_palin_perm(input_str): input_str = input_str.replace(" ", "") input_str = input_str.lower() d = dict() for i in input_str: if i in d: d[i] += 1 else: d[i] = 1 odd_count = 0 for k, v in d.items(): if v%2 != 0 and odd_count == 0: odd_count += 1 elif v%2 != 0 and odd_count !=0: return False return True palin_perm = "Tact Coa" not_palin_perm = "This is not a palindrome permutation" print(is_palin_perm(palin_perm)) print(is_palin_perm(not_palin_perm))
786c02c6392619a0f3314621d11c31cc07de1539
pihu480/more-exercise
/factorial.py
88
3.921875
4
i=int(input("enter tha number")) f=1 while i>0: f=f*i i=i-1 print("factorial",f)
50eb6623a6aabd9a9c9d1d1cd6809a7ee4574d4f
feng1o/python_1
/文件/pickling.py
679
3.71875
4
#!/usr/bin/python # Filename: pickling.py import pickle # the name of the file where we will store the object shoplistfile = 'shoplist.data' # the list of things to buy shoplist = ['apple','mango','carrot'] shoplist1= ['name','age','sex'] # Write to the file f = open(shoplistfile,'wb') pickle.dump(shoplist, f) #dump the object to a file pickle.dump(shoplist1,f) f.close() del shoplist # detroy the shoplist variable del shoplist1 # Read back from the storage with open(shoplistfile,'rb') as f: while True: try: storedlist = pickle.load(f) # load the object from the file except EOFError: print("eof---") break print(storedlist)
c82f723057a489b6a9d21494071338f8481aa76c
armansujoyan/codefights
/The Journey Begins/checkPalindrome.py
282
3.5625
4
def checkPalindrome(inputString): # In order to solve this problem we # will use Python's Extended Slice # For more information see https://docs.python.org/2.3/whatsnew/section-slices.html if inputString == inputString[::-1]: return True return False
f2fd5b0e455c2b7ca6a2ac654d2ade0a28d8a489
lucaderi/sgr
/2021/Pini/Client.py
962
3.609375
4
class Client: """Represents a wireless client seen in that envirement Inputs: - bssid(str) the MAC address of the wireless client - ssid set of the network names (of the APs) """ def __init__(self, bssid): self.bssid = bssid self.requested_ssid = set() def add_new_requested_ssid(self, new_ssid): """ Returns True if new_ssid was not present and for that added, False otherwise """ if new_ssid not in self.requested_ssid: self.requested_ssid.add(new_ssid) return True return False def printClient(self): ssid_list = [] for item in self.requested_ssid: ssid_list.append(item) if len(ssid_list) == 0: print(self.bssid) return print(self.bssid + " " + ssid_list[0]) x = 1 while x < len(ssid_list): print(" "*17 + " " + ssid_list[x]) x = x + 1
53ae502ad523bd6cd23e8b3b0f1422ff05a716bf
lucaschen198311/Python
/fundamentals/extras/TDD.py
3,458
3.96875
4
import unittest def reverseList(input): return input[::-1] def isPalindrome(input): for i in range(0,len(input)//2): if input[i] != input[len(input)- 1 -i]: return False return True def factorial(n): if n<1: return if n ==1: return n return n*factorial(n-1) def fibonacci(n): if n>=0 and n<=1: return n elif n>1: fibNum=fibonacci(n-1) + fibonacci(n-2) return fibNum; class isPalindromeTests(unittest.TestCase): def testTrue(self): self.assertEqual(isPalindrome("racecar"), True) # another way to write above is self.assertTrue(isPalindrome("racecar")) def testFalse(self): self.assertEqual(isPalindrome("rabcr"), False) # another way to write above is self.assertFalse(isPalindrome("rabcr")) # any task you want run before any method above is executed, put them in the setUp method def setUp(self): # add the setUp tasks print("running setUp") # any task you want run after the tests are executed, put them in the tearDown method def tearDown(self): # add the tearDown tasks print("running tearDown tasks") class fibonacciTests(unittest.TestCase): def testTrue(self): self.assertEqual(fibonacci(5), 5) # another way to write above is #self.assertTrue(fibonacci(5)) def testFalse(self): self.assertEqual(fibonacci(6), 8) # another way to write above is #self.assertFalse(fibonacci("rabcr")) # any task you want run before any method above is executed, put them in the setUp method def setUp(self): # add the setUp tasks print("running setUp") # any task you want run after the tests are executed, put them in the tearDown method def tearDown(self): # add the tearDown tasks print("running tearDown tasks") class factorialTests(unittest.TestCase): def testTrue(self): self.assertEqual(factorial(5), 120) # another way to write above is #self.assertTrue(fibonacci(5)) def testFalse(self): self.assertEqual(factorial(6), 720) # another way to write above is #self.assertFalse(fibonacci("rabcr")) # any task you want run before any method above is executed, put them in the setUp method def setUp(self): # add the setUp tasks print("running setUp") # any task you want run after the tests are executed, put them in the tearDown method def tearDown(self): # add the tearDown tasks print("running tearDown tasks") class reverseListTests(unittest.TestCase): def testTrue(self): self.assertEqual(reverseList("abc"), "cba") # another way to write above is #self.assertTrue(fibonacci(5)) def testFalse(self): self.assertEqual(reverseList("a"), "a") # another way to write above is #self.assertFalse(fibonacci("rabcr")) # any task you want run before any method above is executed, put them in the setUp method def setUp(self): # add the setUp tasks print("running setUp") # any task you want run after the tests are executed, put them in the tearDown method def tearDown(self): # add the tearDown tasks print("running tearDown tasks") print(__name__) if __name__ == '__main__': unittest.main() # this runs our tests
8bc3f20acb694177404d1722cc8ea5348e4ab85d
pranaysingh25/Facial-Keypoint-Detection
/models.py
1,790
3.578125
4
# define the convolutional neural network architecture import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() # input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel self.conv1 = nn.Conv2d(1, 32, 5) self.conv2 = nn.Conv2d(32, 64, 4) self.conv3 = nn.Conv2d(64, 128, 3) self.conv4 = nn.Conv2d(128, 256, 3) self.conv5 = nn.Conv2d(256, 512, 3) self.maxpool = nn.MaxPool2d(2,2) self.fc1 = nn.Linear(512*4*4, 2000) self.fc2 = nn.Linear(2000, 1000) self.fc3 = nn.Linear(1000, 136) self.dropout1 = nn.Dropout(p=0.1) self.dropout2 = nn.Dropout(p=0.2) self.dropout3 = nn.Dropout(p=0.3) self.dropout4 = nn.Dropout(p=0.4) def forward(self, x): # Define the feedforward behavior of this model ## x is the input image x = self.maxpool(F.relu(self.conv1(x))) x = self.dropout1(x) # print(x.shape) x = self.maxpool(F.relu(self.conv2(x))) x = self.dropout2(x) x = self.maxpool(F.relu(self.conv3(x))) x = self.dropout3(x) x = self.maxpool(F.relu(self.conv4(x))) x = self.dropout3(x) x = self.maxpool(F.relu(self.conv5(x))) x = self.dropout4(x) # print(x.shape) x = x.view(x.size(0), -1) x = F.relu(self.fc1(x)) x = self.dropout4(x) x = F.relu(self.fc2(x)) x = self.dropout4(x) x = self.fc3(x) return x
670c49d5fb55308d44d18d645dbe7b9beb685f26
nkwarrior84/Statistical-coding
/encryption.py
1,860
4.4375
4
''' An English text needs to be encrypted using the following encryption scheme. First, the spaces are removed from the text. Let L be the length of this text. Then, characters are written into a grid, whose rows and columns have the following constraints: floor(root(L)) < row < column < ceil(root(L)) Example s = if man was meant to stay on the ground god would have given us roots After removing spaces, the string is 54 characters long. root(54) is between 7 and 8, so it is written in the form of a grid with 7 rows and 8 columns. ifmanwas meanttos tayonthe groundgo dwouldha vegivenu sroots Ensure that row*columns>=L If multiple grids satisfy the above conditions, choose the one with the minimum area, i.e. . The encoded message is obtained by displaying the characters of each column, with a space between column texts. The encoded message for the grid above is: imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau Create a function to encode a message. Function Description Complete the encryption function in the editor below. encryption has the following parameter(s): string s: a string to encrypt Returns string: the encrypted string ''' import math import os import random import re import sys # # Complete the 'encryption' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def encryption(s): L = len(s) rows = int(math.floor(L**(0.5))) columns = int(math.ceil(L**(0.5))) output = "" for i in range(columns): k = i for j in range(k,L,columns): output+=s[j] output+=" " return output if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = raw_input() result = encryption(s) fptr.write(result + '\n') fptr.close()
c129f135bdc0cd94047a9dc887f310ce673c6522
thedog2/dadadsdwadadad
/часть 2(week2)/koordinatnue chetverti.py
135
3.734375
4
x1=int(input()) y1=int(input()) x2=int(input()) y2=int(input()) if x1*x2>0 and y1*y2>0: print('Yes') else: print('No')
40037ac32edd672a48aa75d40a1a968bd8fe3c97
sourlows/pyagricola
/src/player/family_member.py
628
3.8125
4
__author__ = 'djw' class FamilyMember(object): """ A single family member and his current state """ def __init__(self, is_adult=False): self.is_adult = is_adult self.currently_working = False @property def food_cost(self): """ :return: The number of food this unit requires at harvest """ return 2 if self.is_adult else 1 def update(self): """ Called at the very beginning of a new turn """ if not self.is_adult: self.is_adult = True # family members are only newborn on the turn they are created self.currently_working = False
87987b3bcb41b671f3eac7367e32ceb737bdf208
omdeshmukh20/Python-3-Programming
/Even Factor.py
206
4.0625
4
#Discription: Even factor program #Date: 09/07/21 #Author : Om Deshmukh x = int(input("Enter any number")) print("The even factors of",x,"are:") for i in range(2, x + 2): if x % i == 0: print(i)
d1eadafd170e7f8e5fcdd099bc29dc4a06337888
SinglePIXL/CSM10P
/Homework/randomNumbersReadWrite.py
1,699
3.953125
4
# Alec # randomNumbersReadWrite.py # 10-2-19 # Ver 2.1 # A program that writes a series of random numbers to a file. # Each random number should be in the range of 1 through 100. # The user specifies how many random numbers the file will hold. import random def main(): outfile = open('randomNumbers.txt','w') # Ask user for number of random numbers randomPasses = int(input("How many random numbers do you want? ")) # Loop for user defined number for i in range(1,randomPasses + 1): randomNumber = random.randint(1,101) # Write random numbers to randomNumbers.txt outfile.write(str(randomNumber)+'\n') outfile.close() print('Writing...') print('Done.') main() ######################################################################### # Write another program that reads the random numbers from the file, # display the numbers, and then display the following data: # The total of the numbers # The number of random numbers read from the file def main(): infile=open('randomNumbers.txt','r') # Define total total = 0 # Define how many numbers are in file count = 0 for line in infile: # Remove newwline operator line=line.rstrip('\n') # Print the random number print('Number', count + 1, 'is', line) randomNumber = int(line) # Add number to total total += randomNumber count += 1 infile.close() # Print the total of the random numbers print('The total of the random numbers is', total) # Print how many random numbers are in the file print('There are', count,'random numbers in the file.') print('Exiting...') main()
e4a29712471031057df356f78a09aa1bf1ed28da
prajwal60/ListQuestions
/learning/BasicQuestions/Qsn73.py
285
4.1875
4
# Write a Python program to calculate midpoints of a line x1 = int(input('Enter value of x1 ')) x2 = int(input('Enter value of x2 ')) y1 = int(input('Enter value of y1 ')) y2 = int(input('Enter value of y2 ')) x = (x1+x2)/2 y= (y1+y2)/2 print(f'The mid point is ({int(x)},{int(y)})')
f6ee182153c8c4e488cf232aaa824b0b44bc6eff
NavTheRaj/python_codes
/loop.py
86
3.625
4
for num in range (1,6,2): print(num) for x in range(1,8): print(x)
dc36e0402d7e9253ebb1b70ee76df105e7ff625d
Carvanlo/Python-Crash-Course
/Chapter 10/learning_c.py
226
3.765625
4
filename = 'learning_python.txt' with open(filename) as file_object: lines = file_object.readlines() file_string = '' for line in lines: file_string += line.rstrip() file_string.replace('python', 'c') print(file_string)
ba90f3ff508957195195c7f5bdbef694b608d90b
DivyaMaddipudi/NPTEL_Pyhton
/Programming Assignments/week-3/practice1.py
195
3.8125
4
def descending(l): li = [] for i in l: li = li + [i] x = l x.sort(reverse = True) if li == x: return True else: return False print(descending([]))
ac62b22d0de999d532fffb9dbd80cbc95f4e77fb
ianlai/Note-Python
/algo/tree/_0314_BinaryTreeVerticalOrderTraversal.py
1,350
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # DFS with sorting [O(N + WlogW + WHlogH), 80%] def verticalOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] ans = [] idxToVal = collections.defaultdict(list) self.helper(root, idxToVal, 0, 0) for key in sorted(idxToVal): verts = sorted(idxToVal[key], key = lambda x:x[0]) # IMPORTANT: need to specify the key # Without the key, it will sort by x[0] first than x[1] (maybe) # However, we want to sort by x[0] but keep others in insertion order tmp = [] for node in verts: tmp.append(node[1]) ans.append(tmp) return ans def helper(self, node, idxToVal, idx, layer): if not node: return # Pre-order DFS idxToVal[idx].append([layer, node.val]) self.helper(node.left, idxToVal, idx - 1, layer + 1) self.helper(node.right, idxToVal, idx + 1, layer + 1)
23d4866bd2d524ad80704aa68d958c2050dc5b5e
GustavoJatene/practice
/029.py
195
3.65625
4
vel = int(input("Informe a velocidade do carro: ")) if vel <= 80: print("Dentro do limite permitido") else: mul = (vel-80)*7 print("Deverá pagar multa no valor de: {}R$".format(mul))
50556888317ba4b3502a2d915aca31803285b383
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/ian_letourneau/Lesson02/fizz_buzz.py
526
4.5
4
## Ian Letourneau ## 4/25/2018 ## A script to list numbers and replace all multiples of 3 and/or 5 with various strings def fizz_buzz(): """A function that prints numbers in range 1-100 inclusive. If number is divisible by 3, print "Fizz" If number is divisible by 5, print "Buzz" If number is divisible by both 3 and 5, print "FizzBuzz""" for num in range(1,101): if not num%3 and not num%5: print('FizzBuzz') elif not num%3: print('Fizz') elif not num%5: print('Buzz') else: print(num) fizz_buzz()
d727324b20758b00bb745be414e585baf732ffbb
EstherAmponsaa/cssi
/cssi-labs (copy)/python/labs/word-frequency-counter/starter-code/wordfreq_starter.py
1,186
4.125
4
def read_process_data(): with open('third_party/jane-eyre.txt') as f: # the following line # - joins each line in the file into one big string # - removes all newlines and carriage returns # - converts everything to lowercase content = ' '.join(f.readlines()).replace('\n','').replace('\r','').lower() return content # You do not need to call this function unless you are doing level 3 def get_stop_words(): with open('stop-words.txt') as f: content = ' '.join(f.readlines()).replace('\n','').replace('\r','').lower() return content.split(' ') def get_highest_words(counts_dictionary, count): highest = sorted(counts_dictionary.items(), key=lambda x:x[1])[::-1][:count] for word in highest: print("%s: %s" % (word[0], word[1])) content = read_process_data() stop_words = get_stop_words() # Write your solution below! word_count = {} words = content.split(" ") for word in words: if word_count.has_key(word): word_count[word] = word_count[word] + 1 else: if word != "" and word not in stop_words: word_count[word] = 1 get_highest_words(word_count,10)
d9acf0b20e3941cb5b529f80e253e10d00b97433
2ptO/code-garage
/icake/q2.py
1,060
4.5
4
# Given a list of integers, find the highest product you # can get from three of the integers. def get_highest_product_of_three(nums): # Can't calculate highest product of 3 with less than 3 numbers if len(nums) < 3: raise ValueError("Expected a minimum of 3 numbers") highest_product_of_three = nums[0] * nums[1] * nums[2] highest_product_of_two = nums[0] * nums[1] highest = max(nums[0], nums[1]) lowest_product_of_two = nums[0] * nums[1] lowest = min(nums[0], nums[1]) # walk from the third number in the list. for n in nums[2:]: highest_product_of_three = max(highest_product_of_three, highest_product_of_two * n, lowest_product_of_two * n) highest_product_of_two = max(highest_product_of_two, highest * n, lowest * n) highest = max(highest, n) lowest_product_of_two = min(lowest_product_of_two, highest * n, lowest * n) lowest = min(lowest, n) return highest_product_of_three
3fbf94406da7d036b3d2e4411c772a63ad53313a
Blitzdude/advent-of-code-2020
/tutorials/python_sets.py
1,498
4.25
4
# https://pythonspot.com/python-set/ exampleSet = set(["Postcard", "Radio", "Telegram"]) print(exampleSet) # Sets cannot contains multiples. Any doubles are removed exampleSet = set(["Postcard", "Radio", "Telegram", "Postcard"]) print(exampleSet) # Above is old notation, Use simple notation in python 3 simpleSet = {"Postcard", "Radio", "Telegram"} print(simpleSet) # set.clear() removes all elements from set emptySet = {"Postcard", "Radio", "Telegram"} emptySet.clear() print(emptySet) # set.remove(var) removes specified elements removedSet = {"Postcard", "Radio", "Telegram"} removedSet.remove("Postcard") print(removedSet) # set.difference(other) compares set with another and returns set with differing values xSet = {"Postcard", "Radio", "Telegram" } ySet = {"Radio"} print("xset " + str(xSet.difference(ySet))) print("ySet " + str(ySet.difference(xSet))) # Subset - set.issubset(other) tests if values in "set" are contained in "other" xSuperSet = {"a","b","c","d"} ySubSet = {"c","d"} print("Subsets") print(xSuperSet.issubset(ySubSet)) print(ySubSet.issubset(xSuperSet)) # Superset - set.issuperset(other) tests if values in "other" are contained in "set" print("Superset") xSuperSet = {"a","b","c","d"} ySubSet = {"c","d"} print(xSuperSet.issuperset(ySubSet)) print(ySubSet.issuperset(xSuperSet)) # Intersection - set.intersection(other) returns all variables in both sets xIntersect = {"a","b","c","d","e"} yIntersect = {"c","d"} print( xIntersect.intersection(yIntersect))
8b73e28dcaa92c356ba1f8d4433816a598610d5a
XOR0831/speech-recognition-fcs
/1-Data Gathering & Preparation/audio_segmentation.py
7,271
3.546875
4
# import dependencies from pydub import AudioSegment from pydub.silence import split_on_silence import os import speech_recognition as sr import datetime # use the audio file as the audio source for recognition r = sr.Recognizer() # file path to original data path = "./Data/" # file path to transcribed data path_split = "./Data_Clean/" # if directory for transcribed data does not exists if not os.path.exists(path_split): # create directory os.makedirs(path_split) # for every volume folder in the original data for volume in os.listdir(path): # if volume directory for transcribed data does not exists if not os.path.exists(path_split + volume): # create directory os.makedirs(path_split + volume) # for every folder in volume directory of original data for folder in os.listdir(path + volume): # initialize/reset unknown count to 0 unknown = 0 # if folder in volume directory of transcribed data does not exists if not os.path.exists(path_split + volume + "/" + folder): # create directory os.makedirs(path_split + volume + "/" + folder) # for every file in folder under volume directory of original data for file in os.listdir(path + volume + "/" + folder): # initialize/reset transcripts container to empty/null transcripts = [] # if folder for the transcribe audio under folder under volume directory does not exists if not os.path.exists(path_split + volume + "/" + folder + "/" + file[:-4]): #create directory os.makedirs(path_split + volume + "/" + folder + "/" + file[:-4]) # load audio file sound_file = AudioSegment.from_wav(path + volume + "/" + folder + "/" + file) print("LOADED: " + str(path + volume + "/" + folder + "/" + file)) # segments/splits audio on silence and assign segmented/splitted audio to audio chunks # some segmented/splitted audio are per word but some are in sentences due to fast speech of speaker print("SEGMENTING") audio_chunks = split_on_silence(sound_file, # must be silent for at least a half second to consider it a word min_silence_len=25, # consider it silent if quieter than -16 dBFS silence_thresh=-35 ) print("SEGMENTED") # write all segmented audio into new file print("WRITING") for i, chunk in enumerate(audio_chunks): # save every segmented audio to created directory for transcribed data out_file = path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "chunk{0}.wav".format(i) print("WRITE:", out_file) chunk.export(out_file, format="wav") # status for transcript checking status = "" # open saved audio and send to Google Speech Recognition (Speech to Text) to recognize and label the audio with sr.AudioFile(out_file) as source: audio = r.record(source) # read the entire audio file is_not_transcribe = True while is_not_transcribe: try: # send audio to GSR for recognition transcribe = r.recognize_google(audio,language="fil-PH") # set language code to Filipino print("(GSR)Transcription: " + transcribe) status = "GSR" is_not_transcribe = False except sr.UnknownValueError: # if GSR cant recognize audio set audio name to UNKNOWN print("Unknown") unknown += 1 status = "UNKNOWN" is_not_transcribe = False except: is_not_transcribe = True # renaming audio with the GSR transcript print("LABELING") writed = True # if GSR recognize if status == "GSR": # if GSR transcribe exist in transcripts if transcribe in transcripts: # add timestamp transcribe = transcribe + " " + str(datetime.datetime.now().second) + "" + str(datetime.datetime.now().minute) + "" + str(datetime.datetime.now().hour) while writed: print("-"*100) # try to rename audio with GSR transcript if not set to UNKNOWN try: # rename audio with GSR transcribe os.rename(out_file, path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "{0}.wav".format(transcribe)) writed = False # add GSR transcribe to transcripts transcripts.append(transcribe) except: # rename audio with UNKNOWN unknown += 1 os.rename(out_file, path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "UNKNOWN{0}.wav".format(unknown)) writed = False # if not else: while writed: print("+"*100) # try to rename audio with GSR timestamp try: # rename audio with GSR transcribe os.rename(out_file, path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "{0}.wav".format(transcribe)) writed = False # add GSR transcribe to transcripts transcripts.append(transcribe) except: # rename audio with UNKNOWN unknown += 1 os.rename(out_file, path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "UNKNOWN{0}.wav".format(unknown)) writed = False # if not recognized else: while writed: print("="*100) # try to rename audio until renamed try: # rename audio with UNKNOWN os.rename(out_file, path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "UNKNOWN{0}.wav".format(unknown)) writed = False except: writed = True print("LABELED")
2814a3bb6ff9806fe03cd3934c5b3a5dcaccf062
hamzaansarics/Python-
/star args Operator.py
1,563
4.09375
4
# def total(a,b): ///// Simple Function ////////// # return a+b # print(total(10,22)) # print(total(10,12,12)) //// Genrating Error Because Input is Extra than Parameters /// # /////////////// *args Operator ///////////// # n=int(input("Enter a value")) # b=int(input("Enter b value")) # c=int(input("Enter c value")) # def unlimited_do(*args): # total=0 # print(type(args)) # for i in args: # # print(type(args)) # # total+=i # # return total # print(unlimited_do(n,b,c)) # n=int(input("Enter a value")) ///// They Will Genrate Error if we add aonther paramter with *args //// # b=int(input("Enter b value")) # c=int(input("Enter c value")) # def unlimited_do(*args,num): # total=0 # # print(type(args)) # for i in args: # total+=i # # # return total # print(unlimited_do(n,b,c)) # def unlimited_do(*args): # total=0 # # for i in args: # total+=i # # # return total # lists=[1,2,3] # print(unlimited_do(lists)) /////TypeError: unsupported operand type(s) for +=: 'int' and 'list'/////// # def unlimited_do(*args): # total=0 # # for i in args: # total+=i # # # return total # lists=[1,2,3,10] # list2=(1,2,3,4) # print(unlimited_do(*lists,*list2)) ////////// Error Free Working Perfect Becaouse we Unpacked the list and tuple //////////// # def tricky(num,*args): # a=[i**num for i in args] # if args: # return a # return "Please Enter Args Values" # print(tricky(3))
7c107a6f871acb68be870aad8b3bcb7f284a2384
jones3kd/Cracking_The_Coding_Interview
/ch2/2.3.py
708
3.859375
4
""" Problem 2.3 implement an algorithm to delete a node in the middle of a singly linked list given acces only to that node. """ from linked_list import LinkedList def delete_mid_node(middle_node): if middle_node is None: return 0 if middle_node.next is not None: middle_node.value = middle_node.next.value middle_node.next = middle_node.next.next middle_node.next.next = None return middle_node linked_list = LinkedList() letters = ['a', 'b', 'c', 'd', 'e'] for let in letters: linked_list.append(let) print(str(linked_list)) mid_node = linked_list.get_node('c') print(str(mid_node)) print(str(delete_mid_node(mid_node))) print(str(linked_list))
d703841bd6da03a0888a11e775e3e9b355f904dd
kefirzhang/algorithms
/leetcode/python/easy/p203_removeElements.py
797
3.65625
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements(self, head: ListNode, value: int) -> ListNode: pre_head = back_head = ListNode(None) pre_head.next = head while pre_head.next is not None: if pre_head.next.val == value: pre_head.next = pre_head.next.next else: pre_head = pre_head.next return back_head.next l1 = ListNode(1) l1.next = ListNode(6) l1.next.next = ListNode(3) l1.next.next.next = ListNode(4) l1.next.next.next.next = ListNode(5) l1.next.next.next.next.next = ListNode(6) slu = Solution() l2 = slu.removeElements(l1, 1) while l2 is not None: print(l2.val) l2 = l2.next
9b82ef0076be12130ad77c0d10e7d1cd39c0c8af
kristiluu/Student-Gradebook
/College/main.py
4,877
4
4
# Kristi Luu from student import Student, IntlStudent, StudentEmployee class StudentRecord(Student): '''This is the StudentRecord class''' def __init__(self): '''The constructor for StudentRecord class. It has 2 variables: list of countries for International students and dictionary of students, organized by 3 keys: student employees (e), international students (i), and students (s). The values of each key is an object (one object = one student)''' self.__countryList = [] try: with open("record.txt") as fh: self.__studentRecord = {} #database count = 1 for line in fh: if count % 2 != 0: #odd lines are student type studType = line.rstrip('\n') if count % 2 == 0: #even lines are the lines if studType == "i": if "i" not in self.__studentRecord: self.__studentRecord["i"] = [] #default dictionary try: i = IntlStudent(line) self.__studentRecord[studType].append(i) except: print(line.strip('\n') + " is not valid. Not adding to database.") elif studType == "s": if "s" not in self.__studentRecord: self.__studentRecord["s"] = [] #default dictionary try: s = Student(line) self.__studentRecord["s"].append(s) except: print(line.strip('\n') + " is not valid. Not adding to database.") elif studType == "e": if "e" not in self.__studentRecord: self.__studentRecord["e"] = [] #default dictionary try: e = StudentEmployee(line) self.__studentRecord["e"].append(e) except: print(line.strip('\n') + " is not valid. Not adding to database.") else: print(line.strip('\n') + " was removed because type " + studType + " is not in the StudentRecord database.") count += 1 except FileNotFoundError: raise SystemExit("lab4in.txt" + " not found") def print(self): '''Function that orints each student type, followed by the list of student records of the corresponding type''' if "i" in self.__studentRecord: #key = i print ("\nInternational Students" + '\n' + '*' * 22) for i in range(0, len(self.__studentRecord["i"])): self.__studentRecord["i"].sort() self.__studentRecord["i"][i].print() print("Countries of origin: ", end="") print(", ".join(sorted(set(self.__countryList)))) print() if "e" in self.__studentRecord: #key = e print ("Employee Students" + '\n' + '*' * 22) for i in range(0, len(self.__studentRecord["e"])): self.__studentRecord["e"].sort() self.__studentRecord["e"][i].print() if "s" in self.__studentRecord: #key = s print ("Students" + '\n' + '*' * 22) for i in range(0, len(self.__studentRecord["s"])): self.__studentRecord["s"].sort() self.__studentRecord["s"][i].print() print() def addSalary(self): '''Function that gets salary for each student in the Student Employee type. It prompt the user for the pay rate and the hours worked and store them in the student object''' for i in range(0, len(self.__studentRecord["e"])): self.__studentRecord["e"][i].setSalary() def addCountry(self): '''Function that gets home country for each student in the International Student type. For each student in the International Student type, it prompts the user for the home country and store it in the student object. ''' for i in range(0, len(self.__studentRecord["i"])): self.__studentRecord["i"][i].setCountry() self.__countryList.append(self.__studentRecord["i"][i].getCountry()) def main() : r = StudentRecord() r.addSalary() r.addCountry() r.print() main()