blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
58293f1f659653a907d4e8bdd2f0f9ab59888f30
law35/Weekly-Expendature-Graph
/Bar charts.py
886
3.796875
4
"""Weekly expenditures:""" import matplotlib.pyplot as plt def draw_bar_graph(data, labels): num_bars = len(data) positions = range(1, num_bars + 1) plt.barh(positions, data, align = 'center') plt.yticks(positions, labels) plt.xlabel('Amount') plt.ylabel('Catagories') plt.title('Weekly Expenditures') plt.grid() plt.show() if __name__ == '__main__': costs = [] catagories = [] catagory = int(raw_input("Enter number of catagories:>> ")) while True: try: for i in range(catagory): cat = str(raw_input("Enter catagory:>> ")) catagories.append(cat) cost = float(raw_input("Enter expenditure:>> ")) costs.append(cost) except ValueError: print "**Error, invalid entry." draw_bar_graph(costs, catagories) query = str(raw_input("Are you ready to quit?(Y/N):>> ").upper()) if query == "Y": break
e4a741b36a99b4754efdcf0ae4173a2056909337
ranjithkumar121/Data_Structure
/linearsearch.py
288
4
4
def search(arr,n,x): for i in range(0,n): if(arr[i] == x): return i return -1 arr = [1,2,6,3,7,8] x = 1 n = len(arr) result = search(arr,n,x) if(result == -1): print("Element not found") else: print("Element found at index ",result)
b98135c387649a9c148ce47a926b84940124df05
cnguyen83/learn-python-hard-way
/ex3.py
778
4.125
4
# Print start statement. PEMDAS print "I will now count my chickens:" # Print hens and roosters. / * % go first print "Hens", 25.0 + 30.0 / 6.0 # 30 print "Roosters", 100 - 25 * 3 % 4 # 97 # Print eggs. % / left to right. print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # 7 print "Partial eggs:", 3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4 + 6 # Print comparison booleans print "Is it true that 3 + 2 < 5 -7?" print 3 + 2 < 5 - 7 # False print "What is 3 + 2?", 3 + 2 # 5 print "What is 5-7?", 5 - 7 # -2 # Print statements print "Oh, that's why it's False." print "How about some more." # Print more comparison booleans print "Is it greater?", 5 > -2 # True print "Is it greater or equal?", 5 >= -2 # True print "Is it less or equal?", 5 <= 2 # False
ef125de24f07904f2f39c524b4b39c63d8e88e4b
mikesorsibin/PythonHero
/Functions/function_rangecheck.py
336
3.78125
4
def ran_check(num,low,high): if num in range(low,high): print(f"{num} is in range of {low} and {high}") else: print(f"{num} not in range") ran_check(2,1,9) ran_check(2,3,9) def ran_check_bool(num,low,high): return num in range(low,high) print(ran_check_bool(2,1,9)) print(ran_check_bool(2,3,9))
830939a82ec23093671179b718f3ac02f112bdc8
michalisFr/last_will
/last_will/file_encryption.py
3,710
3.609375
4
from pretty_bad_protocol import gnupg from pathlib import Path import shutil def import_pubkey(pubkey): """This function takes as argument the public key filepath, reads the key from file and adds it to the keychain. The key will be used in encrypt_info to encrypt the file. It returns a gpg object that contains all the info of the keychain (that has only that one public key).""" gpg = gnupg.GPG(homedir='./keys') try: if Path(pubkey).exists(): try: with open(pubkey, 'rb') as key_file: data = key_file.read() gpg.import_keys(data) except OSError as e: return f"Can't open the public key file: {e}" elif not Path(pubkey).is_file(): return "The path to the public key file doesn't appear to be valid" else: return "An unknown error occurred, while trying to read the public key from file." # This is a design decision that hasn't been implemented, where you can give the public key as text instead of file. # This exception would be raised if pubkey was not a path but instead a long string, # in which case Path(pubkey).exists raises an OSError. except OSError: try: gpg.import_keys(pubkey) except Exception as e: return f"This doesn't seem to be a valid public key: {e}" return gpg def encrypt_info(gpg, info_file): """This function takes as arguments the gpg keychain and the filepath to the file to be encrypted It saves the file to disk and returns its path, which is ./file/<filename_as_it_was>.gpg""" if Path(info_file).exists() and Path(info_file).is_file(): key_id = gpg.list_keys()[0]['keyid'] # The keychain contains only one key (index=0), read the keyid of that key. name = Path(info_file).name suffix = Path(info_file).suffix encrypted_path = Path('files/') if not encrypted_path.exists(): Path(encrypted_path).mkdir() # Append the suffix .gpg to the file's filename. That way the filename of the original file is kept. encrypted_file = encrypted_path.joinpath(Path(f'{name}').with_suffix(suffix + '.gpg')) try: with open(info_file, 'rb') as message: try: with open(encrypted_file, 'wb') as encrypted: try: gpg.encrypt(message, key_id, output=encrypted) # Remove the public key from hard disk shutil.rmtree('./keys') except Exception as e: shutil.rmtree('./keys') return f"Fatal error. The file couldn't be encrypted. Error: {e}" except OSError as e: shutil.rmtree('./keys') return f"Fatal error. The target file couldn't be opened. Error: {e}" except OSError as e: shutil.rmtree('./keys') return f"Fatal error. The source file couldn't be opened. Error: {e}" return encrypted_file # This is a Path object else: # Remove the public key from hard disk shutil.rmtree('./keys') return f"Fatal error. The source file couldn't be found." if __name__ == '__main__': print( "If you want to run this script standalone, edit it and provide the necessary parameters to the function calls") gpg = import_pubkey('') # Path to public key if gpg is not None: print(encrypt_info(gpg, '')) # Path to file to encrypt # Remove the public key from hard disk shutil.rmtree('./keys')
346f3c1dd08de93850527f31a6eda27d0148a680
A-French-PngHash/PonziPyramidalSystem
/Client/mainclient.py
6,059
3.546875
4
from Client.hashing import * import requests import os import sys token = "" invitation_code = "" current_balance = 0 def welcome_message(): print( "Welcome to the \"Hoped Programm\" where you can begin to earn money in juste a few days ! All you need to do" " is recruit other persons.") def begin_menu(): print("1. Register") print("2. Login") print("3. Quit") choice = input("Your choice : ") while choice not in "123": os.system("clear") print("1. Register") print("2. Login") print("3. Quit") choice = input("Your choice : ") if choice == "1": os.system('clear') register_user() elif choice == "2": os.system('clear') login() elif choice == "3": sys.exit() def register_user(): print( "Be aware than you need an invitation code of a friend to register so if you don't have one you won't be able " "to register...") print("You will need to buy an entry ticket before registering.") payment_process() do_register_request() def payment_process(): # In a real ponzi pyramidal service you would introduce some kind of payment here print("Confirm the payment of the entry ticket (10€) by pressing Y.") letter = input() while letter.lower() != "y": letter = input() os.system('clear') print("Bravo ! Now you can access the system and you will soon be able to begin making some money.") def read_error_if_one(response): if response.status_code != 200: # Error happend, explanation of the error can be found in the error field of the respons if # the error was raised by the server json_response = response.json() print(f"Oups, there was an error (error code {response.status_code}) : ") if "error" in json_response.keys(): print(json_response["error"]) else: print(json_response) return True return False def do_register_request(): username = input("Please enter the username you want to use, please note that this must be a unique username : ") os.system('clear') print(f"Username : {username}") password = input( "Now enter a password. This password will be strongely encrypted but even with this encryption hackers can " "hack your password and steal all your revenues so please choose a strong password : ") os.system('clear') print(f"Username : {username}") print(f"Password : {password}") invitation_code = input("As said earlier you need to have an invitation code, please input it here : ") os.system('clear') print(f"Username : {username}") print(f"Password : {password}") print(f"Invitation Code : {invitation_code}") print("Thank you, your account is being created.") hashed_password = hash_password(password, username) response = requests.put("http://127.0.0.1:5002/login", params={ "username": username, "hash": hashed_password, "invited_by": invitation_code }) os.system('clear') json_response = response.json() if not read_error_if_one(response): print("Vous etes bien inscrit ! ") global token token = json_response["token"] def login(): username = input("Please enter your username : ") password = input("Please enter your password : ") password = hash_password(password, username) response = requests.get("http://127.0.0.1:5002/login", params={ "username": username, "hash": password }) os.system('clear') json_response = response.json() if not read_error_if_one(response): print("You logged in succesfully ! ") global token token = json_response["token"] def get_invite_code(): response = requests.get("http://127.0.0.1:5002/invite", headers={"Authentication": token}) if response.status_code != 200: read_error_if_one(response) return None json = response.json() return json["invite_code"] def get_current_balance(): response = requests.get("http://127.0.0.1:5002/money", headers={"Authentication": token}) if response.status_code != 200: read_error_if_one(response) return None json = response.json() return json["balance"] def retrieve_money(): amount = 0 while amount == 0: try: os.system('clear') amount = int(input("How much do you want to retrieve : ")) except: amount = 0 print("Please enter a number") response = requests.get("http://127.0.0.1:5002/money", headers={"Authentication": token}, params={"amount" : amount}) if response.status_code != 200: read_error_if_one(response) return None json = response.json() global current_balance print(f"{json['amount']}$ were succesfully retrieved ! You now have {round(current_balance - int(json['amount']), 2)}") def logged_menu(): global invitation_code global token global current_balance print(f"Your code to invite friends : {invitation_code}") print(f"Your current balance : {current_balance}$") print("-------------------") print("1. Disconnect") print("2. Retrieve money") choice = input() os.system("clear") while choice not in "12": os.system("clear") print(f"Your code to invite friends : {invitation_code}") print(f"Your current balance : {current_balance}$") print("-------------------") print("1. Disconnect") print("2. Retrieve money") choice = input() if choice == "1": token = "" elif choice == "2": retrieve_money() def main_loop(): welcome_message() while True: global token while token == "": begin_menu() global invitation_code invitation_code = get_invite_code() global current_balance current_balance = get_current_balance() logged_menu() main_loop()
8afef4475ea33fb0a914018d4ec80ba434ac66e6
RoanPaulS/Whileloop_Python
/divby_both_2_3.py
134
3.640625
4
first = 1; last = 100; while(first <= last): if(first%2 == 0 and first%3 == 0): print(first); first = first +1;
345fb68e8b72971feccbc4fecaa12f4c4e1cf4e4
Ayoabass/Whitt-Company
/2a.py
851
3.515625
4
from pulp import * prob = LpProblem("Problem 2.", LpMinimize) x1 = LpVariable('x_1', lowBound = 0) x2 = LpVariable('x_2', lowBound = 0) x3 = LpVariable('x_3', lowBound = 0) # Objective function prob += 3*x1 + 3*x2 + 5*x3, "Obj" # Constraints prob += 2*x1 + x3 >= 8 prob += x2 + x3 >= 6 prob += 6*x1 + 8*x2 >= 48 print(prob) prob.solve() print('status:' + LpStatus[prob.status]) ## Optimal for variable in prob.variables(): print("{}* = {}".format(variable.name, variable.varValue)) print('The Objective value = ',value(prob.objective)) # We add these lines for sensitivity analysis print('\n Sensitivity Analysis') for name, c in prob.constraints.items(): print('\n', name,':',c,',Slacks = ',c.slack,'Shadow Price =',c.pi) #reduced cost for v in prob.variables(): print('\n',v,name, '=', v.varValue, ', Reduced Cost =', v.dj)
12afde179467ad9e8262a1d5be5f85776f92dab8
Shubhamsingh7/Python-Exercise-File-
/euler 4.py
673
3.5625
4
import sys def prime(n): flag=0 for i in range(2,n//2): if n%i==0: flag=1 else: pass if flag==0: return True else: return False def palindrome(n): a=n i=0 num=0 while(n!=0): rem=n%10 num=num+rem*(10**i) i+=1 n=n//10 if a==num: return True else: return False for i in range(999,99,-1): for j in range(999, 99, -1): k=palindrome(i*j) if k==True: print(f"{i}*{j}={i*j}") sys.exit() else: print(f"{i}*{j}={i*j}")
500fcff3bc8d47ce5b847bbe9e5d6d2e98dc2b99
aminbeirami/dataVisualization
/Bar Charts/basicBarChartMatplot.py
282
3.5625
4
import matplotlib.pyplot as plt plt.bar([1,3,5,7,9],[5,2,3,6,8], label= 'example one', color = 'r') plt.bar([2,4,6,8,10],[3,6,7,2,1], label = 'example two', color = 'g') plt.xlabel = ('bar number') plt.ylabel = ('bar height') plt. title ('just a practice') plt.legend() plt.show()
b0e69fa86238add45dd66244891011549b3124b8
manmohanalla2/aisera
/challenge1.py
697
3.75
4
def three_percentage(string): counter = 0 value_holder = 0 result = False for i in string: if i.isdigit(): digit = int(i) if digit + value_holder == 10: if counter != 3: return False result = True value_holder = digit counter = 0 elif i == '%': counter = counter + 1 if result: return True return False print(three_percentage('arrb6%%%4xxb8l5%%%eee5')) print(three_percentage('acc%7%%sss%3rr1%%%%%%5')) print(three_percentage('5%%aaaaaaaaaaaaaaaaaaa%5%5')) print(three_percentage('9%%%1%%%9%%%1%%%9')) print(three_percentage('aa6%9'))
4d3f63f2a12b8008bc4954a88977671dafae0fe3
yezaki/pyCSV-1
/src/test/test_sample_csv_file.py
1,111
3.578125
4
# -*- coding: utf-8 -*- """ Unit test for sample_csv_file.py """ import sys sys.path.append('../') # 親ディレクトリの親ディレクトリを読み込む import unittest from sample_csv_file import csvfl_csvToList from sample_csv_file import csvfl_listToCsv newData = [] dataDir = r"C:\work\GitHub\pyCSV\data" csvFullPath = dataDir + r'\sample_data.CSV' class TestCsvFile(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_csvfl_csvToList(self): countRows = 0 countColumns = 0 global newData result, newData, countRows, countColumns = csvfl_csvToList (csvFullPath) self.assertEqual((1, 124118, 7), (result, countRows, countColumns)) def test_csvfl_listToCsv(self): global newData directory = dataDir + "\\" result, newName, countRows = csvfl_listToCsv (newData, True, directory, "newCsv") self.assertEqual((1, 124118), (result, countRows)) print('### The following file is created. => ' + newName) if __name__=='__main__': unittest.main()
44100ba7957a6ce497203d8eabf17d5a7182663a
legendofmiracles/dots
/bin/jonas
176
4.15625
4
#!/usr/bin/env python3 print("HALLO JONAS!") jonas = input("DU BIST DOCH JONAS, ODER? (Y/N)") if jonas == "Y": print("HALLO JONAS!") else: print("HAU AB! NUR JONASE DUERFEN DAS HIER NUTZEN")
ec4e5c686b6a954d6adc2f1bdd1a560c7ef2ba13
alxtt/Algorithms-and-Data-Structures
/books/Algorithms+DataStructures/binary_search.py
1,429
3.828125
4
import random """ Binary Search """ """ binary_search: returns index of key if found, -1 if not found. """ def binary_search(a, start, end, key): mid = start + (end-start)//2 if( key < a[mid] ): return binary_search(a,start,mid-1,key) elif(key > a[mid] ): return binary_search(a,mid+1,end,key) elif(key == a[mid] ): return mid return -1 """ binarySearch : return True if item is in List """ def binarySearch(alist, item): first = 0 last = len(alist)-1 found = False while first<=last and not found: midpoint = (first + last)//2 if alist[midpoint] == item: found = True else: if item < alist[midpoint]: last = midpoint-1 else: first = midpoint+1 return found from future import compiler_optimizations @compiler_optimizations def branch_and_bounds( A, optimal_branches ): hyper_p = map(A, sort(A)) R = hyper_p.binary_search( combinatorial_explosions(optimal_branches).all_permutations.select_features(combinations))) if( R.isOptimizable() ): hyper_p.python_combinatorial_compiler_optimizations() X,Y = hyper_p.split() hyper_p.compile() F = hyper_p.run( compiler_optimizations.select_partition(X,Y) ) return hyper_p.optimize_super_tuples( Y(F(X)) ) else: F = hyper_p.linear_models(compiler_optimizations.linear_executor(A,optimal_branches)) return F(A)
ae26fe4efb28a77c1efa0d2ee42331aee646ab89
deveshrattan/dsabeginning
/day3_quick.py
772
4
4
import random def partition(arr, low ,high): pivot=arr[high] i=low for j in range(i,high): if (arr[j]<=pivot): arr[j],arr[i]=arr[i],arr[j] i+=1 arr[i],arr[high]=arr[high],arr[i] return i def quicksort(arr, low, high): if(low<high): p=partition(arr,low,high) quicksort(arr,low,p-1) quicksort(arr,p+1,high) def display(arr): for i in range(n): print(arr[i],end=" ") print(end="\n") if __name__=="__main__": arr=[] n=int(input("Enter the lenght of an array ")) for i in range(n): arr.append(random.randrange(0,101,2)) print("The orignal array is ") display(arr) quicksort(arr,0,n-1) print("The array after sorting is ") display(arr)
94412e759cd91eb5d81d7b66374cba5d033d0088
dylanlee101/leetcode
/code_week32_1130_126/reorganize_string.py
1,172
3.5
4
''' 给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。 若可行,输出任意可行的结果。若不可行,返回空字符串。 示例 1: 输入: S = "aab" 输出: "aba" 示例 2: 输入: S = "aaab" 输出: "" 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reorganize-string ''' class Solution: def reorganizeString(self, S: str) -> str: if len(S) < 2: return S length = len(S) counts = collections.Counter(S) maxCount = max(counts.items(), key=lambda x: x[1])[1] if maxCount > (length + 1) // 2: return "" reorganizeArray = [""] * length eventIndex, oddINdex = 0, 1 halfLength = length // 2 for c, count in counts.items(): while count > 0 and count <= halfLength and oddINdex < length: reorganizeArray[oddINdex] = c count -= 1 oddINdex += 2 while count > 0: reorganizeArray[eventIndex] = c count -= 1 eventIndex += 2 return "".join(reorganizeArray)
20298562ef80226ac1886e4df38e1e2b1649666f
FKatenbrink/Advent-of-Code
/2018/day2_1.py
1,213
3.640625
4
import sys from collections import defaultdict def test_day2_1(): assert evaluate_line("abcdef") == (0, 0) assert evaluate_line("bababc") == (1, 1) assert evaluate_line("abbcde") == (1, 0) assert evaluate_line("abcccd") == (0, 1) assert evaluate_line("aabcdd") == (1, 0) assert evaluate_line("abcdee") == (1, 0) assert evaluate_line("ababab") == (0, 1) assert day2_1( "abcdef\nbababc\nabbcde\nabcccd\naabcdd\nabcdee\nababab") is 12 print("All tests successful.") def evaluate_line(line): characters = defaultdict(int) for c in line: characters[c] += 1 two = 0 three = 0 for _, val in characters.items(): if val is 2: two = 1 if val is 3: three = 1 return (two, three) def day2_1(input): line_values = [evaluate_line(line) for line in input.split("\n")] twos = sum([two for (two, _) in line_values]) threes = sum([three for (_, three) in line_values]) return twos * threes if __name__ == "__main__": if len(sys.argv) == 2: with open(sys.argv[1]) as file: print(f"Result for file input: {day2_1(file.read().strip())}") else: test_day2_1()
0bd06085ab2467bf5788f0ee12a066f7da05f96e
Una-zh/algorithms
/code_repo/topK.py
1,377
3.8125
4
# -- coding: utf-8 -- # author: una # datetime: 2019-09-02 16:09 """ 找第K大的数 """ # 1. 大根堆 def heap_sort(nums, k): """ :param nums: 无序数组 :param k: 第k大的数 :return: 返回第k大的数 """ n = len(nums) nums = [0] + nums # 将下标变成从1开始,方便计算 # 自下而上初始化大根堆 for i in range(n // 2, 0, -1): heap_adjust(nums, i, n) print(nums) # 输出最大的元素 nums[1], nums[n] = nums[n], nums[1] # 依次输出堆顶元素,然后重新调整(共k-1次),i表示待调整的数组的末尾的下标,n-k取不到 for i in range(n-1, n-k, -1): heap_adjust(nums, 1, i) nums[1], nums[i] = nums[i], nums[1] return nums[-k] def heap_adjust(nums, start, end): # tmp为需要调整的目标对象,先检查是否需要调整,如果不需要,函数返回 tmp = start # 保证该目标对象有子结点,如果没有子结点了,函数返回 while tmp <= end // 2: t = 2 * tmp # tmp的左子结点 if t < end and nums[t+1] > nums[t]: t += 1 if nums[tmp] >= nums[t]: break else: nums[tmp], nums[t] = nums[t], nums[tmp] tmp = t if __name__ == '__main__': a = [1, 4, 2, 6, 3, 7, 5, 8] k = 3 print(heap_sort(a, k))
2342388fae90ea279542f73ba4df69b9f8fd6398
kxu68/BMSE
/assignments/AY_2017_2018/semester_1/7/assignment/test_person.py
3,182
3.703125
4
""" Test Person :Author: Arthur Goldberg <[email protected]> :Date: 2017-12-09 :Copyright: 2017, Arthur Goldberg :License: MIT """ import unittest from person import Person, Gender, PersonError class TestGender(unittest.TestCase): def test_gender(self): self.assertEqual(Gender().get_gender('Male'), Gender.MALE) self.assertEqual(Gender().get_gender('female'), Gender.FEMALE) self.assertEqual(Gender().get_gender('FEMALE'), Gender.FEMALE) self.assertEqual(Gender().get_gender('NA'), Gender.UNKNOWN) with self.assertRaises(PersonError) as context: Gender().get_gender('---') self.assertIn('Illegal gender', str(context.exception)) class TestPerson(unittest.TestCase): def setUp(self): # create a few Persons self.child = Person('kid', 'NA') self.mom = Person('mom', 'f') self.dad = Person('dad', 'm') # make a deep family history ''' self.generations = 4 self.people = people = [] self.root_child = Person('root_child', Gender.UNKNOWN) people.append(self.root_child) def add_parents(child, depth, max_depth): if depth+1 < max_depth: dad = Person(child.name + '_dad', Gender.MALE) mom = Person(child.name + '_mom', Gender.FEMALE) people.append(dad) people.append(mom) child.set_father(dad) child.set_mother(mom) add_parents(dad, depth+1, max_depth) add_parents(mom, depth+1, max_depth) add_parents(self.root_child, 0, self.generations) ''' def test_set_mother(self): self.child.set_mother(self.mom) self.assertEqual(self.child.mother, self.mom) self.assertIn(self.child, self.mom.children) self.mom.gender = Gender.MALE with self.assertRaises(PersonError) as context: self.child.set_mother(self.mom) self.assertIn('is not female', str(context.exception)) def test_get_persons_name(self): self.assertEqual(Person.get_persons_name(self.child), self.child.name) self.assertEqual(Person.get_persons_name(None), 'NA') ''' def test_add_child(self): self.assertNotIn(self.child, self.mom.children) self.mom.add_child(self.child) self.assertEqual(self.child.mother, self.mom) self.assertIn(self.child, self.mom.children) self.assertNotIn(self.child, self.dad.children) self.dad.add_child(self.child) self.assertEqual(self.child.father, self.dad) self.assertIn(self.child, self.dad.children) def test_add_child_error(self): self.dad.gender = Gender.UNKNOWN with self.assertRaises(PersonError) as context: self.dad.add_child(self.child) self.assertIn('cannot add child', str(context.exception)) self.assertIn('with unknown gender', str(context.exception)) def test_remove_father(self): self.child.set_father(self.dad) self.child.remove_father() self.assertNotIn(self.child, self.dad.children) ''' if __name__ == '__main__': unittest.main()
a3b5f383f030bd206f866aaf7318124a68db1ee6
GriffithsLab/fooof-unit
/fooofunit/scores/score_correlation.py
1,055
3.515625
4
# -*- coding: utf-8 -*- """Correlation Coefficient score class""" import sciunit import numpy as np class CorrelationScore(sciunit.scores.Score): """A Correlation Score. A float in the range [-1.0,1.0] representing the correlation coefficient. """ _description = ('A correlation of -1.0 shows a perfect negative correlation,' 'while a correlation of 1.0 shows a perfect positive correlation.' 'A correlation of 0.0 shows no linear relationship between the movement of the two variables') _best = 1.0 def _check_score(self, score): if not (-1.0 <= score <= 1.0): raise errors.InvalidScoreError(("Score of %f must be in " "range -1.0-1.0" % score)) @classmethod def compute(cls, observation, prediction): """Compute whether the observation equals the prediction.""" return CorrelationScore(float(np.corrcoef(observation, prediction)[0,1])) def __str__(self): return '%.3g' % self.score
5864ca7b4e8dbae1637da47a60b9a8a6f040f602
erjan/coding_exercises
/the_number_of_the_smallest_unoccupied_chair.py
2,470
3.953125
4
''' There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number. For example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair number 2. When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct. Return the chair number that the friend numbered targetFriend will sit on. ''' ''' We will be using two min heaps, one for available chairs and the other for occupied chairs. Every time a new friend arrives, we will see that whether there is/are occupied chairs which can be free now(friend sat/sitting on such chairs has left or is leaving) then we pop these chairs from occupied chairs heap and push into available chairs heap. Then we pop the minimum number chair from available chairs heap and assign it to the current arrived friend and push it to occupied chairs heap. When the target friend arrives, we assign the applicable chair and return its number. ''' class Solution: def smallestChair(self, times: List[List[int]], targetFriend: int) -> int: friendsCount = len(times) targetFriendTime = times[targetFriend] times.sort(key=lambda x: x[0]) chairs = list(range(friendsCount)) heapq.heapify(chairs) # occupiedChairs will have values like this: [time till it is occupied, chair number] occupiedChairs = [] heapq.heapify(occupiedChairs) for arrival, leaving in times: # Vacate all the occupied chairs which are free by now. while occupiedChairs and occupiedChairs[0][0] <= arrival: _, chairAvailable = heapq.heappop(occupiedChairs) heapq.heappush(chairs, chairAvailable) smallestChairNumberAvailable = heapq.heappop(chairs) if arrival == targetFriendTime[0] and leaving == targetFriendTime[1]: return smallestChairNumberAvailable else: heapq.heappush(occupiedChairs, (leaving, smallestChairNumberAvailable))
d87010d0af0b0b174446bf75f4bc4a119539e575
jonathanschen/python_practice
/mitlab4stones.py
1,539
4.09375
4
start_pile = 100 max = 5 total_pile = start_pile p1 = [] p2 = [] while total_pile <= 100: p1_turn = int(raw_input("P1 pick a number between 1 and 5: ")) while p1_turn > max: print "Your response needs to between 1 and 5" p1_turn = int(raw_input("P1 pick a number between 1 and 5: ")) while p1_turn <= 0: print "Your response needs to between 1 and 5" p1_turn = int(raw_input("P1 pick a number between 1 and 5: ")) while p1_turn > total_pile: print "there aren't that many stones left" p1_turn = int(raw_input("P1 pick a number between 1 and 5: ")) p1.append(p1_turn) total_p1 = sum(p1) total_p2 = sum(p2) total_pile = total_pile - (p1_turn) print "There are %d total stones remaining" % total_pile if total_pile == 0: print "You picked the last stone, you win!!!" break p2_turn = int(raw_input("P2 pick a number between 1 and 5: ")) while p2_turn > max: print "Your response needs to between 1 and 5" p2_turn = int(raw_input("P2 pick a number between 1 and 5: ")) while p2_turn <= 0: print "Your response needs to between 1 and 5" p2_turn = int(raw_input("P2 pick a number between 1 and 5: ")) while p2_turn > total_pile: print "there aren't that many stones left" p2_turn = int(raw_input("P2 pick a number between 1 and 5: ")) p2.append(p2_turn) total_p1 = sum(p1) total_p2 = sum(p2) total_pile = total_pile - (p2_turn) print "There are %d total stones remaining" % total_pile if total_pile == 0: print "You picked the last stone. You win!!" break print "Game Over"
24df1675b31327b36e820a94b44a69cb6e0bcf1f
yagays/nlp100
/chp02/18.py
277
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- col = [] with open("data/hightemp.txt") as f: for line in f: l = line.rstrip().split("\t") col.append(l) sorted_col = sorted(col, key=lambda x: x[2], reverse=True) for c in sorted_col: print("\t".join(c))
c47ca67642b70fd09e5e8802beb51a29f3fe57e0
tangmaoguo/python
/learn_python/advanced_features/iterable.py
320
4.0625
4
#迭代器 from collections import Iterable from collections import Iterator print(isinstance([],Iterator)) print(isinstance({},Iterator)) print(isinstance('abc',Iterator)) print(isinstance((x for x in range(10)),Iterator)) print(isinstance(100,Iterator)) #把Iterable变成Iterator print(isinstance(iter([]),Iterator))
c91232cc8f00fc66a37340be80a2f579dd99d0dc
devbelloni/Exercicios_em_python
/ex010.py
117
3.859375
4
r=float(input('Digite o valor em reais... R$')) d=r/3.27 print('O valor de R${} em dólar é US${:.2f}.'.format(r,d))
4726c22d618edbae13f724e76ad12747e085664c
Rivarrl/leetcode_python
/leetcode/601-900/819.py
1,346
3.640625
4
# -*- coding: utf-8 -*- # ====================================== # @File : 819.py # @Time : 2019/11/27 23:44 # @Author : Rivarrl # ====================================== from algorithm_utils import * class Solution: """ [819. 最常见的单词](https://leetcode-cn.com/problems/most-common-word/) """ @timeit def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: """ 思路:字典 """ banned = set(banned) a, z, A, Z = ord('a'), ord('z'), ord('A'), ord('Z') j = k = 0 words = {} res = "" def update(j, k): nonlocal res word = paragraph[j:k].lower() if word and not word in banned: words[word] = words.get(word, 0) + 1 if words.get(res, 0) < words[word]: res = word for i, c in enumerate(paragraph): if a <= ord(c) <= z or A <= ord(c) <= Z: k = i + 1 else: update(j, k) j = i + 1 update(j, k) return res if __name__ == '__main__': a = Solution() a.mostCommonWord(paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]) a.mostCommonWord('a.', []) a.mostCommonWord("a, a, a, a, b,b,b,c, c", ["a"])
8992e04198f014d38447d700fa1b77dd962b54af
pushpanjay-kmr/video_transcoding_time_prediction
/Implementation_Python/socket_programming/prac/server.py
776
3.8125
4
#!/usr/bin/python # Import all from module socket from socket import * # Defining server address and port host = '' #'localhost' or '127.0.0.1' or '' are all same port = 52000 #Use port > 1024, below it all are reserved #Creating socket object sock = socket() #Binding socket to a address. bind() takes tuple of host and port. sock.bind((host, port)) #Listening at the address sock.listen(5) #5 denotes the number of clients can queue #Accepting incoming connections conn, addr = sock.accept() #Sending message to connected client conn.send('Hi! I am server') #send only takes string #Receiving from client data = conn.recv(1024) # 1024 stands for bytes of data to be received print data #Closing connections conn.close() sock.close()
7223e52658a063bc07e26c424aaef2a502a285c0
KlebanA/Python.lessons
/1.4.py
240
4.0625
4
a = int(input("Введите числитель: ")) b = int(input("Введите знаменатель: ")) if a < b: print("правильная дробь") else: print("неправильная дробь") # print Fraction
e7fda4a0d62271d37a255edf84c46401a6bbb110
daniel-reich/ubiquitous-fiesta
/cGaTqHsPfR5H6YBuj_11.py
170
3.75
4
def make_sandwich(i, f): b = [] for a in i: if a == f: b.append("bread") b.append(f) b.append("bread") else: b.append(a) return b
75474e6fce3e801ad8f01498314294fcad082110
mhdella/energy-market-deep-learning
/marketsim/model/energy_market.py
4,848
3.515625
4
class Bid(): """A bid that represents a price-quantity pair in the system.""" def __init__(self, label, price, quantity, band): self.label = label self.price = price self.quantity = quantity self.band = band def copy(self): return Bid(self.label, self.price, self.quantity, self.band) def to_dict(self): return { 'label':self.label, 'price':self.price, 'quantity':self.quantity, 'band':self.band, } class BidStack(): """Provides an api that handles bidstack calculations.""" def __init__(self): self.reset() def reset(self): self.stack = [] def add_price_quantity_bid(self, bid_obj): """Adds a price <> quantity bid for a given participant.""" self.stack.append( bid_obj ) def economic_dispatch(self, capacity_MW): """Takes a capacity_MW and returns modified bids accepted under economic dispatch.""" meritorder = sorted(self.stack, key=lambda k: k.price) accepted = [] cumulative_cap_MW = 0 # Loop through the sorted bids. for bid in meritorder: if cumulative_cap_MW + bid.quantity < capacity_MW: accepted.append(bid) cumulative_cap_MW += bid.quantity else: bid = bid.copy() bid.quantity = capacity_MW - cumulative_cap_MW accepted.append(bid) break return accepted def get_all_bids_dict(self): out = {} for bid in self.stack: label = bid.label out[label] = [] if not label in out else out[label] out[label].append(bid.to_dict()) return out class DispatchOrder(): def __init__(self, winning_bids): self.winning_bids = winning_bids def get_generator_dispatch(self): dispatch = {} for bid in self.winning_bids: if not bid.label in dispatch: dispatch[bid.label] = 0 dispatch[bid.label] += bid.quantity return dispatch class Market(): def __init__(self, participant_labels, dispatch_callback, initial_demand_MW): """ Takes a list of participant labels (strings). Also takes a dispatch callback, which is called when all bids are submitted. """ self.bidstack = BidStack() self.dispatch_callback = dispatch_callback self.timestep = 0 self.participant_labels = participant_labels self.demand_MW = initial_demand_MW self.step(initial_demand_MW) def step(self, demand_MW): """Called to step the market forward in time by one. """ self.timestep += 1 self.submitted = { p : False for p in self.participant_labels } self.demand_MW = demand_MW self.bidstack = BidStack() def reset(self, demand_MW): self.timestep = 0 self.step(demand_MW) def add_bid(self, participant_label, bids): """ Takes a participant_label string, and an array of bid objects """ self.submitted[participant_label] = True for bid in bids: self.bidstack.add_price_quantity_bid(bid) self.check_finished() def _get_state(self): # Perform economic dispatch to get a list of winning bids winning_bids = self.bidstack.economic_dispatch(self.demand_MW) # Generate a dispatch order object that stores a queriable result of the dispatch. dispatch_order = DispatchOrder(winning_bids) # Calculate the market price - price of winning bid marginal_price = winning_bids[-1].price # Get a dict containing each gen and amount dispatched dispatch = dispatch_order.get_generator_dispatch() state = { 'dispatch':dispatch, 'price':marginal_price, 'demand': self.demand_MW, 'all_bids':self.bidstack.get_all_bids_dict() } return state def check_finished(self): """ Checks whether all bids have been submitted. If not, returns false. If so, calls the dispatch callback and returns true. """ # Check if all have been submitted. for participant_label in self.submitted: if not self.submitted[participant_label]: return False # If we get to here, it means all submitted. # Get a dict to represent current market state. state = self._get_state() # Call the simulation's dispatch callback and pass it the market state. self.dispatch_callback(state) return True
304f08fd8acad398c49a9253bb1829cba5a0c3d7
JakeNTech/GCSE-Python-Code
/Arrays/arrays.py
346
3.71875
4
myString1="hello" print("1D ARRAY") for i in range(0,len(myString1)): print(myString1[i]) print("\n"*10) print("2D ARRAY") myString2=["Hello"," I am macintosh"] for a in range(0,len(myString2)): for b in range(0,len(myString2[a])): print(myString2[a][b]) myString3=["Hello"," I am macintosh"," And I have a habit of running hot"]
51e6d0a9096f97844ef495910eac6266a683494e
anunayarunav/MCMC-Deciphering
/utils.py
3,602
3.8125
4
import numpy as np import random from copy import deepcopy from copy import copy def az_list(): """ Returns a default a-zA-Z characters list """ cx = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') return cx def generate_random_permutation_map(chars): """ Generate a random permutation map for given character list. Only allowed permutations are alphabetical ones. Helpful for debugging Arguments: chars: list of characters Returns: p_map: a randomly generated permutation map for each character """ cx = az_list() cx2 = az_list() random.shuffle(cx2) p_map = generate_identity_p_map(chars) for i in xrange(len(cx)): p_map[cx[i]] = cx2[i] return p_map def generate_identity_p_map(chars): """ Generates an identity permutation map for given list of characters Arguments: chars: list of characters Returns: p_map: an identity permutation map """ p_map = {} for c in chars: p_map[c] = c return p_map def scramble_text(text, p_map): """ Scrambles a text given a permutation map Arguments: text: text to scramble, list of characters p_map: permutation map to scramble text based upon Returns: text_2: the scrambled text """ text_2 = [] for c in text: text_2.append(p_map[c]) return text_2 def shuffle_text(text, i1, i2): """ Shuffles a text given the index from where to shuffle and the upto what we should shuffle Arguments: i1: index from where to start shuffling from i2: index upto what we should shuffle, excluded. """ y = text[i1:i2] random.shuffle(y) t = copy(text) t[i1:i2] = y return t def move_one_step(p_map): """ Swaps two characters in the given p_map Arguments: p_map: A p_map Return: p_map_2: new p_map, after swapping the characters """ keys = az_list() sample = random.sample(keys, 2) p_map_2 = deepcopy(p_map) p_map_2[sample[1]] = p_map[sample[0]] p_map_2[sample[0]] = p_map[sample[1]] return p_map_2 def pretty_string(text, full=False): """ Pretty formatted string """ if not full: return ''.join(text[1:200]) + '...' else: return ''.join(text) + '...' def compute_statistics(filename): """ Returns the statistics for a text file. Arguments: filename: name of the file Returns: char_to_ix: mapping from character to index ix_to_char: mapping from index to character transition_probabilities[i,j]: gives the probability of j following i, smoothed by laplace smoothing frequency_statistics[i]: gives number of times character i appears in the document """ data = open(filename, 'r').read() # should be simple plain text file chars = list(set(data)) N = len(chars) char_to_ix = {c : i for i, c in enumerate(chars)} ix_to_char = {i : c for i, c in enumerate(chars)} transition_matrix = np.ones((N, N)) frequency_statistics = np.zeros(N) i = 0 while i < len(data)-1: c1 = char_to_ix[data[i]] c2 = char_to_ix[data[i+1]] transition_matrix[c1, c2] += 1 frequency_statistics[c1] += 1 i += 1 frequency_statistics[c2] += 1 transition_matrix /= np.sum(transition_matrix, axis=1, keepdims=True) return char_to_ix, ix_to_char, transition_matrix, frequency_statistics
6f6a2dd98239b59b5a9cbcb55dfedb19de6d5565
drcpcg/codebase
/Array/array-rotation-type.py
836
4.34375
4
# https://www.geeksforgeeks.org/type-array-maximum-element # descending, clockwise rotated or anti-clockwise rotated. # increasing or Ascending and rotated # decreasing or Descending and rotated def findArrayRot(a,n): i=0 while (i<n-1 and a[i]<a[i+1]): i+=1 if i==n-1: print("Ascending Array") if i==0: while i<n-1 and a[i]>a[i+1]: i+=1 if i==n-1: print("Descending Array") if a[0]<a[i+1]: print("Descending Rotated Array") else: print("Ascending Rotated Array") if i<n-1 and a[0]<a[i+1]: print("Descending Rotated Array") else: print("Ascending Rotated Array") a1=[1, 3, 5, 9] a2=[5, 3, 2, 1] a3=[2, 1, 5, 4] a4=[3, 4, 1, 2] findArrayRot(a3,len(a3))
b9dc4c1f20d9ac531cad7f9e2d08f52832b60fbb
waiteb15/py3forsci3day
/dicts_and_sets.py
1,475
3.703125
4
#!/usr/bin/env python """ Dict and set examples for KAPL class """ # builtin imports # 3rd-party (CPAN) imports # org imports # project imports def main(): """ Program entry point :return: None """ # get cmd line options dict_examples() set_examples() def dict_examples(): """ Examples of using dicts :return: None """ d1 = { 's2': [1, 4, 9, 8], 's3': [5, 8, 1, 7] } print(d1['s2']) print(d1['s2'][2]) d1['s4'] = [7, 6, 1, 9] print(d1) print(d1.keys()) print(d1.values()) print() for k, values in d1.items(): print(k, values) print() print(d1['s2']) print(d1.get('s2')) print(d1.get('x5')) print(d1.get('x5', [])) del d1['s4'] def set_examples(): """ Examples of using sets. :return: """ cities1 = {'Albany', 'Colonie', 'Saratoga Springs', 'Clifton Park'} cities2 = {'Clifton Park', 'Colonie', 'Latham', 'Troy', 'Schenectady'} print("Both:", cities1 & cities2) print("Just one:", cities1 ^ cities2) print("All:", cities1 | cities2) print('Just cities1:', cities1 - cities2) print('Just cities2:', cities2 - cities1) names = ['John', 'John', 'Jacob', 'Jingleheimer', 'Smith', 'Jacob'] print(set(names)) if __name__ == '__main__': # if run as script main()
f4b47d4b167bf351d49e9cbb825919fd19d37334
Yuri-Santiago/curso-udemy-python
/Seção 8/Exercícios/atv10.py
2,358
3.921875
4
""" 10 - Foi realizada uma pesquisa de algumas características físicas de cinco habitantes de certa região. De cada habitante foram coletados os seguintes dados: sexo, cor dos olhos (A - Azuis ou C - Castanhos), cor dos cabelos (L - Louros, P - Pretos ou C - Castanhos) e idade. - Faça uma função que leia esses dados em um vetor - Faça uma função que determine a média de idade das pessoas com olhos castanhos e cabelos pretos. - Faça uma função que determine e devolva ao programa principal a maior idade entre os habitantes - Faça uma função que determine e devolva ao programa principal a quantidade de indivíduos do sexo feminino cuja idade está entre 18 e 35 (inclusive) e que tenham olhos azuis e cabelos louros """ def leitura(sexo, cor_olhos, cor_cabelos, idade): vetor = [] sexo = sexo.upper() cor_olhos = cor_olhos.upper() cor_cabelos = cor_cabelos.upper() vetor.extend([sexo, cor_olhos, cor_cabelos, idade]) return vetor def idade_media_castanho_preto(pessoas): idades = 0 contagem = 0 for pessoa in pessoas: if 'C' in pessoa and 'P' in pessoa: idades += pessoa[3] contagem += 1 if contagem != 0: return idades / contagem return 0 def maior_idade(pessoas): maior = 0 individuo = 0 for pessoa in pessoas: if pessoa[3] > maior: maior = pessoa[3] individuo = pessoas.index(pessoa) + 1 return maior, individuo def feminino_azul_loiro(pessoas): quantidade = 0 for pessoa in pessoas: if 'A' in pessoa and 'L' in pessoa and 18 <= pessoa[3] <= 35: quantidade += 1 return quantidade lista = [leitura('f', 'A', 'l', 25), leitura('M', 'c', 'c', 20), leitura('m', 'C', 'p', 18), leitura('F', 'C', 'C', 18), leitura('m', 'C', 'l', 30)] for x in range(len(lista)): print(f'A pessoa número {x + 1} tem as características: {lista[x]}') print(f'A média de idade das pessoas com olhos castanhos e cabelos pretos é: {idade_media_castanho_preto(lista)}') print(f'A maior idade entre os habitantes é: {maior_idade(lista)[0]}, da pessoa de número {maior_idade(lista)[1]}') print(f'A quantidade de indivíduos do sexo feminino cuja idade está entre 18 e 35 (inclusive) e que tenham olhos azuis ' f'e cabelos louros é: {feminino_azul_loiro(lista)}')
be4aed99f181e5576f7853219b6c0fe7d2a3c8e0
Interloper2448/BCGPortfolio
/Python_Files/murach/exercises/ch14/movies/objects.py
323
3.5
4
class Movie: def __init__(self,name="",year=0): self.name = name self.year = year def getStr(self): return self.name + " ("+str(self.year)+")" def main(): mov = Movie() mov.name = "The Moleman" mov.year = 2050 print(mov.name, mov.year) if __name__ == "__main__": main()
f4ccc3922b61bc49aecd71a9f53e62f62f4d8442
dbutler20/ISAT252Lab1Butler
/lab9.py
761
3.53125
4
""" Lab 9 Classes """ #3.1 #3.2 class my_stat(): def cal_sigma(self,m,n): self.result=0 for i in range(n,m+1): self.result = self.result +i return self.result def cal_pi(self,m,n): self.result=1 for i in range(n,m+1): self.result=self.result *i return self.result def cal_f(self,m): if m==0: return 1 else: return m * self.cal_f(m-1) def cal_p(self,m,n): return self.cal_f(m)/self.cal_f(m-n) #3.3 my_cal = my_stat() print(my_cal.cal_sigma(5,3)) print(my_cal.cal_pi(5,3)) print(my_cal.cal_f(5)) print(my_cal.cal_p(5,3))
67c255e54c776a2271e39cbde8be6ec1ef85fbb5
younglua-wv/curso-em-video-python-mundo1
/antecessorESucessor.py
143
4.125
4
numero = int(input("Digite um número: ")) print(f"Analisando o valor {numero}, seu antecessor é {numero - 1} e o sucessor é {numero + 1}.")
8e39aeadc7634c01da963438ecdf907709ea0c30
daksh105/CipherSchool
/Assignment1/AlternateSort.py
280
3.890625
4
def AlternateSort(li): n = len(li) for i in range(n): if i == (n - i - 1): print(li[i]) break print(li[n - i - 1], end =" ") print(li[i], end = " ") li = list(map(int, input().split())) li.sort() AlternateSort(li)
24d62c6ddd9e9d7ddf1e47fa762d49cafdfa3a97
jeykarlokes/complete-reference-to-python3-programs
/python/nptel1.py
1,229
4
4
age = input("enter the age ") if age and (age >= 18 and age <=21): print("you are ok ") elif age and age < 18 : print("you are not eligible") else : print ("nooooooooo") # else: # print("enter the input please ") # rock paper scissors print(".....................") print("welcome to rock paper scissors game ") print(".....................") print(".....................") print(".....................") choice1 = input("enter the choice of the player 1 ;")) choice2 = input("enter the choice of the player 1 ;")) ch1 ,ch2,ch3= "rock","paper","scissors" #rock paper paper wins #paper scissors scisro wins #rock scissors rock wins if (choice1 == choice2): print("player2 give different input ") elif choce1 == ch1 and choice2 == ch2 : print("player2 wins") elif choce1 == ch2 and choice2 == ch1 : print("player1 wins") elif choice1 == ch2 and choice2 == ch3: print("player2 wins") elif choice1 == ch3 and choice2 == ch2: print("player1 wins") elif choice1 == ch3 and choice2 == ch1: print("player2 wins") elif choice1 == ch and choice2 == ch3: print("player2 wins") elif choice1 == ch2 and choice2 == ch3: print("player2 wins")
02cb91310ce122b1d985465a31509691cf87645a
Alexh99/NLP-Assignment1-Tweet-Classification
/Submit/twtt.py
1,099
3.75
4
import sys import preprocess def main(argv): if (len(argv) < 2 or len(argv) > 3): print "Wrong number or arguements" sys.exit(2) # Get command line arguements input_file_name = argv[0] output_file_name = argv[len(argv) - 1] #Last arguement input_file = open(input_file_name, 'r') data = input_file.readlines() input_file.close() if (len(argv) == 3): #Optional arguement group_number = int(argv[1]) #TODO: Make 5500 and 800,000 constants? first_half = data[group_number * 5500 : (group_number + 1) * 5500] last_half = data[800000 + group_number * 5500 : 800000 + (group_number + 1) * 5500] data = first_half + last_half #Process the tweet as per the steps in the assignment processed_tweets = preprocess.preprocess(data) #write results to the file output_file = open (output_file_name,'w') output_file.write(processed_tweets) output_file.close() if __name__ == "__main__": main(sys.argv[1:]) # command line arguements
983654d48aeea4996af91b6b717214cb4f46c255
LiyangLingIntel/HandsOnAlgorithms
/python/LeetCode/3_LongestSubstringWithoutRepeatingCharacters.py
1,035
4.125
4
""" Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. """ class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ s_dic = {} length = 0 start = -1 for i in range(len(s)): if s_dic.get(s[i], -1) > start: start = s_dic[s[i]] s_dic[s[i]] = i length = max(length, i - start) return length if __name__ == '__main__': inputs = ["abcabcbb", "bbbbb", "pwwkew"] s = Solution() for string in inputs: print(s.lengthOfLongestSubstring(string))
4afdb81389083b737200cc057149791dd237b7f3
Arman-Amandykuly/python-lessons
/TSIS1/day1/28.py
78
3.765625
4
txt = "Hello World" txt = txt.replace('H','J') #Replacing 'H' character by 'J'
cb3733b67539c459128f8b8495e7936575aafb5e
Aasthaengg/IBMdataset
/Python_codes/p02403/s457006428.py
217
3.59375
4
#coding:utf-8 h = 1 w = 1 while h+w != 0: h, w=input().rstrip().split(" ") h = int(h) w = int(w) if h == 0: if w==0: break for i in range(h): print("#"*w) print("")
36f9c59be09da2169d54cf160b33b525a10b38ed
alexandramilliron/Ratings-v2
/crud.py
1,044
3.515625
4
"""CRUD operations to populate the ratings database.""" from model import db, User, Movie, Rating, connect_to_db def create_user(email, password, name): """Create and return a new user.""" user = User(email=email, password=password, name=name) db.session.add(user) db.session.commit() return user def create_movie(title, overview, release_date, poster_path, genre): """Create and return a new movie.""" movie = Movie(title=title, overview=overview, release_date=release_date, poster_path=poster_path, genre=genre) db.session.add(movie) db.session.commit() return movie def get_movies(): return Movie.query.all() def get_movie_by_id(movie_id): return Movie.query.get(movie_id) def create_rating(score, movie, user): """Create and return a new rating.""" rating = Rating(score=score, movie=movie, user=user) db.session.add(rating) db.session.commit() return rating if __name__ == '__main__': from server import app connect_to_db(app)
172b525a570b43fa09fbf8e6c36fc35edd2ac99a
socodezuhair/aptlist
/aptlist.py
4,930
4
4
import random import string import csv # Define filename to store list of employees EMPFILE = 'employees.txt' OOOFILE = 'ooo.txt' # Function to add employee to list def addEmployee(): # Prompt to get employee name response = raw_input("Please enter employee name (to add): ") # Open file and save new employee's name to list with open(EMPFILE, "a") as myfile: myfile.write("%s\n" % response) # Function to remove employee from list def delEmployee(): # Prompt to get employee name response = raw_input("Please enter employee name (to remove): ") # Open file and read employees to a list (not efficient if list is very long, but works for us now) empList = open(EMPFILE).read().splitlines() # Remove employee from list empList.remove(response) # Write list back to file. First open file, then write employee list to file f = open(EMPFILE, 'w') for emp in empList: f.write("%s\n" % emp) # Function to print the list of groups def printGroupList(): # Generate employee list by reading from a file # empList = open(EMPFILE).read().splitlines() # print("%d total employees" % len(empList)) # print(empList) # # Handle OOO employees # oooList = open(OOOFILE).read().splitlines() # print(oooList) # print("%d OOO employees" % len(oooList)) # for oooEmp in oooList: # empList.remove(oooEmp) employeeList = [] empList = {} # Read employee list in csv format. csv.reader returns a tuple, that I can use to populate # my dictionary as I choose. data = csv.reader(open(EMPFILE, 'r')) for row in data: if row[0] not in empList: empList[row[0]] = [] empList[row[0]].append(row[1]) # Loop through all the employees for employee in empList: # The case where multiple people have the same first name if len(empList[employee]) > 1: # Resetting variables l = empList[employee] d = {} letters = [] counter = 1 # This is the array that holds the last name # of the people with the same first name, e.g. [Dost, Davidson, Davids, Hayden] # While the length of the array is > 0 while len(l) > 0: # Loop through and see how many last names have the first initial # and add to last name dictionary for x in range(len(l)): initial = l[x][0:counter] if initial not in d: d[initial] = [] d[initial].append(l[x]) # For all the first initials we read, see how many have more than one person # for that initial. For example, for D, we will have 3 and for H we will have 1 for letter in d: if len(d[letter]) == 1: # Remove this name from the array, so we don't process in the next iteration of the loop # using the previous example, we are removing Hayden after the first pass l.remove(d[letter][0]) # Add to another array, so we can delete from the dictionary. Python does not allow # dictionaries to mutate during an iteration letters.append(letter) # Remove from the dictionary and add to our employees list for letter in letters: employeeList.append("%s %s" % (employee, letter)) del d[letter] # Increment counter. # At this point, the array will not have Hayden and will only have the three Chris' with the last name starting with # the initial D. By incrementing the counter, we will look at the first two letters in the next iteration. This will # eliminate Dost. We will keep doing this until the array is empty and we come out of the WHILE loop above. counter = counter + 1 d = {} letters = [] else: # We didn't have multiple people with this first name, so we just add the first name. employeeList.append(employee) # Get the mod and div, to be used to create the groups later divMod = divmod(len(employeeList), 3) div = divMod[0]-1 mod = divMod[1] # Shuffle the list to generate random groups # This is where the magic happens random.shuffle(employeeList,random.random) #print("Shuffled list: %s" % empList) #Generate groups based on the numbers above. for x in range(div): print("Group #%d: %s" % (x, employeeList[0:3] )) del employeeList[0:3] # Print the final group print("Group #%d: %s" % (x+1, employeeList[0:mod+3])) del employeeList[0:mod+3] # Check the number of employees without a table # This can just be the length of our list of employees. If len(list) == 0, all employees have a seat if (len(employeeList) == 0): print("\nAll employees have a seat\n") else: print("\nThe following employees were not seated: %s\n" % employeeList) # Prompt user for what to do. print("Welcome to the Apartment List lunch table group generator!\n") print("Please choose from the following options:\n1.) Get seating chart\n2.) Add employee\n3.) Remove employee\n\n") response = raw_input("What would you like to do: ") if (response == '1'): printGroupList() elif (response == '2'): addEmployee() elif (response == '3'): delEmployee() else: print("Error: Input not recognized\n")
012d617c4dcffb5659c69105c153175e203e86b6
roozbehsaffarkhorasani/assignment4
/11.py
530
3.8125
4
import math print("a*(x^2) + b*x + c = 0") firstnumber = float(input("adad aval ro vared kon")) number2 = float(input("adad dovom ro vared kon")) number3 = float(input("adad sevom ro vared kon")) a = math.sqrt((number2 ** 2) - (4 * firstnumber* number3)) if a > 0: print("javab aval hast", ((-1 * number2) + a) / (2 * firstnumber)) print("javab dovom hast", ((-1 * number2) - a) / (2 * firstnumber)) elif a == 0: print("javab hast", (-1 * number2) / (2 * firstnumber)) else: print("bedeon javab")
cd5ae3dab94472ca5e0a32475ad97f6ceddd53fc
farmanAbbasi/farmanAbbasi-pythonAll3
/Stack & Queue Questions/nextLargestElementInArray.py
979
3.8125
4
# class Stack: # def __init__(self): # self.items = [] # def isEmpty(self): # return self.items == [] # def push(self, item): # self.items.append(item) # def pop(self): # return self.items.pop() # def peek(self): # return self.items[len(self.items)-1] # def size(self): # return len(self.items) def nextLargestNumber(arr): if arr==None or len(arr)==0: return [-1] s=[] a=[-1]*len(arr) for i in range(len(arr)): if(len(s)==0): s.append(i) j=i while(len(s)>0 and j<len(arr)-1): j=j+1 if arr[s[len(s)-1]] >arr[j]: s.append(i) else: a[s.pop()]=arr[j] j-=1 return a if __name__ =='__main__': print(nextLargestNumber([3,1]))
b63901a77610248be5aa1baaeca1625eb2bf4458
mrczl/Python-study
/1-1 Input.py
292
4.15625
4
# 1-1 input # input(prompt=None, /) # Read a string from standard input. print('----------1-1 Input---------') name = input("Please enter your name:->") age = input ("Please enter your age:->") print("Hi!,My name is "+name+",and I'm "+age+",Nice to meet you! \ Welcome to join our club.")
c66157dd6eee64c822cf30af0d7acc94cf103e79
aronnax77/python_uploads
/alg#010_chunky.py
824
4.59375
5
""" chunky.py Author: Richard Myatt Date: 15 January 2018 This is an algorithm which mirrors a question set for JS. Write a function that splits an array (first argument) into groups the length of size (the second argument) and returns them as a two-dimensional array. Please enter an array (list) of numbers followed by a positive integer at the prompt. For instance if you enter the list 0 1 2 3 4 5 6 7 8 followed by 2 the result should be [[0, 1], [2, 3], [4, 5], [6, 7], [8]]. """ def chunkArrayInGroups(arr, size): newArr = [] i = 0 while i < len(arr): newArr.append(arr[i : i + size]) i += size return newArr numList = [int(x) for x in input().split()] chunkSize = int(input()) print(chunkArrayInGroups(numList, chunkSize)) #print(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2))
d37b26ac05c1c3bf6f1df3ad0601e20233a5f6a5
AdamZhouSE/pythonHomework
/Code/CodeRecords/2621/60693/237467.py
276
3.859375
4
numbers=input().split(',') sum=int(numbers[0]) maxsum=sum for i in range(1,len(numbers)): if sum>0: sum+=int(numbers[i]) if sum>maxsum: maxsum=sum else: sum=int(numbers[i]) if sum>maxsum: maxsum=sum print(maxsum)
556747cb04ec1fbba2adddbbf401abf58d16d191
yoavh28/Space_Invaders
/Space Invader Game.py
5,931
3.578125
4
#Space Invaders - Part 1 import pip import turtle import os import math import random import time import pygame from pygame import mixer # Load the required library pygame.mixer.pre_init(44100,16,2,4096) pygame.init() #Situation In game -> 1 Lose -> 0 situation=1 #Set up screen wn=turtle.Screen() #change to full screen wn.screensize() wn.setup(width = 1.0, height = 1.0) wn.bgcolor("Black") wn.title("Space Invaders") wn.bgpic("SpaceInvaders_background.gif") #Register the shapes turtle.register_shape("invader.gif") turtle.register_shape("player.gif") #Draw border border_pen=turtle.Turtle() border_pen.speed(0) border_pen.color("white") border_pen.penup() border_pen.setposition(-300,-300) border_pen.pendown() border_pen.pensize(3) for size in range(4): border_pen.fd(600) border_pen.lt(90) border_pen.hideturtle() #Set score to 0 score=0 #Draw the score score_pen=turtle.Turtle() score_pen.speed(0) score_pen.color("white") score_pen.penup() score_pen.setposition(-290,270) scorestring="Score: " +str(score) score_pen.write(scorestring,False, align="left", font=("Arial", 14, "normal")) score_pen.hideturtle() #Create the player turtle player=turtle.Turtle() player.hideturtle() player.shape("player.gif") player.penup() player.speed(0) player.setposition(0,-250) player.setheading(90) player.showturtle() playerspeed=15 #Choose a number of enemies number_of_enemies=20 #Create an empty list of enemies enemies=[] #Add enemies to the list for i in range(number_of_enemies): #Create the enemy enemies.append(turtle.Turtle()) x_number=-200 for e in range(len(enemies)/2): x_number+=40 # Create the enemy enemies[e].hideturtle() enemies[e].shape("invader.gif") enemies[e].penup() enemies[e].speed(0) x=x_number y=200 enemies[e].setposition(x,y) enemies[e].showturtle() x_number=-200 for e in range(len(enemies)/2,len(enemies)): x_number+=40 # Create the enemy enemies[e].hideturtle() enemies[e].shape("invader.gif") enemies[e].penup() enemies[e].speed(0) x=x_number y=180 enemies[e].setposition(x,y) enemies[e].showturtle() enemyspeed=2 #Create the player's bullet bullet=turtle.Turtle() bullet.hideturtle() bullet.color("yellow") bullet.shape("triangle") bullet.penup() bullet.speed(0) bullet.setheading(90) bullet.shapesize(0.5,0.5) bulletspeed=20 #Define bullet state #Ready - ready to fire #fire - bullet is firing bulletstate="ready" #Move the player left and right def move_left(): x=player.xcor() x-=playerspeed if(x<-280): x=-280 player.setx(x) def move_right(): x=player.xcor() x+=playerspeed if(x>280): x=280 player.setx(x) #check if invaders get the positive side def check_posisides(enemies): x=enemies[0].xcor() for enemy in enemies: def fire_bullet(): #Declare bulletstate as a global if it needs a change global bulletstate if(bulletstate=="ready"): pygame.mixer.music.load("Laser Gun Sound Effect.mp3") pygame.mixer.music.set_volume(0.5) pygame.mixer.music.play(1) bulletstate="fire" #Move the bullet to just above the player x=player.xcor() y=player.ycor() + 10 bullet.setposition(x,y) bullet.showturtle() def isCollision(t1,t2): distance=math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2)) if(distance<25): return True else: return False #Create keyboards bindings turtle.listen() turtle.onkey(move_left,"Left") turtle.onkey(move_right,"Right") turtle.onkey(fire_bullet,"space") #Main game loop while (situation==1): for enemy in enemies: #Move the enemy x = enemy.xcor() x += enemyspeed enemy.setx(x) #Move the enemy back and down if(enemy.xcor()>280): #Move all enemies down for e in enemies: y=e.ycor() y-=40 e.sety(y) #Change enemy direction enemyspeed*=-1 if(enemy.xcor()<-280): #Move all enemies down for e in enemies: y = e.ycor() y -= 40 e.sety(y) #Change enemy direction enemyspeed *= -1 #Check for collision between the bullet and the enemy if (isCollision(bullet, enemy)): # Reset the bullet bullet.hideturtle() bulletstate = "ready" bullet.setposition(0, -400) # Reset the enemy x = random.randint(-200, 200) y = random.randint(-200, 200) enemy.setposition(x, y) pygame.mixer.music.stop() #Update the score score+=10 scorestring = "Score: " + str(score) score_pen.clear() score_pen.write(scorestring, False, align="left", font=("Arial", 14, "normal")) if (isCollision(player, enemy)or(enemy.ycor()<=-220)): pygame.mixer.music.load("Gameover Sound Effect.mp3") pygame.mixer.music.set_volume(0.5) pygame.mixer.music.play(1) player.hideturtle() bullet.hideturtle() for enemy in enemies: enemy.hideturtle() turtle.hideturtle() turtle.color("white") turtle.write("GAME OVER", move=False, align="center", font=("Arial", 26, "normal")) time.sleep(1) pygame.mixer.music.stop() situation=0 #Move the bullet if(bulletstate=="fire"): y=bullet.ycor() y+=bulletspeed bullet.sety(y) #Check to see if the bullet has gone to the top if (bullet.ycor()>275): bullet.hideturtle() bulletstate="ready" turtle.done() delay=raw_input("Press enter to finish")
ecbef2280175552f047fcb4e477bfdcfe86e194d
czrj-fun/example
/Python/一,基础语法/21.文件操作.py
215
3.859375
4
# 操作文件或者文件夹的相关技术 # 通过file函数打开指定位置文件 file = open("C://Users//zhangjian//Desktop//张健-3月份绩效.txt",mode='r'); # 输出文件中的内容 print(file.read())
e4800acb2eb611b8e3a04d7ad7f97504daf5a017
MarcosVRM/Exercices
/Alura/Games/forca.py
4,786
3.765625
4
from random import randrange import jogos def jogar(): mensagem_de_abertura() gerar_palavra() palavra_secreta = gerar_palavra() letras_acertadas = ocultar_palavra(palavra_secreta) acertou = False enforcou = False erros = 0 print("A palavra secreta tem {} letras".format(letras_acertadas.count("_"))) while not enforcou and not acertou: chute = pedir_chute() if chute in palavra_secreta: marcacao(chute, palavra_secreta, letras_acertadas) else: erros += 1 desenha_forca(erros) print(letras_acertadas) acertou = "_" not in letras_acertadas enforcou = erros == 7 if acertou: imprime_mensagem_vencedor() else: imprime_mensagem_perdedor(palavra_secreta) repetir() selecao_jogo() def marcacao(chute, palavra_secreta, letras_acertadas): index = 0 for letra in palavra_secreta: if chute == letra: letras_acertadas[index] = letra index += 1 def pedir_chute(): chute = input("Qual a Letra?") chute = chute.strip().upper() return chute def mensagem_de_abertura(): print('*' * 27) print('Bem vindo ao jogo de Forca!') print('*' * 27) def gerar_palavra(): arquivo = open("Fruit_list.txt", "r") palavras = [] for x in arquivo: palavras.append(x.strip()) arquivo.close() y = randrange(0, len(palavras)) palavra_secreta = palavras[y].upper() return palavra_secreta def ocultar_palavra(palavra_secreta): return ["_" for x in palavra_secreta] def repetir(): s = False n = False while not s and not n: print("Gostaria de tentar novamente?\nDigite S para sim e N para Não") x = input() x = x.strip().upper() if x == "S": s = True elif x == "N": n = True else: print("Por favor utilize S ou N") if s: jogar() elif n: print("Obrigado por jogar") def selecao_jogo(): s = False while not s: print("Utilize S para sim e N para Não") x =input("Voltar a seleção de jogos?") x = x.strip().upper() if x == "S": jogos.escolhe_jogo() elif x == "N": s = True def imprime_mensagem_vencedor(): print("Parabéns, você ganhou!") print(" ___________ ") print(" '._==_==_=_.' ") print(" .-\\: /-. ") print(" | (|:. |) | ") print(" '-|:. |-' ") print(" \\::. / ") print(" '::. .' ") print(" ) ( ") print(" _.' '._ ") print(" '-------' ") def desenha_forca(erros): print(" _______ ") print(" |/ | ") if(erros == 1): print(" | (_) ") print(" | ") print(" | ") print(" | ") if(erros == 2): print(" | (_) ") print(" | \ ") print(" | ") print(" | ") if(erros == 3): print(" | (_) ") print(" | \| ") print(" | ") print(" | ") if(erros == 4): print(" | (_) ") print(" | \|/ ") print(" | ") print(" | ") if(erros == 5): print(" | (_) ") print(" | \|/ ") print(" | | ") print(" | ") if(erros == 6): print(" | (_) ") print(" | \|/ ") print(" | | ") print(" | / ") if (erros == 7): print(" | (_) ") print(" | \|/ ") print(" | | ") print(" | / \ ") print(" | ") print("_|___ ") print() def imprime_mensagem_perdedor(palavra_secreta): print("Puxa, você foi enforcado!") print("A palavra era: {}".format(palavra_secreta)) print(" _______________ ") print(" / \ ") print(" / \ ") print("// \/\ ") print("\| XXXX XXXX | / ") print(" | XXXX XXXX |/ ") print(" | XXX XXX | ") print(" | | ") print(" \__ XXX __/ ") print(" |\ XXX /| ") print(" | | | | ") print(" | I I I I I I I | ") print(" | I I I I I I | ") print(" \_ _/ ") print(" \_ _/ ") print(" \_______/ ") if __name__ == "__main__": jogar()
c992cc45184564282099df45d6edc999b9ecbed8
vv31415926/python_lesson_04_UltraLite
/main.py
442
4.25
4
''' Написать любую функцию без параметров и функцию с параметрами Написать любую функцию с возвращаемым значением и без него Написать любую lambda функцию ''' def hi(): print('Всем привет!') def summa( a,b ): return a+b fLambda = lambda x,y: x+y hi() print( summa(3,2) ) print( fLambda(3,2) )
16bb271f93b5f03e1f4107f3789ec8a53fdd8d35
Nnigmat/Homeworks
/Sort_words_using_radix_sort.py
1,258
3.828125
4
''' Task: Write a program that takes as input N English words written in lower case, and sort them in lexicographic order. For example, if the input is blue red green then the output should be blue green red As another example, if the input is apples apple then the output should be apple apples Implement your program by using the radix sort. Note that there are 26 lower-case letters in English. As shown in the example, the lengths of the words can be different from each other. ''' def radix_sort(arr): max_length = -1 for el in arr: if len(el) > max_length: max_length = len(el) for i in range(len(arr)): arr[i] = arr[i] + ' ' * (max_length - len(arr[i])) for i in range(max_length - 1, -1, -1): count = [[] for _ in range(27)] delta = 96 for el in arr: if el[i] != ' ': count[ord(el[i]) - delta].append(el) else: count[0].append(el) arr = [] for array in count: for el in array: arr.append(el) return [el.strip() for el in arr] inp = open('input.txt', 'r') out = open('output.txt', 'w') out.write(' '.join(radix_sort(list(inp.readline().split(' '))))) inp.close()
9e76a48e7b47f29c88a30e7f12084f9ede8b1ec4
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/a5484b0e3bd240789005a33c83d4e800.py
115
3.765625
4
def word_count(string): string = string.split() return dict((word,string.count(word)) for word in string)
be0ef86355b98b4a2e0e014229603ef2a007c65d
joncrawf/aoc-2018
/day01/1.py
400
3.546875
4
from argparse import ArgumentParser def build_parser(): parser = ArgumentParser() parser.add_argument('--data-path', type=str, required=True) return parser def main(): args = build_parser().parse_args() with open(args.data_path) as file: data = file.read().splitlines() frequency = sum(map(int, data)) print(frequency) if __name__ == '__main__': main()
1c3a3100c7176915ea621635adade2692e1d03f4
atreadw1492/pyply
/pyply/pyply.py
6,022
4.125
4
import pandas import collections import functools def lapply(OBJECT, func, keys = None): """ lapply(OBJECT, func, keys = None) Based off R's lapply function. Takes a list, tuple, or dict as input, along with a function. The function is applied to every element in this object. lapply returns a dict. The keys of the dict are either the value of input 'keys' parameter or a default index. """ if is_list(OBJECT) or is_tuple(OBJECT): mapped = [func(x) for x in OBJECT] keys = keys if keys is not None else range(len(mapped)) result = {key : val for key,val in zip(keys , mapped)} return result elif is_dict(OBJECT): keys = OBJECT.keys() if keys is None else keys mapped = [func(x) for x in OBJECT.items()] result = {key : val for key,val in zip(keys , mapped)} return result else: raise Exception("Only lists, tuples, and dicts supported") def sapply(LIST , func, return_type = list): """sapply(LIST , func) Based off R's sapply function. Takes a list, tuple, or dict as input, along with a function. The function is applied to every element in this object. sapply returns a list. """ if return_type == list: return [func(x) for x in LIST] elif return_type == tuple: return tuple(func(x) for x in LIST) else: raise Exception("return_type must be list or tuple") def mode(OBJECT): """stats_mode(OBJECT) Computes simple statistical mode of a list or tuple. """ if not is_list(OBJECT) and not is_tuple(OBJECT): raise Exception("Input must be a list or tuple") counter = collections.Counter(OBJECT) max_count = max(counter.values()) result = [key for key,val in counter.items() if val == max_count] if len(result) == 1: return result[0] return sorted(result) def rapply(OBJECT, func, keys = None , _type = None): """ rapply(func , OBJECT, keys = None , _type = None) Based off R's rapply function. Takes a list, tuple, or dict as input, along with a function. The function is applied to each element in this object that has type = _type (the input parameter). For example, this can apply a function to all integers in a list of mixed types. rapply returns a dict, list, or tuple depending on the input. If a dict is returned, the keys are either the value of input 'keys' parameter or a default index.""" if is_list(OBJECT) or is_tuple(OBJECT): result = [x for x in OBJECT if type(x) == _type] return sapply(result , func) elif is_dict(OBJECT): keys = OBJECT.keys() if keys is None else keys result = {key : val for key,val in zip(keys, OBJECT)} result = {key : val for key,val in result.items() if type(val) == _type} return lapply(result , func, keys) else: raise Exception("Only lists, tuples, and dicts supported") def flatten(LIST): """flatten(LIST , recursive = True) Flattens a list of lists. """ if LIST == []: return [] if is_list(LIST[0]): return flatten(LIST[0]) + flatten(LIST[1:]) return LIST[:1] + flatten(LIST[1:]) def split(df,field): """ split(df,field) Based of R's split function. This splits a data frame into a list of subset data frames, split """ unique_field_values = list(set(field)) temp = {key : df[df[field] == key] for key in unique_field_values} return collections.OrderedDict(temp) def unsplit(df_list): """unsplit(df_list) Based off R's unsplit function. Appends a list of data frames and outputs a single data frame.""" return functools.reduce(lambda x,y: x.append(y) , df_list) def is_tuple(x): if type(x) == tuple: return True return False def is_list(x): if type(x) == list: return True return False def is_dict(x): if type(x) == dict: return True return False def is_int(x): if type(x) == int: return True return False def is_float(x): if type(x) == float: return True return False def is_str(x): if type(x) == str: return True return False def is_DataFrame(x): if type(x) == pandas.core.frame.DataFrame: return True return False def ifelse(EXPR , flow1 , flow2): """ifelse(EXPR , flow1 , flow2) Based off R's ifelse function. Single-line, functional version of if / else. """ if EXPR: return flow1 return flow2 def switch(EXPR , *args,**kwargs): """ switch(EXPR , *args,**kwargs) Based off switch function from R and other languages. switch offers a condensed version of a series of if / else statements. See github page for examples. """ if is_int(EXPR): if is_list(args[0]) or is_tuple(args[0]): return args[0][EXPR] else: return args[EXPR] elif is_str(EXPR): return kwargs[EXPR] else: raise Exception("'EXPR' must be an int or str")
d765c8ee99db6694ff32e9dd974af8420ab8ac37
julius1290/pythonProject
/main.py
1,125
4.03125
4
import math while True: try: userInput = float(input("Please give a circle radius:\n")) break; except ValueError: print("Please give a valid number") radius = float(userInput) area = (radius**2)*math.pi print(area) userInput = input("Give a comma seperatet list of numbers:\n") userInputAsList = userInput.split(', ') userInputAsTuple = tuple(userInputAsList) print("List: ", userInputAsList) print("Tuple: ", userInputAsTuple) devisibleList = [] for number in range(1500, 2701): if not number%7 and not number%5: devisibleList.append(number) print(devisibleList) userInput = input("Give a temperatur and a scala Celsius or Fahrenheit, e.g. '20,f' :\n") temperature = int(userInput.split(',')[0]) if userInput.split(',')[1] == 'f': newTemp = (9*temperature + (32 * 5)) / 5 print('%d°C is %.0f in Fahrenheit' % (temperature, newTemp)) else: if userInput.split(',')[1] == 'c': newTemp = (5*(temperature - 32)) / 9 print('%d°F is %.0f in Celsius' % (temperature, newTemp)) else: print("Unkown scala. Please use f for Fahrenheit or c for Celsius.")
f87db646dc2f0fd7a608f6e1664ee415d407a2a4
rtillmo/Python-coding
/Tidbits2/binary.py
166
3.875
4
def binary(): s="" n=(raw_input("Type a number:")) n=int(n) while n>0: r=n%2 s=str(r)+s n=n/2 print "the binary equivalent is", s binary()
36b6d77933b815c84ddbfa23a18f17e61aae2818
ilsersokolov/Otus
/hw01/data_gathering/gathering.py
11,061
3.703125
4
""" ЗАДАНИЕ Выбрать источник данных и собрать данные по некоторой предметной области. Цель задания - отработать навык написания программ на Python. В процессе выполнения задания затронем области: - организация кода в виде проекта, импортирование модулей внутри проекта - unit тестирование - работа с файлами - работа с протоколом http - работа с pandas - логирование Требования к выполнению задания: - собрать не менее 1000 объектов - в каждом объекте должно быть не менее 5 атрибутов (иначе просто будет не с чем работать. исключение - вы абсолютно уверены что 4 атрибута в ваших данных невероятно интересны) - сохранить объекты в виде csv файла - считать статистику по собранным объектам Этапы: 1. Выбрать источник данных. Это может быть любой сайт или любое API Примеры: - Пользователи vk.com (API) - Посты любой популярной группы vk.com (API) - Фильмы с Кинопоиска (см. ссылку на статью ниже) - Отзывы с Кинопоиска - Статьи Википедии (довольно сложная задача, можно скачать дамп википедии и распарсить его, можно найти упрощенные дампы) - Статьи на habrahabr.ru - Объекты на внутриигровом рынке на каком-нибудь сервере WOW (API) (желательно англоязычном, иначе будет сложно разобраться) - Матчи в DOTA (API) - Сайт с кулинарными рецептами - Ebay (API) - Amazon (API) ... Не ограничивайте свою фантазию. Это могут быть любые данные, связанные с вашим хобби, работой, данные любой тематики. Задание специально ставится в открытой форме. У такого подхода две цели - развить способность смотреть на задачу широко, пополнить ваше портфолио (вы вполне можете в какой-то момент развить этот проект в стартап, почему бы и нет, а так же написать статью на хабр(!) или в личный блог. Чем больше у вас таких активностей, тем ценнее ваша кандидатура на рынке) 2. Собрать данные из источника и сохранить себе в любом виде, который потом сможете преобразовать Можно сохранять страницы сайта в виде отдельных файлов. Можно сразу доставать нужную информацию. Главное - постараться не обращаться по http за одними и теми же данными много раз. Суть в том, чтобы скачать данные себе, чтобы потом их можно было как угодно обработать. В случае, если обработать захочется иначе - данные не надо собирать заново. Нужно соблюдать "этикет", не пытаться заддосить сайт собирая данные в несколько потоков, иногда может понадобиться дополнительная авторизация. В случае с ограничениями api можно использовать time.sleep(seconds), чтобы сделать задержку между запросами 3. Преобразовать данные из собранного вида в табличный вид. Нужно достать из сырых данных ту самую информацию, которую считаете ценной и сохранить в табличном формате - csv отлично для этого подходит 4. Посчитать статистики в данных Требование - использовать pandas (мы ведь еще отрабатываем навык использования инструментария) То, что считаете важным и хотели бы о данных узнать. Критерий сдачи задания - собраны данные по не менее чем 1000 объектам (больше - лучше), при запуске кода командой "python3 -m gathering stats" из собранных данных считается и печатается в консоль некоторая статистика Код можно менять любым удобным образом Можно использовать и Python 2.7, и 3 Зачем нужны __init__.py файлы https://stackoverflow.com/questions/448271/what-is-init-py-for Про документирование в Python проекте https://www.python.org/dev/peps/pep-0257/ Про оформление Python кода https://www.python.org/dev/peps/pep-0008/ Примеры сбора данных: https://habrahabr.ru/post/280238/ Для запуска тестов в корне проекта: python3 -m unittest discover Для запуска проекта из корня проекта: python3 -m gathering gather или python3 -m gathering transform или python3 -m gathering stats Для проверки стиля кода всех файлов проекта из корня проекта pep8 . """ import logging import sys from scrappers.scrapper import Scrapper from storages.file_storage import FileStorage from parsers.html_parser import HtmlParser import numpy as np import pandas as pd from itertools import islice # pd.set_option('display.height', 1000) pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) # pd.set_option('display.width', 1000) FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' SCRAPPED_FILE = 'scrapped_data.zip' TABLE_FORMAT_FILE = 'data.csv' LOG_FILE = 'gathering.log' #logger settings log_formatter = logging.Formatter(FORMAT) logger = logging.getLogger('gathering') logger.setLevel(logging.INFO) fh = logging.FileHandler(LOG_FILE) fh.setFormatter(log_formatter) logger.addHandler(fh) ch = logging.StreamHandler() ch.setFormatter(log_formatter) logger.addHandler(ch) def gather_process(): """ Scrap hotslog.com data to storage """ logger.info("gather") storage = FileStorage(SCRAPPED_FILE) scrapper = Scrapper() scrapper.scrap_process(storage) def convert_data_to_table_format(): """ extract data from storage to csv """ logger.info("transform") storage = FileStorage(SCRAPPED_FILE) data = storage.read_data() hp = HtmlParser() result = [] # data = dict(islice(data.items(), 10)) total_ids = len(data) num = 1 old_percent = -1 for id, html in data.items(): percent = int(num * 100 / total_ids) if percent > old_percent: logger.info('{}% done'.format(percent)) old_percent = percent try: dt = hp.parse(html) except Exception as ex: logger.error('error at user id = {}'.format(id)) raise ex dt['id'] = int(id) num += 1 result.append(dt) user_data = pd.DataFrame(result) cols = list(user_data) cols.insert(0, cols.pop(cols.index('Win %'))) cols.insert(0, cols.pop(cols.index('Total games'))) cols.insert(0, cols.pop(cols.index('Name'))) cols.insert(0, cols.pop(cols.index('Place'))) cols.insert(0, cols.pop(cols.index('id'))) user_data = user_data.ix[:, cols] user_data.set_index('id', inplace=True) user_data.to_csv(TABLE_FORMAT_FILE, index=False) def stats_of_data(): """ extract some statistics from csv """ logger.info("stats") user_data = pd.read_csv(TABLE_FORMAT_FILE, index_col=False) user_data.set_index('id', inplace=True) print(user_data.describe()) print('Как зависит % побед от числа игр?') print(user_data.groupby(pd.cut(user_data['Win %'],np.arange(45,67,1)))['Total games'].median()) print('Как зависит % побед от числа игр за класс Ambusher?') print(user_data.groupby(pd.cut(user_data['Win %'], np.arange(45, 66, 1)))['Ambusher games'].median()) print('Как зависит % побед от числа игр за класс Bruiser?') print(user_data.groupby(pd.cut(user_data['Win %'], np.arange(45, 66, 1)))['Bruiser games'].median()) print('Как зависит % побед от числа игр за класс Burst Damage?') print(user_data.groupby(pd.cut(user_data['Win %'], np.arange(45, 66, 1)))['Burst Damage games'].median()) print('Как зависит % побед от числа игр за класс Healer?') print(user_data.groupby(pd.cut(user_data['Win %'], np.arange(45, 66, 1)))['Healer games'].median()) print('Как зависит % побед от числа игр за класс Siege?') print(user_data.groupby(pd.cut(user_data['Win %'], np.arange(45, 66, 1)))['Siege games'].median()) print('Как зависит % побед от числа игр за класс Support?') print(user_data.groupby(pd.cut(user_data['Win %'], np.arange(45, 66, 1)))['Support games'].median()) print('Как зависит % побед от числа игр за класс Sustained Damage?') print(user_data.groupby(pd.cut(user_data['Win %'], np.arange(45, 66, 1)))['Sustained Damage games'].median()) print('Как зависит % побед от числа игр за класс Tank?') print(user_data.groupby(pd.cut(user_data['Win %'], np.arange(45, 66, 1)))['Tank games'].median()) print('Как зависит % побед от числа игр за класс Utility?') print(user_data.groupby(pd.cut(user_data['Win %'], np.arange(45, 66, 1)))['Utility games'].median()) if __name__ == '__main__': logger.info("Work started") if sys.argv[1] == 'gather': gather_process() elif sys.argv[1] == 'transform': convert_data_to_table_format() elif sys.argv[1] == 'stats': stats_of_data() logger.info("work ended")
ba6efde91089fd2659b82cdada59b956b47017bd
danielstabile/python
/exercicio 5.py
527
4.03125
4
#5 Escreva um programa que receba dois números e um sinal, e faça a operação matemática definida pelo sinal. n1 = int(input("Informe o primeiro numero: ")) n2 = int(input("Informe o segundo numero: ")) sinal = input("Informe o segundo numero: ") resultado = 0 sinal_ok = 1 if sinal == "+": resultado = n1 + n2 elif sinal == "-": resultado = n1 - n2 elif sinal == "*": resultado = n1 * n2 elif sinal == "/": resultado = n1 / n2 else: print("Operador invalido") sinal_ok = 0 if sinal_ok > 0: print(str(resultado))
c4be7aa01d56e6701f6f08940efe88e105388e54
rohit-kadam-hub/python-project
/Project_2_hello_YOU.py
448
4.34375
4
#Ask user for name name =input("What is your Name? : ") #Ask user for age age =input("What is your age ? : ") #ask user for city city = input("What city do you live in ? : ") #Ask user what they enjoy love=input("What do you love doing? : ") #Create output text string = "Your name is {} and you are {}yrs old and live in {} and you love {}" output = string.format(name,age,city,love) #print output screen print(output)
72b34d82d798c92c305e28869dfec6201e606539
ikramulkayes/University_Practice
/practice30.py
221
3.8125
4
lst = [2,53,-2,6,2] for i in range(len(lst)-1): for j in range(len(lst)-i-1): #bubble sorting if lst[j]>lst[j+1]: temp = lst[j] lst[j] = lst[j+1] lst[j+1] = temp print(lst)
c4784d117fb0b18720a5fa6080cb054a4495c664
jaweria332/GUI-with-Python
/Notepad.py
2,035
3.90625
4
#Import Tkinter, a library used for GUI in Python from tkinter import * #Importing filedialog from tkinter import filedialog #Importing messagebox from tkinter import messagebox #Declaring a root object root=Tk() #Define title of your window root.title("Gets Started with Python GUI") #Defining the windows size root.geometry("800x600+300+50") #Defining background color root.config(bg="#FFFFFF") #Declaring whether windows in resizable or not root.resizable(False, False) #Defining a functions #OPENFILE def openFile(): op=filedialog.askopenfile(title="Select File", filetypes=(("text file", ".txt"),)) if op!=None: lbl_name.config(text="FileName : "+str(op.name.split("/")[-1])) var_filename.set(str(op.name)) for i in op: txt_area.insert(END, str(i)) op.close() #SAVE AS def saveAs(): op=filedialog.asksaveasfile(title="Save As", filetypes=(("text file", ".txt"))) if op!=None: lbl_name.config(text="Filename : ") var_filename.set(str(op.name)) op.write(txt_area.get('1.0', END)) op.close() messagebox.showinfo("Save As", "File has been saved") #SAVE def save_file(): if var_filename.get()=="": saveAs() else: op=open(var_filename.get(), "w") op.write(txt_area.get('1.0', END)) op.close() messagebox.showinfo("Save", "File has been saved") #Defining buttons btn1=Button(root, text="Open", command=openFile) btn1.place(x=0, y=0, width=100) btn2=Button(root, text="Save", command=save_file) btn2.place(x=100, y=0, width=100) btn3=Button(root, text="Save As", command=saveAs) btn3.place(x=200, y=0, width=100) var_filename=StringVar() #Defining label for filename lbl_name=Label(root, text="FileName", font=("times new roman", 16, "bold")) lbl_name.place(x=50, y=50) txt_area=Text(root, font=("times new roman", 14, "normal"), bd=2, relief=RIDGE) txt_area.place(x=50, y=100, width=700, height=450) #Indicate to hold windows infinitely root.mainloop()
e154ffe65ae5fad51df0c58d72c95d2fdda292a0
ErinSmith04/Python-2018
/Magic_8_Ball_ErinSmith.py
685
4.0625
4
import random import time name = input("What is your name?: ") print("What's up %s! I can predict your future" %name) g_1 = "Yes" g_2 = "Outlook seems good" g_3 = "Results seems true" m_1 = "It seems unclear" m_2 = "Maybe..." m_3 = "I'm not saying no, but I'm not saying yea.." b_1 = "No" b_2 = "Fear the Future" b_3 = "Idk" answers = [g_1,g_2,g_3,m_1,m_2,m_3,b_1,b_2,b_3] while True: user_input = input("Please ask me a yes or no question or e[x]it.") if user_input.strip() == "x": print("Till we meet again... %s" %name) break else: print("Wait a mysterious 3 seconds... ^__^") time.sleep(3) print(random.choice(answers))
cd000608d0f956da717253e4a7d3589571957c21
Aish32/data-chronicles
/Core Concepts/Data Preprocessing/standardizing_and_scaling.py
732
3.609375
4
from sklearn.datasets import load_wine data = load_wine() X = data.features y = data.target # Split the dataset and labels into training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y) # Fit the k-nearest neighbors model to the training data knn.fit(X_train, y_train) # Score the model on the test data print(knn.score(X_test, y_test)) # Create the scaling method. ss = StandardScaler() # Apply the scaling method to the dataset used for modeling. X_scaled = ss.fit_transform(X) X_train, X_test, y_train, y_test = train_test_split(X_scaled, y) # Fit the k-nearest neighbors model to the training data. knn.fit(X_train, y_train) # Score the model on the test data. print(knn.score(X_test, y_test))
6e4af8dd72ef37ba5abe7ad478d7b25d0789d7b0
kudeh/automate-the-boring-stuff-projects
/character-picture-grid/character-picture-grid.py
1,034
3.65625
4
# character-picture-grid.py # Author: Kene Udeh # Source: Automate the Boring stuff with python Ch. 4 Project def rotate90(grid): """Rotates a grid 90 degrees Args: grid (list): a 2d list representing a grid Returns: grid (list): rotated copy of a 2d grid """ return list(zip(*grid[::-1])) def print2DGrid(grid): """Prints a 2D grid Args: grid (list): 2D grid Returns: None """ for row in range(len(grid)): for col in range(len(grid[row])): print(grid[row][col], end='') print() if __name__ == "__main__": grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] gridRotated = rotate90(grid) print2DGrid(gridRotated)
2c40e43be678e94d36611789dfabc001ae294b44
SuYoungHong/checkIO_solutions
/CheckIO/most_frequent_days.py
1,467
3.734375
4
__author__ = 'Su-Young Hong' __version__ = '0.1' __email__ = '[email protected]' __status__ = 'for fun' import datetime def most_frequent_days(year): """ :param year: integer, year you want to check :return: list, days which were most common days in that year """ reference = [('Monday', 0), ('Tuesday', 1), ('Wednesday', 2), ('Thursday', 3), ('Friday', 4), ('Saturday', 5), \ ('Sunday', 6)] firstDay = datetime.date(year, 1, 1) lastDay = datetime.date(year, 12, 31) firstWeek = range(firstDay.weekday(), 7) lastWeek = range(0, lastDay.weekday() + 1) Combined = firstWeek + lastWeek # combines last week and first week into one list maxFreq = max([Combined.count(i) for i in Combined]) # gets the most common frequency day's frequency in Combined MaxDays = [i for i in set(Combined) if Combined.count(i) == maxFreq] # gets days where maxFreq occurs freq_Days = [i[0] for i in reference if i[1] in MaxDays] return freq_Days if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert most_frequent_days(2399) == ['Friday'], "1st example" assert most_frequent_days(1152) == ['Tuesday', 'Wednesday'], "2nd example" assert most_frequent_days(56) == ['Saturday', 'Sunday'], "3rd example" assert most_frequent_days(2909) == ['Tuesday'], "4th example"
14827d4f4382cf7fe44d92baabbad12f0b7022ab
andrewparmar/python-tools
/python-practice/GeekforGeeks/bfs_graph_traversal_simple.py
676
3.875
4
class Graph(object): def __init__(self): self.graph = {} def add_edge(self, u, v): self.graph.setdefault(u, []).append(v) def BFS(graph, root): visited = [False] * len(graph.graph) queue = [] queue.append(root) stringer = [] while queue != []: node = queue.pop(0) stringer.append(node) visited[node] = True for i in graph.graph[node]: if not visited[i]: queue.append(i) print(" -> ".join([str(i) for i in stringer])) g = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) print(g.graph) BFS(g, 2)
28fe12fdf851d531e00df243fc0f1e0b422ee422
Mohammed-Shoaib/Coding-Problems
/Gulf Programming Contest/2019/pyramids/pyramids.py
372
3.78125
4
def tetrahedral(n): return n * (n + 1) * (n + 2) // 6 def pyramids(n, m): return tetrahedral(n) - tetrahedral(m) with open("pyramids.in", "r") as fin: with open("output.out", "w") as fout: n, m = map(int, fin.readline().split()) while n or m: fout.write(f'{pyramids(n, m)}\n') n, m = map(int, fin.readline().split())
3319313a5939bd97d4e876bb6b413b36f38f7915
gauravhansda/InterviewQuestions
/QuickSort.py
1,033
4
4
def main(): arr = [54, 26, 93, 17, 77, 31, 44, 55, 20] print "before sorting: ", arr quickSort(arr) print "after Sorting: ", arr def quickSort(arr): qSortHelper(arr, 0, len(arr) - 1) def qSortHelper(alist, start, end): if start < end: split_point = partition(alist, start, end) qSortHelper(alist, start, split_point - 1) qSortHelper(alist, split_point + 1, end) def partition(alist, start, end): pivot = alist[start] leftmark = start + 1 rightmark = end done = False while not done: while leftmark <= rightmark and alist[leftmark] <= pivot: leftmark += 1 while alist[rightmark] >= pivot and rightmark >= leftmark: rightmark -= 1 if rightmark < leftmark: done = True else: alist[leftmark], alist[rightmark] = alist[rightmark], alist[leftmark] alist[start], alist[rightmark] = alist[rightmark], alist[start] return rightmark if __name__ == '__main__': main()
d26aa92ca71e8b10402f076b1fcd45c6b432f351
paul-khouri/Flask_ReadingData_Searching_Inserting
/dbDeleting.py
1,311
3.90625
4
import sqlite3 # connect def db_Search(s): conn = sqlite3.connect('memberTable.sqlite') cur = conn.cursor() sql = 'select * from memberTable where lastName like "%{0}%" ' \ 'or address like "%{0}%" or suburb like "%{0}%" '.format(s) cur.execute(sql) result = cur.fetchall() conn.close() for x in result: print(x) def db_search_id(id): conn = sqlite3.connect('memberTable.sqlite') cur = conn.cursor() sql = 'select * from memberTable where memberID = {} '.format(id) cur.execute(sql) member = cur.fetchall() sql = 'select * from results where memberID = {} '.format(id) cur.execute(sql) results = cur.fetchall() conn.close() for x in member: print(x) for x in results: print(x) # delete given an ID def db_delete_id(id): conn = sqlite3.connect('memberTable.sqlite') cur = conn.cursor() sql ="delete from memberTable where memberID = {}".format(id) cur.execute(sql) conn.commit() sql ="delete from results where memberID = {}".format(id) cur.execute(sql) conn.commit() conn.close() my_search_id=input("Please enter an ID number: ") db_search_id(my_search_id) db_delete_id(my_search_id) #my_search=input("Please enter your search query: ") #db_Search(my_search)
65a388d0983b871be240fe402aeaa1d631017105
uyennguyen16900/leetcode-problems-and-variable-table
/coding.py
1,457
3.96875
4
# Given a sorted linked list, delete all duplicates such that each element appear only once. # head = 1->1->2 = 1->2 # curr = 2 def deleteDuplicates(head): """ :type head: ListNode :rtype: ListNode """ if head is None: return head curr = head while curr.next is not None: if curr.val == curr.next.val: curr.next = curr.next.next else: curr = curr.next return head # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # # Note: # # The number of elements initialized in nums1 and nums2 are m and n respectively. # You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. # m 0 # n 1 # l 0 def merge(nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ l = len(nums1) - 1 while n > 0 and m > 0: if nums1[m-1] <= nums2[n-1]: nums1[l], nums2[n-1] = nums2[n-1], nums1[l] l -= 1 n -= 1 else: nums1[l], nums1[m-1] = nums1[m-1], nums1[l] l -= 1 m -= 1 if n > 0: while n > 0: nums1[n-1] = nums2[n-1] n -= 1
f391fafab5bbc55bdeb48f9c975e0fd7e6326ca2
ctrlMarcio/feup-iart-proj1
/delivery/algorithm/genetic/crossover.py
7,003
3.71875
4
"""Holds crossover classes used in genetic algorithms. Classes: Crossover OnePointCrossover OrderCrossover """ from abc import ABC, abstractmethod import delivery.algorithm.operation.restriction as restriction import copy import random class Crossover(ABC): """The general abstract crossover class. Crossover, also called recombination, is a genetic operator used to combine the genetic information of two parents to generate new offspring. It is one way to stochastically generate new solutions from an existing population, and is analogous to the crossover that happens during sexual reproduction in biology. Solutions can also be generated by cloning an existing solution, which is analogous to asexual reproduction. Newly generated solutions are typically mutated before being added to the population. Being an abstract class, works as an interface in the sense that it obliges all crossovers to implement a run method. """ @abstractmethod def run(self, parent1, parent2): """Runs the crossover. Since it is an abstract method, the arguments are not required, but are present to assert a sort of convention, this is, every crossover function should receive this arguments to run properly. ... Args: parent1 (List[Path]): The first parent chromosome parent2 (List[Path]): The second parent chromosome Returns: (List[Path], List[Path]): The generated offsprings """ pass class OnePointCrossover(Crossover): """For each offspring, gets the first genes of a parent and the rest of the genes from the other parent. Given two parents, a random cut point is selected in the same place for both. The left part is taken from the first parent, completing the rest with non repeated genes from the second parent. Vice versa for a second offspring. """ def run(self, parent1, parent2): """Runs the one point crossover. ... Args: parent1 (List[Path]): The solution of the first parent parent2 (List[Path]): The solution of the second parent Returns: (List[Path], List[Path]): The two generated offsprings """ # generates the cut point [smaller, larger] = sorted( (parent1, parent2), key=lambda parent: len(parent)) min_size = len(smaller) cut_point = random.randint(1, min_size - 1) # starts the offsprings with the first part of the parents offspring1 = [] offspring2 = [] offspring1_hashes_source = set() offspring2_hashes_source = set() offspring1_hashes_destination = set() offspring2_hashes_destination = set() for idx in range(cut_point): gene1 = copy.copy(smaller[idx]) gene2 = copy.copy(larger[idx]) offspring1.append(gene1) offspring2.append(gene2) offspring1_hashes_source.add(gene1.hash_source()) offspring2_hashes_source.add(gene2.hash_source()) offspring1_hashes_destination.add(gene1.hash_destination()) offspring2_hashes_destination.add(gene2.hash_destination()) # finishes the building of the offspring with the other parent for idx in range(0, min_size): if restriction.valid_insert(offspring1_hashes_source, offspring1_hashes_destination, larger[idx]): offspring1.append(copy.copy(larger[idx])) if restriction.valid_insert(offspring2_hashes_source, offspring2_hashes_destination, smaller[idx]): offspring2.append(copy.copy(smaller[idx])) for idx in range(min_size, len(larger)): if restriction.valid_insert(offspring1_hashes_source, offspring1_hashes_destination, larger[idx]): offspring1.append(copy.copy(larger[idx])) return (copy.deepcopy(offspring1), copy.deepcopy(offspring2)) class OrderCrossover(Crossover): """For each offspring, gets a sequence of genes from the middle of a parent and the rest from the other parent. Builds offspring by choosing a subtour (between two random cut points) of a parent and preserving the relative order of bits of the other parent. Vice versa for a second offspring. """ def run(self, parent1, parent2): """Runs the order crossover. ... Args: parent1 (List[Path]): The solution of the first parent parent2 (List[Path]): The solution of the second parent Returns: (List[Path], List[Path]): The two generated offsprings """ # generates the cut points [smaller, larger] = sorted( (parent1, parent2), key=lambda parent: len(parent)) min_size = len(smaller) points = random.sample(range(1, min_size - 1), 2) [p1, p2] = sorted(points) # starts the offsprings with the sequence between the points in the parents offspring1 = [] offspring2 = [] offspring1_hashes_source = set() offspring2_hashes_source = set() offspring1_hashes_destination = set() offspring2_hashes_destination = set() for idx in range(p1, p2): gene1 = copy.copy(smaller[idx]) gene2 = copy.copy(larger[idx]) offspring1.append(gene1) offspring2.append(gene2) offspring1_hashes_source.add(gene1.hash_source()) offspring2_hashes_source.add(gene2.hash_source()) offspring1_hashes_destination.add(gene1.hash_destination()) offspring2_hashes_destination.add(gene2.hash_destination()) # finishes the building of the offspring with the other parent # inserts the genes to the left of the second point for idx in range(p2 - 1, -1, -1): # the range goes from the second point to 0 in reverse order if restriction.valid_insert(offspring1_hashes_source, offspring1_hashes_destination, larger[idx]): offspring1.insert(0, copy.copy(larger[idx])) if restriction.valid_insert(offspring2_hashes_source, offspring2_hashes_destination, parent1[idx]): offspring2.insert(0, copy.copy(smaller[idx])) # appends the genes to the right of the second point for idx in range(p2, min_size): if restriction.valid_insert(offspring1_hashes_source, offspring1_hashes_destination, larger[idx]): offspring1.append(copy.copy(larger[idx])) if restriction.valid_insert(offspring2_hashes_source, offspring2_hashes_destination, smaller[idx]): offspring2.append(copy.copy(smaller[idx])) for idx in range(min_size, len(larger)): if restriction.valid_insert(offspring1_hashes_source, offspring1_hashes_destination, larger[idx]): offspring1.append(copy.copy(larger[idx])) return (offspring1, offspring2)
6f430b8cc4d4b0cdc6b22e1958c9181ca818bdad
thomashigdon/poker-sim
/player.py
2,594
3.5625
4
import card_set import chip_stack import hand_scorer class Player(object): def __init__(self, name, starting_stack_amount): self.name = name self.stack = chip_stack.ChipStack(starting_stack_amount) self.hole = card_set.Hole() self.game_state = None # Set a player's activity state during a round. self.active = True # Set a player's calling state during a round. self.caller = False # Whether a player's out of money and can't play any more games. self.bust = False # How much I have in the pot this round so far. self.bet_amount = 0 def __str__(self): result = "" result += "Name: %s\n" % self.name result += str(self.stack) + "\n" result += str(self.hole) + "\n" return result def reset_for_hand(self): self.active = True def reset_for_round(self): self.caller = False self.bet_amount = 0 def set_active(self, bool): self.active = bool def set_game_state(self, game_state): self.game_state = game_state def accept_card(self, card): self.hole.add_card(card) def muck_cards(self): self.hole.reset() def act(self): """ A naive player that always calls. This is where the poker AI would go. One could also have some user input code here.""" self.call() print 'Pot is now: %d' % (self.game_state.pot.amount) def call(self): if self.game_state.current_bet: to_call = self.game_state.current_bet.amount - self.bet_amount bet_amount = self.game_state.current_bet.amount else: to_call = 0 bet_amount = 0 print '%s calls the bet of %d with %s' % (self.name, bet_amount, to_call) self.stack.emit(self.game_state.pot, to_call) self.caller = True def bet(self, amount): print '%s bets %d' % (self.name, amount) self.bet_amount = amount self.stack.emit(self.game_state.pot, amount) self.game_state.current_bet = Bet(self, amount) self.game_state.reset_callers() def fold(self): self.active = False self.muck_cards() def best_hand(self): return hand_scorer.HandScorer( card_set.Hand(self.game_state.board, self.hole)).best_hand() class Bet(object): def __init__(self, player, amount): self.player = player self.amount = amount
7b560c5192a5fbea60da3b0db8e054f70983fc46
solar1um/solarium
/dunders.py
815
3.625
4
# dunder method, magic methods # double underscore methods # isistence print(dir(1), type(1)) class CInt: def __init__(self, n): self.n = n def __add__(self, other): return f'sum is {self.n + other}' def __eq__(self, other): if self.n == other: return f'{self.n}, is equal to {other}' else: return f'{self.n} is not equal to {other}' # not equal def __ne__(self, other): if self.n != other: return f'{self.n} is not equal to {other}' else: return f'{self.n} is equal to {other}' def __str__(self): return f'number is {self.n}' def __repr__(self): return f'number issaafd {self.n}' c = CInt(5) # print(c + 10) # print(c == 10) # print(c != 5) print(c) print(repr(c.n))
617ec6a342cb58ba08c5da2d837f276a7f841513
neethupauly/Luminarmaybatch
/Fundamentals/raise_keyword.py
389
3.859375
4
# raise - keyword for exception printing # same number # no1=int(input("enter num1")) # no2=int(input("enter num2")) # if no1==no2: # raise Exception("two numbers are same") # else: # print(no2+no1) #age condition exception printing age=int(input("enter your age")) if age>18: print("eligible for vaccination") else: raise Exception("Exception occured..not eligible")
a6ac0f2d6cd586bed36db89ebce93582224c80b8
kailee-madden/Natural-Language-Processing
/hw2/incase.py
6,776
3.6875
4
for character in string.printable: for character2 in string.printable: sub = (character, character2) s = Transition(1, sub, 0) s2 = Transition(0, sub, 0) fst.add_transition(s) fst.add_transition(s2) ins = ("ε", character) i = Transition(0, ins, 0) fst.add_transition(i) delete = (character, "ε") d = Transition(0, delete, 1) fst.add_transition(d) fst.add_transition(Transition(0, ("</s>", "</s>"), 2)) fst.add_transition(Transition(1, ("</s>", "</s>"), 2)) fst.set_start(0) fst.set_accept(2) def unweightedT_m(new, old): fst = FST() with open(new) as f: content_new = f.read().splitlines() with open(old) as f: content_old = f.read().splitlines() content = content_new + content_old options = set() for line in content: for word in line.strip(): for character in list(word): options.add(character) for character in options: for character2 in options: fst.add_transition(Transition(1, (character, character2), 0)) fst.add_transition(Transition(0, (character, character2), 0)) fst.add_transition(Transition(0, ("ε", character), 0)) fst.add_transition(Transition(0, (character, "ε"), 1)) fst.add_transition(Transition(0, ("</s>", "</s>"), 2)) fst.add_transition(Transition(1, ("</s>", "</s>"), 2)) fst.set_start(0) fst.set_accept(2) return fst def unweightedT_m(new, old): fst = FST() with open(new) as new, open(old) as old: content_new = new.read().splitlines() content_old = old.read().splitlines() options = set() for line_new, line_old in zip(content_new, content_old): for word_new, word_old in line.strip(): for character in list(word): options.add(character) for character in options: for character2 in options: fst.add_transition(Transition(1, (character, character2), 0)) fst.add_transition(Transition(0, (character, character2), 0)) fst.add_transition(Transition(0, ("ε", character), 0)) fst.add_transition(Transition(0, (character, "ε"), 1)) fst.add_transition(Transition(0, ("</s>", "</s>"), 2)) fst.add_transition(Transition(1, ("</s>", "</s>"), 2)) fst.set_start(0) fst.set_accept(2) return fst def topological_sort(graph, key, path): path.append(key) for item in graph: if key == item[0][0][0][0]: key = item[1] if key not in path: topological_sort(graph, key, path) return path def viterbi(transducer): best_weights = {} best_transitions = {} sorted_states = topological_sort(transducer.states, transducer.start, []) for state in sorted_states: #print(transducer.transitions_to) for incoming_transition in transducer.transitions_to: #print(transducer.transitions_to[incoming_transition]) #print(incoming_transition) #self.transitions_to[t.r][t] = wt #print(transducer.transitions_to[incoming_transition[1]]) #print(incoming_transition[1]) #print(transducer.transitions_to[incoming_transition[1]][incoming_transition]) if state not in best_weights: best_weights[state] = transducer.transitions_to[incoming_transition][1] best_transitions[state] = incoming_transition elif transducer.transitions_to[incoming_transition][1] > best_weights[state]: best_weights[state] = transducer.transitions_to[incoming_transition][1] best_transitions[state] = incoming_transition else: continue transition_list = [] cur_state = sorted_states[len(sorted_states)-1] while cur_state != sorted_states[0]: transition = best_transitions[cur_state] transition_list.append(transition) cur_state = transition[1] character_changes = [] for i in reversed(transition_list): characters = i[0][1] char = characters[0] character_changes.append(char) predicted_lines = ''.join(character_changes) return predicted_lines #not sure if I should be accessing 1 or 0 for char def topological_sort_util(graph, v, visited, stack): visited[v] = True #print(graph[v][0][0][0]) for i in graph[v]: j = i[0][0][0] print(j) if visited[j] == False: topological_sort_util(graph, j, visited, stack) return stack.insert(0,v) def topological_sort(graph, vertices): visited = [False]*vertices stack = [] for i in range(vertices): #print(i) if visited[i] == False: topological_sort_util(graph, i, visited, stack) #print(stack) return stack def sort(graph, final_state): ordered_all = [] i = 0 while i < final_state[1]: ordered = [] for state in graph: if state[1] == i: ordered.append(state) if len(ordered) > 1: j = 0 for item in ordered: if j == item[0][1]: ordered_all.append(item) j += 1 else: ordered_all.append(state) i += 1 #print(ordered_all) return ordered_all def viterbi(transducer): best_weights = {} best_transitions = {} sorted_states = sort(list(transducer.states), transducer.accept) for state in sorted_states: #print(state) for incoming_transition, weight in transducer.transitions_to[state].items(): #print(incoming_transition.r) #print(weight) if state not in best_weights: best_weights[state] = weight best_transitions[state] = incoming_transition elif weight > best_weights[state]: best_weights[state] = weight best_transitions[state] = incoming_transition else: continue transition_list = [] cur_state = #the accept state #print(cur_state) #print(sorted_states[0]) while cur_state != #the start state: transition = best_transitions[cur_state] print(transition) print(transition.a) print(transition.r) transition_list.append(transition.a) cur_state = #the next state #figure out how to work backwards with the pointers character_changes = [] for i in reversed(transition_list): characters = i[0][1] char = characters[0] character_changes.append(char) predicted_lines = ''.join(character_changes) return predicted_lines #not sure if I should be accessing 1 or 0 for char
567841fc0a92ed105fee5074af5d843f19878962
harjothkhara/python_sandbox
/python_sandbox_starter/files.py
717
4.09375
4
# Python has functions for creating, reading, updating, and deleting files. # Open a file myFile = open('myfile.txt', 'w') # created a file # Get some info print('Name: ', myFile.name) # Name: myfile.txt # Is Closed : False # means is it closed within our script print('Is Closed : ', myFile.closed) # False print('Opening Mode: ', myFile.mode) # Opening Mode: w # Write to file myFile.write('I love Python') myFile.write(' and JavaScript') myFile.close() # Append to file myFile = open('myfile.txt', 'a') myFile.write(' I also like PHP') myFile.close() print('Is Closed : ', myFile.closed) # True # Read from file myFile = open('myfile.txt', 'r+') text = myFile.read(6) # read 6 characters print(text)
0df61cb8171e9fd875f27935ca2d967aec49f0e7
tylors1/Leetcode
/Problems/encodeMessage.py
816
4.21875
4
# Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". # Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid. def encode(s): curr = "" start = -1 res = [] for i in range(len(s)): if i == len(s)-1 or s[i] != s[i+1]: res.append(str(i-start)) res.append(s[i]) start = i curr = s[i] print res return ''.join(res) def decode(s): res = [] for i in range(len(s))[:-1:2]: res.append(s[i+1]*int(s[i])) return res s = "AAAABBBCCDAA" s = encode(s) print s print decode(s)
baf37d76fa5a3cf4f19173bb119fe88a1fcee752
quantumesx/EvolutionofCommunication
/Code/Helper.py
3,999
4.1875
4
"""Compute angles and coordinates.""" import math def find_ang(xy1, xy2, verbose=False): """ Find orientation of the vector linking x1, y1 to x2, y2. Note: this is 180d different from the vector linking x2,y2 to x1,y1. Validated: 03/04/19. """ x1 = xy1[0] y1 = xy1[1] x2 = xy2[0] y2 = xy2[1] dx = x2 - x1 dy = y2 - y1 if dx == 0 and dy == 0: if verbose: print('Error: the two points can not be the same') return 0 # 1st quadrant if dx >= 0 and dy >= 0: if dx != 0: rad = math.atan(abs(dy/dx)) ang_raw = math.degrees(rad) else: ang_raw = 90 # print('1st quadrant') # print(ang_raw) # 2nd quadrant elif dx < 0 and dy >= 0: if dy != 0: rad = math.atan(abs(dx/dy)) ang_raw = math.degrees(rad) + 90 else: ang_raw = 180 # print('2nd quadrant') # print(ang_raw) # 3rd quadrant if dx < 0 and dy < 0: # print('3rd quadrant') rad = math.atan(abs(dy/dx)) ang_raw = math.degrees(rad) + 180 # print(rad) # print(ang_raw) # 4nd quadrant if dx >= 0 and dy < 0: # print('4th quadrant') rad = math.atan(abs(dx/dy)) ang_raw = math.degrees(rad) + 270 # print(rad) # print(ang_raw) ang = ang_raw % 360 return ang def find_dx(x, ang, distance): """ Find change in x coordinate. Used in find_loc. Validated: 03/04/19. """ if ang < 0 or ang >= 360: ang = norm_ang(ang) # 1st quadrant if ang >= 0 and ang < 90: dx = distance * math.cos(math.radians(ang)) # 2nd quadrant elif ang >= 90 and ang < 180: dx = 0 - distance * math.sin(math.radians(ang - 90)) # 3rd quadrant elif ang >= 180 and ang < 270: dx = 0 - distance * math.cos(math.radians(ang - 180)) # 4th quadrant elif ang >= 270 and ang < 360: dx = distance * math.sin(math.radians(ang - 270)) return dx def find_dy(y, ang, distance): """ Find change in y coordinate. Used in find_loc. Validated: 03/04/19. """ if ang < 0 or ang >= 360: ang = norm_ang(ang) # 1st quadrant if ang >= 0 and ang < 90: dy = distance*math.sin(math.radians(ang)) # 2nd quadrant elif ang >= 90 and ang < 180: dy = distance*math.cos(math.radians(ang - 90)) # 3rd quadrant elif ang >= 180 and ang < 270: dy = 0 - distance*math.sin(math.radians(ang - 180)) # 4th quadrant elif ang >= 270 and ang < 360: dy = 0 - distance*math.cos(math.radians(ang - 270)) return dy def find_loc(xy, ang, distance): """ Given a point and an angle, find the new point. Used in all sorts of loc calculations. - x: current x coordinate - y: current y coordinate - ang: ang between current and new loc - distance between current and new loc Validated: 03/04/19 """ dx = find_dx(xy[0], ang, distance) dy = find_dy(xy[1], ang, distance) new_loc = xy[0] + dx, xy[1] + dy return new_loc def norm_ang(ang_raw): """ Arithmetics for angles. Validated: 03/05/19 """ if ang_raw >= 360: ang = ang_raw % 360 elif ang_raw < 0: ang = 360 + (ang_raw % -360) else: ang = ang_raw return ang def get_distance(loc1, loc2): """ Get distance between two points. Validated: 03/05/19 """ distance = math.sqrt((loc1[0]-loc2[0])**2 + (loc1[1]-loc2[1])**2) return distance def normalize(x, in_min=0, in_max=255, out_min=-5, out_max=5): """ Normalize a list of numbers betwen 0-255. Right now it's really just scaling. """ if x < in_min or x > in_max: print("Error: input exceed input range") raise scaled_x = (x - in_min) / (in_max - in_min) * (out_max - out_min) + out_min return scaled_x
3bc6e5afaa49596c4c3761eb69046b675f518680
ParulProgrammingHub/assignment-1-gaganlotey
/q1.py
123
3.71875
4
l=int(input("enter the length of a rectangle")) b=int(input("enter the breath of a rectangle")) a=l*b p=2*(l*b) print(a,p)
36c6baa33a62626609d261102b135842528a1e52
Pythonjowo/Fundamental_banget2020
/RIdwan Ilyas/part 12.py
118
3.71875
4
x = input('Masukkan bilangan') x = int(x) if x % 2==0: print('Bilangan Genap') else: print('Bilangan ganjil')
692524ce0c50f163f689012b504756e3a8923593
clintmthompson/Sweepstakes
/sweepstakes.py
1,658
3.8125
4
from contestants import Contestant import random class Sweepstakes: def __init__(self, name): self.name = name self.contestants_list = [ { "first_name": "Bill", "last_name": "Dauterive", "email": "[email protected]", "registration_number": 1 }, { "first_name": "Hank", "last_name": "Hill", "email": "[email protected]", "registration_number": 2 }, { "first_name": "Rusty", "last_name": "Shackleford", "email": "[email protected]", "registration_number": 3 }, ] def register_contestant(self, contestant): new_contestant = contestant self.contestants_list.append({'first_name': new_contestant.first_name, 'last_name': new_contestant.last_name, 'email': new_contestant.email, 'registration_number': new_contestant.registration_number}) def pick_winner(self): winner = self.contestants_list[random.randint(0, len(self.contestants_list)-1)] self.print_contestant_info(winner) return winner def print_contestant_info(self, contestant): for people in self.contestants_list: if people['first_name'] != contestant['first_name']: print(f"{people['first_name']} {people['last_name']}, please congratulate our winner, {contestant['first_name']} {contestant['last_name']}!!!") else: print(f"Hello {contestant['first_name']} {contestant['last_name']}, you are our grand prize winner!!!")
1a50db09a719e429306de92a56df37ab7b774569
qq915522927/python-
/python_study/算法/迪克斯特拉算法.py
2,040
3.875
4
# coding=utf8 ''' 迪克斯特拉算法用于解决加权图的最小路径问题,适用于有向无环图 总体分为4步 1. 找出最便宜的节点 2. 计算该节点的各个邻居的开销 3. 重复第一步找出最便宜的节点 4. 重复第二部更新该节点邻居的开销 ''' ''' 具体实现步骤: 1.首先需要三个散列表 第一个表用来储存图结构 {'start':{'A':6,'B':2},'A':{'end':1},'B':{'A':3,'end':5},'end':{}} 每一个键值对的值表示该节点下邻居节点以及开销。 第二个表用来存放到各个节点的总开销 costs = {'A':6,'B':2,'end':float('inf')} 第三个表用来记录各个节点的父节点,以记录完整路径 结构如下: ''' graph = {'start':{'A':6,'B':2},'A':{'end':1},'B':{'A':3,'end':5},'end':{}} costs = {'A':6,'B':2,'end':float('inf')} parents = {'A':'start','B':'start','end':''} #处理过的节点列表 processed = [] def find_lowest_node(l): lowest_cost = float('inf') lowest_cost_node = None for node in l: cost = l[node] if cost < lowest_cost and node not in processed: lowest_cost = cost lowest_cost_node = node return lowest_cost_node node = find_lowest_node(costs) while node: #该节点的开销 cost = costs[node] #该节点的邻居 neighbors = graph[node] for n in neighbors.keys(): #邻居节点的新开销 new_cost = cost + neighbors[n] if new_cost < costs[n]: #判断新的开销是否更小,是的化跟新对应节点的costs,同时跟新parents costs[n] = new_cost parents[n] = node processed.append(node) #找出接下来要处理的节点 node = find_lowest_node(costs) route_list = [] def get_route(l,parent): pre = l.get(parent,None) if pre: route_list.append(pre) get_route(l, pre) else: return get_route(parents,'end') route = '-'.join(route_list[::-1]) print '到达终点最少开销为{},路径为{}'.format(costs['end'],route)
389760781784074d77569fd1f0911a238e02657a
eddiewu6/LeetCode
/326. Power of Three.py
385
3.9375
4
#Idea: find the maximum integer of power of 3, and check the residule of that number % n #O(1) in time, O(1) in space #AC in 250ms class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ return n > 0 and 1162261467 % n == 0 #1162261367 is the maximum numbder of power of 3 within the range of 32bit integer.
efd4543579c42e75a178c7d25c2b41d5e86f53b7
psmzakaria/Practical-1-2
/Practical2Q2.py
873
4
4
# Given weightages are represented as below and are universal MIDSUMMERTEST = 0.20 ASSIGNMENT1 = 0.25 ASSIGNMENT2 = 0.35 GENERALPERFORMANCE = 0.20 # User input of scores gradeMidSummerTest = int(input("Enter your Midsummer test scores")) gradeAssignment1 = int(input("Enter your Assignemt1 test scores")) gradeAssignment2 = int(input("Enter your Assignemt2 test scores")) gradeGeneralPerformance = int(input("Enter your General Performance scores")) # Calculate weighted average weightSummer = (gradeMidSummerTest/100)*MIDSUMMERTEST weightAssign1 = (gradeAssignment1/100)*ASSIGNMENT1 weightAssign2 = (gradeAssignment2/100)*ASSIGNMENT2 weightGeneral = (gradeGeneralPerformance/100)*GENERALPERFORMANCE # Call function to calculate the weighted average def sumAvgWeight(): return ((weightSummer+weightAssign1+weightAssign2+weightGeneral)*100) print(sumAvgWeight())
84be4d95894f6b594d3ec29e67405d64a2f437bc
shiwuhao/python
/file/somescript.py
135
3.5
4
# /usr/bin/env python3 import sys text = sys.stdin.read() words = text.split() wordcount = len(words) print('WorldCount:', wordcount)
f8945c1ed591541c48aa7fd7eed5c634612645cb
daniel-reich/turbo-robot
/Ddmh9KYg7xA4m9uE7_20.py
474
4
4
""" Write a function that transforms all letters from `[a, m]` to `0` and letters from `[n, z]` to `1` in a string. ### Examples convert_binary("house") ➞ "01110" convert_binary("excLAIM") ➞ "0100000" convert_binary("moon") ➞ "0111" ### Notes Conversion should be case **insensitive** (see example #2). """ def convert_binary(string): s='' for i in string.lower(): if ord(i)<110: s+='0' else: s+='1' return s
f06901a14879b269d2d75334f97152c9ff85c8f0
ecstowe/AFS505_u1
/assignment4/ex36.py
3,729
3.921875
4
from sys import exit def finish_line(): print("Holy shit it worked. The Fascists are obliterated.") print("You won!") finish_line() def gate_start(): print("""You are at the top of your favorite ski run, you look left and see the Jesus themself strapping into their skis. \n You look right and see Stalin taking one last drag one off his cigar. \n In front of you is your middle school math teacher holding a large flask of liquid LSD. \n 'To the victor goes the spoils!' The teacher yells into the crisp morning air.""") print("""You know Stalin to be an incredible skiier, and Jesus is sure to cheat. \n you think to yourself 'I have to start strong.' \n There is a large rock in front of you. \n Do you veer left and cut off the son of god, try to launch over the rock (type launch) or right into the hulking mass of Stalin?""") choice = input(">") if choice == "left": print(" You duck under Jesus' gaudy out-dated robe and launch into first place.") elif choice == "right": print("Stalin punches you square in the face and you fall into a pillow of powder snow. Do you get back up? Y or N?") get_up = input(">") if get_up == "Y": pass else: print("You don't deserve the spoils anyway, brush yourself off, you're in last place.") else: print("You eat shit over the rock and are relegated to last place. But the race is has just started, carry on!") gate_start() def bear_encounter(): print("You are in the midst of wondering how the heck you got into this situation when a bear steps into the ski run.") print("You are faced with some options here. \n You need the bear to move. \n Do you head butt (head) or use a ski pole as a joust (joust)?") head_joust = input(">") if head_joust == "head": print("""That was a really dumb idea. Do I even need to explain why? \n No, but I will. The bear rips your helmet off, allong with your headphones. \n No more beats for you on this epic ride.""") elif head_joust == "joust": print("Hell yea! Skewered bear balls for dinner tonight! Provided you beat those two fascists in this race and don't die.") else: print("Looks like you F'd that up, heres another bear, try again.") bear_encounter() bear_encounter() def silos(): print("""You're either in first or last at this point (I'm not sure, as I'm just a computer), but you think to yourself: \n 'Gee, sure would be nice to ensure my victory in this race and snag that big 'ol vial of Electric Kool-Aid. \n So you're on the lookout for options.""") print("And just as luck would have it, you see a shiny metal dome in the trees. So you veer towards it.") print("Oh boy, its a Soviet missile silo! Did I forget to mention your favorite ski run is in Siberia now?") print("This is your opportunity, you ponder launching these missiles at your opponents. But you need a code.") print("Do you search the trees for a carving of the four digit code you need (trees), do you check you body for new tatoos (tats) or make something up (make)?") silos = input(">") if silos == "trees": print("You find a carving: 'Putin has a small Дик', fall into a tree well and die.") elif silos == "tats": print("Dude, you need to lay off the ketamine, how'd that new tat get there? You enter the code and launch the missiles right into Stalin and Jesus.") elif silos == "make": print("Think of something quick, that countdown timer just started out of nowhere. Guess your 4 numbers.") make = input() number_correct = False while True: if "1" in make or "7" in make and not number_correct: finish_line() else: print("That's not a number.") else: silos() silos()
b96dd3d9a09cc4f7c19b396ed74c1e2efb945ee9
Bappy200/Python
/learing_python/try_catch.py
198
3.90625
4
try: age=int(input("Enter your age : ")) income=2000 rick=income/age print(rick) except ValueError: print("Invalid Age") except ZeroDivisionError: print("Age not be 0 !")
6e68d627c61dc22d8793c9c312b116272ddc4c2f
rielaben/Final_Project
/calcs_vis.py
7,300
3.625
4
import unittest import sqlite3 import json import os import matplotlib import matplotlib.pyplot as plt import numpy as np from scipy import stats from numpy import percentile import csv def setUpDatabase(db_name): '''This function takes in the name of the database and creates a connection and cursor to it. It returns the cursor and connection.''' path = os.path.dirname(os.path.abspath(__file__)) conn = sqlite3.connect(path+'/'+db_name) cur = conn.cursor() return cur, conn def calculation(cur): '''This function takes in the cursor for finalData1 as input. Uses SQL SELECT...FROM...JOIN statement to find where temperature that results from joining the WeatherData and Temperature tables together. This list of temperatures is extracted with the fetchall() command. The uses SELECT statement to extract a list of the happiness rating scores from the HappyData table. Then performs a SELECT statement to extract a list of average precipitation figures from the WeatherData table. Finally, extracts a list of city names using a SELECT statement to extract city names from the HappyData table. Returns a tuple of lists for temperature, happiness scores, precipitation, and city names.''' cur.execute('SELECT temperature FROM WeatherData JOIN Temperatures ON Temperatures.id = WeatherData.average_temperature_id') temperatures = cur.fetchall() cur.execute('SELECT total_score FROM HappyData') happy_scores = cur.fetchall() cur.execute('SELECT average_precipitation FROM WeatherData') precip = cur.fetchall() cur.execute('SELECT city FROM HappyData') city_names = cur.fetchall() return temperatures, happy_scores, precip, city_names def write_csv(x, y, names_city, file_name, headers): '''This function takes in x and y axis data as lists, a list of city names, the csv file to write to, and the headers to include at the top of the csv file. Writes to the csv file all of the information passed in from the x data, y data and city lists and does not return anything.''' file = open(file_name, mode='w', newline='', encoding="utf8") writer = csv.writer(file, delimiter=',') writer.writerow(headers) for i in range(len(x)): writer.writerow([names_city[i], x[i], y[i]]) file.close() def visualization1(temp, happy, city_names): '''This function takes in a list of temperatures, a list of happiness scores, and a list of city names as inputs. Calls the write_csv function to write to the csv the data from these lists, and then plots the data on a matplotlib plot. The figure is saved as ‘v1.png’ and does not return anything.''' x = [] y = [] names_city = [] for i in temp: x.append(i[0]) for i in happy: y.append(i[0]) for i in city_names: names_city.append(i[0]) write_csv(x, y, names_city, "tempHappy.csv", ['City', 'Temperature', 'Happiness Score']) fig, ax = plt.subplots() ax.scatter(x, y, color='#32db84') ax.set_xlabel('temperature in degrees Celcius') ax.set_ylabel('total happiness score') ax.set_title('Happiness Scores vs. Average Temperatures for Different US Cities') z = np.polyfit(x, y, 1) p = np.poly1d(z) plt.plot(x, p(x), "r-") r = np.corrcoef(x, y) print("correlation coefficient for temperature and happiness scatterplot: " + str(r[0,1])) s1 = sorted(x) s2 = sorted(y) avg1 = (s1[0] + s1[-1]) / 2 avg2 = (s2[0] + s2[-1]) / 2 plt.axvline(avg1) plt.axhline(avg2) fig.savefig('tempHappyScatterplot.png') plt.show() def visualization2(precip, happy, city_names): '''This function takes in a list of precipitation data, a list of happiness scores, and a list of city names as inputs. Calls the write_csv function to write to the csv the data from these lists, and then plots the data on a matplotlib plot. The figure is saved as ‘v2.png’ and does not return anything.''' x = [] y = [] names_city = [] for i in precip: x.append(i[0]) for i in happy: y.append(i[0]) for i in city_names: names_city.append(i[0]) write_csv(x, y, names_city, "precipHappy.csv", ['City', 'Precipitation', 'Happiness Score']) fig, ax = plt.subplots() ax.scatter(x, y, color='#7303fc') ax.set_xlabel('precipitation in mm') ax.set_ylabel('total happiness score') ax.set_title('Happiness Scores vs. Precipitation for Different US Cities') z = np.polyfit(x, y, 1) p = np.poly1d(z) plt.plot(x, p(x), "r-") r = np.corrcoef(x, y) print("correlation coefficient for precipitation and happiness scatterplot: " + str(r[0,1])) s1 = sorted(x) s2 = sorted(y) avg1 = (s1[0] + s1[-1]) / 2 avg2 = (s2[0] + s2[-1]) / 2 plt.axvline(avg1) plt.axhline(avg2) fig.savefig('precipHappyScatterplot.png') plt.show() def box_and_wiskers(data, x_label, fig_name, title, csv_name): '''This function takes in a list of the data of interest we want to plot, the x_label for the plot, the name of the figure, title, and the name of the csv file that is desired to save the data into. Creates a box-and-wiskers plot, which includes the quartiles for the data and the iqr as well. It then writes to the csv file the Min, q1, Median, Q3, Max, and IQR data for the data passed into the the function. The function returns nothing.''' good_data = [] for i in data: good_data.append(i[0]) fig1, ax1 = plt.subplots() ax1.set_title(title) ax1.set_xlabel(x_label) plt.boxplot(good_data, vert=False) fig1.savefig(fig_name) plt.show() quartiles = percentile(good_data, [25, 50, 75]).tolist() data_min, data_max = min(good_data), max(good_data) iqr = stats.iqr(good_data, interpolation='midpoint') file = open(csv_name, mode='w', newline='', encoding="utf8") writer = csv.writer(file, delimiter=',') writer.writerow(['Min', 'Q1', 'Median', 'Q3', 'Max', 'IQR']) writer.writerow([data_min, quartiles[0], quartiles[1], quartiles[2], data_max, iqr]) file.close() def main(): '''The main() function akes in no inputs. It calls the calculations function to return data for temperature, happiness scores, precipitation, and city names, and uses these to call the visualization1() and visualization2() functions. Finally, the box_and_wiskers() function is called on precipitation, temperatures and happiness scores individually so we can see the box-and-whiskers plots for each of these lists of data. Main()returns nothing.''' cur, conn = setUpDatabase('finalProjectDatabase.db') temperatures, happy_scores, precipitation, city_names = calculation(cur) visualization1(temperatures, happy_scores, city_names) visualization2(precipitation, happy_scores, city_names) box_and_wiskers(precipitation, 'Precipitation (mm)', 'precipBoxplot.png', 'Boxplot Precipitation', 'precip.csv') box_and_wiskers(temperatures, 'Temperature (Deg. Celcius)', 'tempBoxplot.png', 'Boxplot Temperature', 'temp.csv') box_and_wiskers(happy_scores, 'Happiness Scores', 'happyBoxplot.png', 'Boxplot Happiness Scores', 'happy.csv') if __name__ == "__main__": main()
184c12923237bf834427058ba20921c7732119f9
mws19901118/Leetcode
/Code/Furthest Building You Can Reach.py
1,108
3.765625
4
class Solution: def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int: heap = [] #Use a min heap to maintain the largest ladders gap. Because we want to use ladder for the heigher gap as many as possible for i in range(len(heights) - 1): #Traverse heights. if heights[i] >= heights[i + 1]: #If current building is higher than or equal to next building, continue. continue heapq.heappush(heap, heights[i + 1] - heights[i]) #Push the gap to heap. if len(heap) > ladders: #If the length of heap is larger than ladders, pop heap and subtract it from bricks. bricks -= heapq.heappop(heap) if bricks < 0: #If bricks is smaller than 0, we cannot go further, so return i. return i return len(heights) - 1 #Return len(heights) - 1 if we can reach the last building.
be98f72e78ce5b67822d7f09bdb249d0fe248a62
sireesha98/15218
/beg-50.py
70
3.609375
4
a=int (input()) if ( a & (a - 1)): print('no') else: print('yes')
d146ca36e0e32ba3edc96191f7ce56a2dc2cd2c2
UWPCE-PythonCert-ClassRepos/py220-online-201904-V2
/students/Shirin_A/lesson09/assignment/src/jpgdiscover.py
713
4.125
4
""" This program will find all the .png files in the file directory system """ import os def list_jpg_files(path): """This is the recursive function for discovering .png files""" path_list = [] for root, directories, files in os.walk(path): file_list = [] for file in files: if '.png' in file: file_list.append(file) if file_list != []: path_list.append(root) path_list.append(file_list) if directories: for directory in directories: list_jpg_files(directory) return path_list if __name__ == '__main__': print(list_jpg_files(os.path.dirname(__file__)))
c506a266a25134dc0c42eb9da45376d8d48aeab8
TalkingFoxMid/hexEditor17
/utils/test_integer_hexer.py
338
3.609375
4
import unittest from utils.integer_hexer import IntegerHexer class TestIntegerHexer(unittest.TestCase): def test_to_hex1(self): hexer = IntegerHexer() assert hexer.get_hex_string(10) == "0000000A" def test_to_hex2(self): hexer = IntegerHexer() assert hexer.get_hex_string(140425) == "00022489"
f71eab5a48e402bd46f793bc951c1f9fbc76fc8e
basantech89/code_monk
/python/MITx/6.00.1x_Introduction_to_ComputerSCience_and_Programming_using_Python/conditional.py
338
4.3125
4
# branching program x = int(raw_input("enter an integer:")) if x%2 == 0: if x%3 == 0: print(" ") print("divisible by 2 and 3") else: print(" ") print("divisible by 2 but not by 3") elif x%3 == 0: print("divisible by 3 but not by 2") else: print("neither divisible by 2 nor by 3") print('done with conditional')
23a3ff947eca4e55235017e2abdf9b7edbb52db5
sgas/luts3-client
/sgasclient/baseconvert.py
438
3.890625
4
""" Module for converting a number to base62. """ BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def base10to62(number): BASE = 62 if number == 0: return BASE62[number] new_number = '' current = number while current !=0 : remainder = current % BASE new_number += BASE62[remainder] current = current / BASE return ''.join( reversed(new_number) )