blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4ee2461848475915a819dfdf6ee064efcf009067
sidazhong/leetcode
/leetcode/easy/67_Add_Binary.py
292
3.5
4
class Solution(object): # python 特殊写法,直接加 def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ return "{0:b}".format(int(a, 2) + int(b, 2)) a = "1010" b = "1011" print(Solution().addBinary(a,b))
e2cb70160aac6a5abc66ee38094fc674629b300d
AKASHRANA931/Python-Program-Akash-Rana-
/binary search.py
532
3.90625
4
def binary(list,key): low=0 high=len(list)-1 Found = False while low <= high and not Found: mid = (low + high) // 2 if key == list[mid]: Found = True elif key > list[mid]: low = mid + 1 else: high = mid - 1 if Found == True: print("key is found ",key) else: print("key is not found") list =[1,2,4,5,6,7,8,9] print(list) key=int(input('Enter the key->')) binary(list,key)
6596b2055eaaa5c7dcfd538ebeadd27202660f58
JonathanC13/python_ref
/35_BirthdayPlot/BD_months.py
2,194
3.53125
4
import json from collections import Counter # need to import at least 3 things to make your # bokeh plots work from bokeh.plotting import figure, show, output_file class BD_months(): def getMonthCount(self): BdaysAll = [] # open file for reading with open('BD_Json.json', 'r') as open_file: inputJson = json.load(open_file) #print the names for name in inputJson: print(name + " : " + inputJson.get(name)); BdaysAll.append(inputJson.get(name)) BdayMonth = [] # parse the birthday months into a list for bday in BdaysAll: bdayParse = bday.split("/") print(bdayParse[0] + ", " + bdayParse[1] + ", " + bdayParse[2]) BdayMonth.append(bdayParse[0]) print(*BdayMonth, sep=', ') switcher = { "01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May", "06": "June", "07": "July", "08": "Aug", "09": "Sept", "10": "Oct", "11": "Nov", "12": "Dec" } s_monthsCount = [] #instead of a dict with set months, we'll follow the exercise and create a list, then use Counter from collections lib for month in BdayMonth: s_monthsCount.append(switcher.get(month, "invalid")) c = Counter(s_monthsCount) print(c) return c def displayGraph(self, count): # we specify an HTML file where the output will go output_file("plot.html") x = [] y = [] print("---") # load our x and y data for month in count: x.append(month) y.append(count.get(month)) #print(month + " : " + str(count.get(month))) # create a figure p = figure() # label x x_categories = list(count.keys()) p = figure(x_range = x_categories) # create a histogram p.vbar(x=x, top=y, width=0.5) # render (show) the plot show(p) BDmn = BD_months() cc = BDmn.getMonthCount() BDmn.displayGraph(cc)
e9ce0adb0c27ce15b11ef0602040454e1fc0af76
gabriellaec/desoft-analise-exercicios
/backup/user_072/ch65_2019_12_05_09_57_06_957795.py
199
3.5
4
def acha_bigramas(string): bigrama=[] i=0 while i<len(string)-1: x=string[i]+string[i+1] if x not in bigrama: bigrama.append(x) i+=1 return bigrama
eb3c64f00680ff9aff5ada60d9a60a42f7dd3798
ChaeSangJung/hankerrank_python
/Algorithms/easy/greedy/re_Beautiful Pairs.py
400
3.90625
4
https://www.hackerrank.com/challenges/beautiful-pairs/problem def beautiful_pairs(A, B): A = sorted(A) B = sorted(B) count = i = j = 0 while i < n and j < n: if A[i] == B[j]: count += 1 i += 1 j += 1 elif A[i] < B[j]: i += 1 else: j += 1 if count == n: return count-1 return count+1
a39e73931b14fe1373d76c36ce9a881ae6fd09c4
zoog15/python_practice
/시간순삭 파이썬/0712 8장 연습문제6 거미줄 그리기.py
182
4.03125
4
import turtle t= turtle.Turtle() t.shape("turtle") t.speed(0) def draw_line(): t.forward(100) t.backward(100) for i in range(12) : draw_line() t.right(30)
ec668fc4fcad4597d78d59ce1690112e2135b23a
lock19960613/SCL
/Daily/PY/Leetcode5706-句子的相似性.py
567
3.53125
4
#往两边剔,前后一定要有一个能匹配 class Solution: def areSentencesSimilar(self, s1: str, s2: str) -> bool: if s1 == s2: return True if len(s1) > len(s2): s1,s2 = s2,s1 a1 = s1.split() a2 = s2.split() while a1: if a1[0] != a2[0] and a1[-1] != a2[-1]: return False if a1[0] == a2[0]: a1.pop(0) a2.pop(0) if a1 and a1[-1] == a2[-1]: a1.pop() a2.pop() return True
ab9e2b113a318f6bfab391424eab7901cc28752e
Rajat986/Python-Learning
/Sudoku.py
794
3.53125
4
class board: def __init__(self): self.a=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]] def compute(self): for i in range(9): r=getrow(i) if checkvalid(r) r=getcolum(m) def getrow(i): return self.a[i] def getcolumn(i): return [ j[i] for j in self.a] def getblock(i): .... class UI: def readmatrix(self): m=board() for i in range(9): for j in range(9): m.a[i][j]=int(input("enter %d,%d element : "%(i,j))) return m c=UI() b=c.readboard() print(m.a)
8831aa1272830231d34528bf2812b595571d7cee
MarceloBritoWD/URI-online-judge-responses
/Iniciante/1010.py
383
3.65625
4
# -*- coding: utf-8 -*- peca1 = input().split() peca2 = input().split() peca1_codigo = int(peca1[0]) peca1_numero = int(peca1[1]) peca1_valor = float(peca1[2]) peca2_codigo = int(peca2[0]) peca2_numero = int(peca2[1]) peca2_valor = float(peca2[2]) valor_total = (peca1_numero*peca1_valor) + (peca2_numero*peca2_valor) print("VALOR A PAGAR: R$ %.2f" % valor_total)
7c97a398fda66b5cc46c4d5373fb0904e6380969
HonniLin/leetcode
/history/138.py
1,796
3.984375
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : 138.py @Time : 2020/03/16 07:57:28 @Author : linhong02 @Desc : 遍历原来的链表并拷贝每一个节点,将拷贝节点放在原来节点的旁边,创造出一个旧节点和新节点交错的链表。 迭代这个新旧节点交错的链表,并用旧节点的 random 指针去更新对应新节点的 random 指针。比方说, B 的 random 指针指向 A ,意味着 B' 的 random 指针指向 A' 。 现在 random 指针已经被赋值给正确的节点, next 指针也需要被正确赋值,以便将新的节点正确链接同时将旧节点重新正确链接。 """ # Definition for a Node. class Node: def __init__(self, x, next=None, random=None): self.val = int(x) self.next = next self.random = random """ class Solution(object): def copyRandomList(self, head): """ :type head: Node :rtype: Node """ if not head: return head # 复制节点在旁边 ptr = head while ptr: new_node = Node(ptr.val, None, None) new_node.next = ptr.next ptr.next = new_node ptr = new_node.next # 连接random节点 ptr = head while ptr: ptr.next.random = ptr.random.next ptr = ptr.next.next # 解链 ptr_old_list = head ptr_new_list = head.next res = ptr_new_list while ptr_old_list: ptr_old_list.next = ptr_old_list.next.next ptr_new_list.next = ptr_new_list.next.next if ptr_new_list.next is not None ptr_old_list = ptr_old_list.next ptr_new_list = ptr_new_list.next return res
fe3a43ed4b476adfc2256014608d5114c54b202a
GanquanWen/Deduplicator
/main/fileretrieve.py
1,159
3.5
4
## Copyright 2018 Ganquan Wen [email protected] import sys def retrieve(file, path): '''get the list of hash then retrieve the file according to hash in order ''' file_name = 'list_' + file f = open(path+file_name, "r") line = f.readline() f.close() org_list = line.split(", ") parts_list = [] for n in range(len(org_list)): parts_list.append(org_list[n].strip("\'")) '''retrieve each part of the original article by the hash connect them to make a string''' original_file = "" for i in range(len(parts_list)): part_file = open(path+parts_list[i]+'.txt', "r") line = part_file.readline() while line: original_file += line line = part_file.readline() # if i < len(parts_list)-1: # original_file += '\n\n' # adding a blank line between each part part_file.close() '''store the article as txt file''' file_name = file.lstrip('list_') file_name = file_name.rstrip('.txt') output_file = open(file_name+'_retrieved.txt', "w") output_file.write(original_file) output_file.close() return original_file def main(): file = 'org_file_a.txt' path = 'test/' # print(retrieve(file, path)) if __name__ == '__main__': main()
32acae746470cd7085870a128d2364da627059d0
Akshay-agarwal/DataStructures
/General Problem/Rps.py
1,403
4.21875
4
import random print("----------------------Welcome To Rock Paper Scissors Lizard Spock------------------") print("0)Rock") print("1)Spock") print("2)Paper") print("3)Lizard") print("4)Scissors") player_wins=0 comp_wins=0 ties=0 game_playing='' while game_playing!='y': user_choice = int(input("Choose the number corresponding to your choice :")) comp_choice = random.randint(0,4) def num_name(guess): if guess==0: return "Rock" elif guess==1: return "Spock" elif guess==2: return "Paper" elif guess==3: return "Lizard" elif guess==4: return "Scissors" else: return "Please Enter a number from the displayed options" user_guess=num_name(user_choice) comp_guess=num_name(comp_choice) print("Player Choose : "+user_guess) print("Computer Choose : "+comp_guess) diff = abs(user_choice-comp_choice) if (diff==2 or diff==1): print("Player Wins") player_wins+=1 elif(diff==3 or diff==4): print("Computer Wins") comp_wins+=1 else: print("Game Ties") ties+=1 print("\n") print("ScoreBoard:") print("Player : ",player_wins) print("Computer : ",comp_wins) print("Ties : ",ties) print("\n") game_playing=input("Do you want to play again [y/n]?").lower().startswith('y')
096d2b83fb090eb9369ce790b8197174f8488873
ValentinaArokiya/python-basics
/try_except_finally_1.py
234
3.875
4
try: result = int(input("Please provide a number: ")) except: print("Whoops! That is not a number") else: print("Thank you") finally: print("End of try/except/finally") print("I will always run at the end")
e4fa0e86ce87ac3baff53a82e79a989f806b15b1
Kirktopode/Python-Homework
/12Program1.py
339
3.84375
4
import urllib website = raw_input("What website do you want to visit?") fhand = urllib.urlopen(website) chars = 0 pcount = 0 for line in fhand: chars += len(line.strip()) pcount += line.count("<P>") if chars < 3000: print line.strip() print chars, "CHARACTERS TOTAL IN DOCUMENT\n" + str(pcount), "<P> TAGS IN DOCUMENT"
0af0f02438e24084a384e392f2ce2eb1e882e4b7
Marlon-Poddalgoda/ICS3U-Unit3-05-Python
/month_program.py
1,459
4.4375
4
#!/usr/bin/env python3 # Created by Marlon Poddalgoda # Created on December 2020 # This program identifies the month from a value def main(): # this function identifies the month from a value print("This program identifies the month from a given value.") # input month_value = int(input("Enter a number between 1-12: ")) print("") # process if month_value == 1: # output print("This month is January") elif month_value == 2: # output print("This month is February") elif month_value == 3: # output print("This month is March") elif month_value == 4: # output print("This month is April") elif month_value == 5: # output print("This month is May") elif month_value == 6: # output print("This month is June") elif month_value == 7: # output print("This month is July") elif month_value == 8: # output print("This month is August") elif month_value == 9: # output print("This month is September") elif month_value == 10: # output print("This month is October") elif month_value == 11: # output print("This month is November") elif month_value == 12: # output print("This month is December") else: # output print("Error, this is not a month.") if __name__ == "__main__": main()
60d6d6bad0f0b8e14d9c57dac9458e13d1f1c62a
danicon/MD3-Curso_Python
/Aula16/ex08.py
856
3.8125
4
listabr = ('São Paulo', 'Atlético - MG', 'Flamengo', 'Palmeiras', 'Internacional', 'Grêmio', 'Fluminense', 'Santos', 'Atlético - GO', 'Corinthians', 'Ceará', 'Red Bull Bragantino', 'Fortaleza', 'Athletico Paranaense', 'Sport', 'Bahia', 'Vasco da Gama', 'Coritiba', 'Goiás', 'Botafogo') for c in range(0, len(listabr)): if listabr[c] == 'Corinthians': x = c print(30*'-=') print(f'Lista de times do Brasileirão: {listabr}') print(30*'-=') print(30*'-=') print(f'Os 5 primeiros são {listabr[:5]}') print(30*'-=') print(30*'-=') print(f'Os 4 últimos são {listabr[-4:]}') print(30*'-=') print(30*'-=') print(f'Times em ordem alfabética: {sorted(listabr)}') print(30*'-=') print(30*'-=') print(f'O Corinthians está na {x+1}ª posição') # Ou print(f'O Corinthians está na {listabr.index("Corinthians")+1}ª posição') print(30*'-=')
1f75fc532322a2e34068e0ceedb1f59326ef32bf
MitiaEfimov/Coursera
/DataStructures/week3_hash_tables/1_phone_book/phone_book_test.py
3,824
3.640625
4
# Python 3 """ In this test used cases given from week3_hash_tables's resource page. """ import sys import unittest #from ..phone_book import process_queries as fast #from ..phone_book import process_queries_naive as naive #from ..phone_book import read_queries FILE_PATH = "tests/" def get_data(file_path, need_answer=False): data = [] with open(file_path) as file: n_queries = int(file.readline()) answer_counter = 0 for line in range(n_queries): data.append(file.readline()) if data[-1][0] == "find": answer_counter += 1 if need_answer: answer = get_answer(file_path=file_path+"a", n_lines=answer_counter) return data, answer else: return data def get_answer(file_path, n_lines): answer = [] with open(file_path) as answer_file: for line in range(n_lines): answer.append(answer_file.readline()[:-1]) return answer class PhoneBookTest(unittest.TestCase): def test_broot(self): for file in range(1, 3): data, answer = get_data(FILE_PATH+str(file).rjust(2, "0"), need_answer=True) naive_answer = process_queries_naive(read_queries(test=True, data=data)) fast_answer = process_queries(read_queries(test=True, data=data)) self.assertEqual(naive_answer, fast_answer) # need to delete all stuff below that line def test(): for file in range(1, 3): data = get_data(FILE_PATH+str(file).rjust(2, "0")) naive_answer = process_queries_naive(read_queries(test=True, data=data)) fast_answer = process_queries(read_queries(test=True, data=data)) if naive_answer == fast_answer: print(f"{file} is OK") print(f"naive = {naive_answer}\nfast = {fast_answer}") class Query: def __init__(self, query): self.type = query[0] self.number = int(query[1]) if self.type == 'add': self.name = query[2] def read_queries(test=False, data=None): if test: return [Query(data[i].split()) for i in range(len(data))] else: n = int(input()) return [Query(input().split()) for _ in range(n)] def write_responses(result): if not test: print('\n'.join(result)) def return_responses(number_of_queries): return process_queries(read_queries(number_of_queries)) def process_queries_naive(queries): result = [] # Keep list of all existing (i.e. not deleted yet) contacts. contacts = [] for cur_query in queries: if cur_query.type == 'add': # if we already have contact with such number, # we should rewrite contact's name for contact in contacts: if contact.number == cur_query.number: contact.name = cur_query.name break else: # otherwise, just add it contacts.append(cur_query) elif cur_query.type == 'del': for j in range(len(contacts)): if contacts[j].number == cur_query.number: contacts.pop(j) break else: response = 'not found' for contact in contacts: if contact.number == cur_query.number: response = contact.name break result.append(response) return result def process_queries(queries): result = [] # Keep list of all existing (i.e. not deleted yet) contacts. contacts = {} for cur_query in queries: if cur_query.type == 'add': contacts[cur_query.number] = cur_query.name elif cur_query.type == 'del': contacts.pop(cur_query.number, None) else: result.append(contacts.get(cur_query.number, "not found")) return result if __name__ == "__main__": test()
974e8e8966a122d9f7d253b2552d1f804a58ac0c
humayun-ahmad/full_stack_web_developer
/Python - Level Two/objectOfCircle.py
320
4.0625
4
class Circle(): pi = 3.14 def __init__(self,radius): self.radius = radius def area(self): return self.radius * self.radius * Circle.pi def set_radius(self,new_r): self.radius = new_r # Circle parameter is the radius value obj = Circle(3) # set the new value of radius obj.set_radius(4) print(obj.area())
2a0fc3228947f0fa585eb179b1704a0decddebf5
msahu2595/PYTHON_3
/in_and_iterations_118.py
1,086
4.0625
4
# in keyword and interarions in dictionary user_info = { 'name' : 'harshit', 'age' : 24, 'fav movies' : ['coco', 'kimi no na wa'], 'fav tunes' : ('awakening', 'fairy tale') } # check if key exist in dictionary if 'name' in user_info: print('present') else: print('not present') # check if valur exist in dictionary if 'harshit' in user_info.values(): print('present') else: print('not present') # loops in dictionaries for i in user_info.values(): print(i) # loops in dictionary for i in user_info: print(user_info[i]) # loops in dictionary for i in user_info: print(i) # values method user_info_values = user_info.values() print(user_info_values) print(type(user_info_values)) # key method user_info_keys = user_info.keys() print(user_info_keys) print(type(user_info_keys)) # loops in dictionary for i in user_info: print(user_info[i]) # items method user_items = user_info.items() print(user_items) print(type(user_items)) # gives ---> [(), (), (), ()] for i, j in user_info.items(): print(f"key is and value is {j}")
69581dbacd411dac2412471b97c541d0a51d3f9f
Lithak/Data_Analysis
/DAdaDistribution.py
378
3.5
4
import numpy as np #Data Analysis import matplotlib.pyplot as plt test_scores = [12, 99, 65, 85, 42] test_names = ["Andy", "Martin", "Zahara", "Vuyo", "Ziyaad"] x_pos = [i for i, _ in enumerate(test_names)] #labels on the x-axis #labeling and visuals plt.bar(x_pos, test_scores, color='blue') plt.xlabel("Names") plt.ylabel("Marks(%") plt.xticks(x_pos, test_names) plt.show()
cec1ab5a78cc0f09a8e4287e73d67023be1b8671
shcpark/PythonSampleCodes
/Algorithm/HackerRank/Strings/Capitalize.py
274
3.796875
4
def capitalize(string): sa = string.split(' ') for i in xrange(len(sa)): if len(sa[i]) == 0: sa[i] = sa[i].upper() else: sa[i] = sa[i][0].upper() + sa[i][1:] return ' '.join(sa) a = raw_input().strip() print capitalize(a)
d002ff326cc0325864e060a5d3c8ea4b76eae8a0
Dan-Teles/URI_JUDGE
/2712 - Rodízio Veicular.py
661
3.96875
4
import re n = int(input()) for i in range(n): s = input() if len(s) == 8: if s[3] == '-' and re.match("[A-Z]", s[:3]) and re.match("[0-9]", s[4:]): if s[-1] == '1' or s[-1] == '2': print('MONDAY') elif s[-1] == '3' or s[-1] == '4': print('TUESDAY') elif s[-1] == '5' or s[-1] == '6': print('WEDNESDAY') elif s[-1] == '7' or s[-1] == '8': print('THURSDAY') elif s[-1] == '9' or s[-1] == '0': print('FRIDAY') else: print('FAILURE') else: print('FAILURE')
c8976fc1119201daeba44ff6c62c066443780b6b
IvanWoo/coding-interview-questions
/puzzles/add_strings.py
1,521
3.8125
4
# https://leetcode.com/problems/add-strings/ """ Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly. """ from collections import defaultdict, deque def add_strings(num1: str, num2: str) -> str: i1, i2 = len(num1) - 1, len(num2) - 1 ans = [] carry = 0 while i1 >= 0 or i2 >= 0: x1 = ord(num1[i1]) - ord("0") if i1 >= 0 else 0 x2 = ord(num2[i2]) - ord("0") if i2 >= 0 else 0 carry, v = divmod(x1 + x2 + carry, 10) ans.append(v) i1 -= 1 i2 -= 1 if carry: ans.append(carry) return "".join(str(x) for x in ans[::-1]) def add_strings(num1: str, num2: str) -> str: def get_val(n: str) -> dict[int, int]: ans = defaultdict(int) for k, v in enumerate(n): ans[k] = int(v) return ans i1, i2 = len(num1) - 1, len(num2) - 1 v1, v2 = get_val(num1), get_val(num2) carry = 0 ans = deque() while i1 >= 0 or i2 >= 0: total = carry + v1[i1] + v2[i2] carry, val = divmod(total, 10) ans.appendleft(val) i1 -= 1 i2 -= 1 if carry: ans.appendleft(carry) return "".join((str(x) for x in ans)) if __name__ == "__main__": add_strings("0", "9")
b2fba7cf532916ec121981ee78632a6a610c0de2
MagidElgady/PyDataScience
/5_Pandas/2_pandas_operations.py
2,918
4.65625
5
# Python Full Course - Learn Python in 12 Hours | Python Tutorial For Beginners | Edureka # This lesson looks at all the basic operations that can be performed using pandas. import pandas as pd from matplotlib import style import matplotlib.pyplot as plt # Dictionary showing data about a website XYZ_web = {'Day': [1, 2, 3, 4, 5, 6], 'Visitors': [1000, 700, 6000, 1000, 400, 350], 'Bounce_Rate': [20, 20, 23, 15, 10, 34]} # Converts dictionary to dataframe df = pd.DataFrame(XYZ_web) # Slicing # Only gets the first rows from the top print("Gets the first 2 rows:\n", df.head(2)) # Only gets the last rows from the bottom print("Gets the last 2 rows:\n", df.tail(2)) # Merging: Merges sets of data based on what they have in common df1 = pd.DataFrame({"HPI": [80, 90, 70, 60], "Int Rate": [2, 1, 2, 3], "IND_GDP": [ 50, 45, 45, 67]}, index=[2001, 2002, 2003, 2004]) df2 = pd.DataFrame({"HPI": [80, 90, 70, 60], "Int Rate": [2, 1, 2, 3], "IND_GDP": [ 50, 45, 45, 67]}, index=[2005, 2006, 2007, 2008]) print("Before dataframes were merged:\n", df1) print("Before dataframes were merged:\n", df2) # Merges the 2 dataframes but keeps the HPI column in common # i.e. only HPI shows up without x or y merge = pd.merge(df1, df2, on="HPI") print("After the data was merged:\n", merge) # Joining: Joins sets of data based on index value (must have same columns and rows # or there will be a mismatch) df3 = pd.DataFrame({"Int Rate": [2, 1, 2, 3], "IND_GDP": [ 50, 45, 45, 67]}, index=[2001, 2002, 2003, 2004]) df4 = pd.DataFrame({"Low_Tier_HPI": [50, 45, 67, 34], "Unemployment": [ 1, 3, 5, 6]}, index=[2001, 2003, 2004, 2004]) # NaN shows up as we're missing data for 2002 in df4 joined = df3.join(df4) print(joined) # Changing index and column headers df = pd.DataFrame({'Day': [1, 2, 3, 4, 5, 6], 'Visitors': [1000, 700, 6000, 1000, 400, 350], 'Bounce_Rate': [20, 20, 23, 15, 10, 34]}) # Names index value as Day df.set_index("Day", inplace=True) # Shows graph in 538 style style.use("fivethirtyeight") # Renames visitors to users df = df.rename(columns={"Visitors": "Users"}) # df.plot() # plt.show() # Concatenate: Adds a new row or column to existing dataset df5 = pd.DataFrame({"HPI": [80, 90, 70, 60], "Int Rate": [2, 1, 2, 3], "IND_GDP": [ 50, 45, 45, 67]}, index=[2001, 2002, 2003, 2004]) df6 = pd.DataFrame({"HPI": [80, 90, 70, 60], "Int Rate": [2, 1, 2, 3], "IND_GDP": [ 50, 45, 45, 67]}, index=[2005, 2006, 2007, 2008]) Concat = pd.concat([df5, df6]) print(Concat) # Data munging: Converts file from one format to another supermarkets = pd.read_csv("5_Pandas\\supermarkets.csv") supermarkets.set_index("ID", inplace=True) # Displays the dataframe print(supermarkets) # Converts file to HTML supermarkets.to_html("5_Pandas\\super.html")
270f01f01f54f8c135a754838fd0ae21417919a8
yakovitskiyv/algoritms
/Вставка_элемента.py
836
4.21875
4
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def print_linked_list(vertex): while vertex: print(vertex.value, end=" -> ") vertex = vertex.next print("None") def get_node_by_index(node, index): while index: node = node.next index -= 1 return node def insert_node(head, index, value): new_node = Node(value) if index == 0: new_node.next = head return new_node previous_node = get_node_by_index(head, index-1) new_node.next = previous_node.next previous_node.next = new_node return head n3 = Node('third') n2 = Node('second', n3) n1 = Node('first', n2) print_linked_list(n1) node, index, value = n1, 2, 'new_node' head = insert_node(node, index, value) print_linked_list(head)
998bb62c5e8f57632bca45aca435ef139be818f0
sdshah5796/Data-Structures
/PycharmProjects/Data-Structures/Trees/mirror_image.py
840
3.796875
4
# https://leetcode.com/problems/symmetric-tree/ class Node: def __init__(self, key): self.left = None self.right = None self.data = key def isMirrorImage(root): if root is None: return True return isMirrorImageUtil(root, root) def isMirrorImageUtil(root1, root2): if root1.left is None and root2.right is None: return True if root1.left is not None and root2.right is not None: if root1.data == root2.data: return isMirrorImageUtil(root1.left, root2.right) and isMirrorImageUtil(root1.right, root2.left) return False root = Node(1) root.left = Node(2) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(4) root.right.right = Node(3) print("Symmetric" if isMirrorImage(root) == True else "Not symmetric")
f86795ef7e7cf1c787b09cdf8892161f37df52d7
hw9603/Easy-Sing
/vocaloid/syllablesParser.py
746
4.40625
4
""" Parse syllables from lyrics. Example usage: 1. from utils import * lyrics = get_lyrics_from_file("lyrics.txt") syllables = parse_syllables(lyrics) 2. lyrics = "These are some lyrics stored in a string" syllables = parse_syllables(lyrics) """ import pyphen def parse_syllables(lyrics): """ Return a list of syllables. Input words are split into syllables using function in pyphen. """ dic = pyphen.Pyphen(lang='en_US') if dic is not None: words = lyrics.split() syllables_list = [] for word in words: hyphened_word = dic.inserted(word) syllables = hyphened_word.split('-') for s in syllables: syllables_list.append(s) return syllables_list
56674abc0867a053205836fc8588fc12e4d19489
KillerAK/agecalculator
/agecalc.py
207
4.03125
4
x = int(input ("year of birth")) years = 2019 - x if years <= 18: print("you are a minor") elif years <= 35: print("you are a god damn youth") else: print ("you are an elder")
f9870046bec00bd53ce49734edac412da3e1dc18
shenez/python
/test1.py
154
3.53125
4
def change(a,b): a = 10 b += a a = 4 b = 5 def main(): a=4 b=5 change(a,b) print(a,b) if __name__=='__main__': main()
3e34391f9f56772af5f33dda21e6c532e654b216
Sakisanprprpr/-
/alien_invasion/ship.py
2,525
3.875
4
import pygame from pygame.sprite import Sprite class Ship(Sprite):#创建一个飞船的类,包含飞船的所有属性 def __init__(self,screen,ai_settings):#添加两个形参 """初始化飞船并设置初始位置""" super().__init__() self.screen = screen#初始化两个形参 self.ai_settings = ai_settings #加载飞船图像并获取外接矩形 self.image = pygame.image.load('images\ship.png')#读取飞船的模型文件 self.rect = self.image.get_rect()#读取飞船模型的矩形数据 self.screen_rect = screen.get_rect()#读取游戏窗口的矩形数据 #将每艘新飞船放在屏幕底部中央 self.rect.centerx = self.screen_rect.centerx#将飞船自身的中心坐标设置成与屏幕中心相同 self.rect.bottom = self.screen_rect.bottom#将飞船自身的下边缘坐标与屏幕下边缘对齐 #移动标志 self.moving_right = False#设置一个向右行的标志,默认为False self.moving_left = False#设置一个向左行的标志,默认为False self.moving_up = False self.moving_down = False def blitme(self): """"在指定位置绘制飞船""" self.screen.blit(self.image,self.rect)#在指定的位置绘制飞船 def update(self):#创建一个update函数,用于设置飞船 if self.moving_right and self.rect.right < self.screen_rect.right:# #如果标志为True并且飞船矩形的右值小于屏幕的右值(意思是并未到达屏幕的最右边 self.rect.centerx += self.ai_settings.ship_speed_factor #那么飞船的中心位置向右移动,数值为settings中的speed_factor if self.moving_left and self.rect.left > 0: #如果标志为True并且飞船矩形最左边大于0(意思是飞船未达到屏幕最左边,因为最左的坐标是0 self.rect.centerx -= self.ai_settings.ship_speed_factor #那么飞船的中心位置向左边移动speed_factor if self.moving_up and self.rect.top > 0: self.rect.centery -= self.ai_settings.ship_speed_factor if self.moving_down and self.rect.bottom < self.screen_rect.bottom: self.rect.centery += self.ai_settings.ship_speed_factor def center_ship(self): self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom
0097b2ae46273a675ced917374d4b13ae4c0a878
coolsnake/JupyterNotebook
/new_algs/Number+theoretic+algorithms/Shor's+algorithm/pyshor.py
4,653
4.15625
4
#!../venv/Scripts/python.exe # -*- encoding : utf-8 -*- """ @Description: This project provides a Python implementation of Shor's algorithm. For more details see : https://arxiv.org/abs/1907.09415 @Author: Quentin Delamea @Copyright: Copyright 2020, PyShor @Credits: [Quentin Delamea] @License: MIT @Version: 0.0.1 @Maintainer: Quentin Delamea @Email: [email protected] @Status: Dev """ # Standard lib imports import random as rd from typing import List, Tuple # Local imports from algs import is_prime_number, primer_power, NotPrimerPowerException, gcd, period_finder def find_divisor(n: int) -> int: """ Finds a non trivial factor of a composite integer performing Shor's algorithm. :param n: (int) a none prime number integer strictly greater than one :return: (int) a divisor of n :except TypeError: raised if the argument passed to the function is not an integer :except ValueError: raised if the argument passed to the function is not an integer strictly greatest than one """ # The following lines check that the argument passed to the function is valid if not isinstance(n, int): raise TypeError('can only handle integers') elif n <= 1: raise ValueError('number must be strictly greater than one') elif n % 2 == 0: return 2 elif is_prime_number(n): raise ValueError('number is prime number') # First we reduce the factorization problem to order-finding problem try: return primer_power(n) except NotPrimerPowerException: x_set = list(range(2, n)) # Main loop while True: x = rd.choice(x_set) x_set.remove(x) print('Random number : ', x) # If gcd(x, n) != 1 then we find a non trivial divisor of n if gcd(x, n) > 1: return gcd(x, n) # Since now the factorization problem consits in finding the period of the function : a -> x^a mod n r = period_finder(n, x) # If the period found r is not valid we go back to the beginning of the loop if r % 2 == 1 or x ** (r / 2) % n == -1: continue # Since the period is valid we compute the two factors we can deduce from it fac_1, fac_2 = gcd(x ** (r // 2) - 1, n), gcd(x ** (r // 2) + 1, n) # If the factors we obtain are trivial, we go back to the beginning of the loop if (fac_1 == 1 or fac_1 == n) and (fac_2 == 1 or fac_2 == n): continue # Shor's algorithm ensures us that the two factors are non trivial factors of n return fac_1, fac_2 def _clean(factorization: List[Tuple[int, int]]) -> List[Tuple[int, int]]: """ cleans up the list of factors by ensuring that each prime number appears only once with its corresponding power and by ensuring that the list is sorted, i.e. the prime powers are arranged in ascending order. :param factorization: (List<Tuple<int, int>>) a non clean list of factors :return: (List<Tuple<int, int>>) the clean up list of factors """ clean_factorization = [] for prime_number, power in factorization: if prime_number not in [factor[0] for factor in clean_factorization]: clean_factorization.append((prime_number, 1)) else: for i in range(len(clean_factorization)): if clean_factorization[i][0] == prime_number: clean_factorization[i] = (prime_number, clean_factorization[i][1] + power) return sorted(clean_factorization, key=lambda item: item[0]) def prime_factorize(n: int) -> List[Tuple[int, int]]: """ Performs the prime factorization of an integer. :param n: (int) a positive integer :return: (List<Tuple<int, int>>) the unique prime factorization of n. If n = p1^a1 * p2^a2 * ... * pn^an then the function returns [(p1, a1), (p2, a2), ..., (pn, an)] :except TypeError: raised if the argument passed to the function is not an integer :except ValueError: raised if the argument passed to the function is not an integer strictly greatest than one """ if not isinstance(n, int): raise TypeError('can only handle integers') elif n <= 1: raise ValueError('integer must be strictly greater than one') elif is_prime_number(n): return [(n, 1)] elif n % 2 == 0: return _clean([(2, 1)] + prime_factorize(n // 2)) else: divisor = find_divisor(n) return _clean([(divisor, 1)] + prime_factorize(n // divisor)) # while True: # n = int(input('Number : ')) # print('Factorization : ', find_divisor(n))
e536066384f58f3fbc5c6b215a16a701fd8c1989
Danutelka/Coderslab-Python-progr-obiektowe
/1_Zadania/Dzien_2/3_Zaawansowana_obiektowosc/zad_2.py
769
3.5
4
class BankAccount: __next_acc_number = 1 def __init__(self, ): self.number = BankAccount.__next_acc_number BankAccount.__next_acc_number +=1 self.cash = 0.0 def deposit_cash(self, amount): if amount > 0: self.cash += amount def withdraw_cash(self, amount): if amount > self.cash: r = amount - self.cash self.cash = 0.0 return r else: self.cash -= amount return amount def print_info(self): print("nr konta: {}, ilość kasy {}" .format(self.number, self.cash)) ba1 = BankAccount() ba2 = BankAccount() ba2.print_info() """ a1 = BankAccount(1234) a1.deposit_cash(600) print(a1.withdraw_cash(200)) a1.print_info() """
b5a89c301aaaea43b51f322ead064ce3cabababf
KrishAjith/Python
/FindLargeNum.py
295
4.25
4
Num1=int(input("Enter your 1st Number :")) Num2=int(input("Enter your 2nd Number :")) Num3=int(input("Enter your 3rd Number :")) if(Num1 > Num2): print(Num1," is Largest Number") elif(Num2 > Num3): print(Num2," is Largest Number") else: print(Num3," is Largest Number ")
ffb7601930a99ce57185784c404c2f2431c6e060
complex-systems-lab/Machine-learning-asssited-Chimera-and-Solitary-states-in-Networks
/Machine learning on multilayer network/neuralNetworkCriticalDelay.py
969
3.515625
4
import numpy as np import matplotlib.pyplot as plt from sklearn.neural_network import MLPClassifier from sklearn.model_selection import train_test_split from statistics import mean data = np.loadtxt("Naveen bhaiya paper\\dataMLCombined.txt") features = np.delete(data , 3 , 1) labels = data[:,3] X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2) numberOfModels = int(input("Enter number of models to run: ")) tauList = [] for i in range(numberOfModels): model = MLPClassifier(hidden_layer_sizes=(30,30) , activation='relu') model.fit(X_train , y_train) a = np.zeros((1,3)) a[0][0] = 1.0 #InterLayer K a[0][1] = 0.3 #IntraLayer K a[0][2] = 0 state = 0 while(state == 0): if(model.predict(a) == 1): state = 1 else: a[0][2] += 0.01 print(a[0][2]) tauList.append(a[0][2]) #print(i , end=" ") print("\n" + str(mean(tauList)))
c437346e13375fd1400e7d386a57c130912c4acb
igorvrykolakas/training.py
/média aritmética.py
193
3.703125
4
n1 = float(input('Qual a nota da primera prova?')) n2 = float(input('Qual a nota do trabalho?')) t = n1 + n2 print('Uau! Sua nota média nesse trimestre é {:.2f}. Parabéns.'.format(t/2))
1275f1247b89ebd594ea6a20a1d5e1a29cbb302f
MingkaiMa/Project-Euler
/Problem_47.py
2,946
3.65625
4
##Prpblem_47 ##from math import sqrt ## ##def prime_factors(n): ## L = [] ## i = 2 ## while i * i <= n: ## if n % i: ## i += 1 ## else: ## n //= i ## L.append(i) ## ## if n > 1: ## L.append(n) ## return L ## ##for i in range(647,100000000): ## a = set(prime_factors(i)) ## b = set(prime_factors(i + 1)) ## c = set(prime_factors(i + 2)) ## d = set(prime_factors(i + 3)) ## ## if len(a) == 4 and len(b) == 4 and len(c) == 4 and len(d) == 4: ## print(i) ## break ##Problem_48 ##n = 0 ##for i in range(1,1001): ## ## n = n + i ** i ## ##print(str(n)[-10:-1] + str(n)[-1]) ## ##Problem_49 from math import sqrt ##def is_prime(n): ## if n == 2: ## return True ## if n < 2: ## return False ## for i in range(2, round(sqrt(n)) + 1): ## if n % i == 0: ## return False ## return True ##for i in range(1000,10000): ## if not is_prime(i): ## continue ## for j in range(i + 1,10000): ## if not is_prime(j): ## continue ## for k in range(j + 1,10000): ## if not is_prime(k): ## continue ## ## if not (set(str(i)) == set(str(j)) and set(str(j)) == set(str(k))): ## continue ## ## if abs(i - j) != abs(k - j): ## continue ## print(i,j) ## break ## ##Problem_50 ##def primes(m,n): ## L = [] ## n_index = (n - 1) // 2 ## primes_sieve = [True] * (n_index + 1) ## for k in range(1, (round(sqrt(n)) + 1) // 2): ## if primes_sieve[k]: ## for i in range(2 * k * (k + 1), n_index + 1, 2 * k + 1): ## primes_sieve[i] = False ## ## for j in range(1, n_index + 1): ## if primes_sieve[j]: ## if 2 * j + 1 >= m: ## L.append(2 * j + 1) ## ## return L ## ##L = primes(1000,10000) ###print(L) ##for i in range(0,len(L)): ## a = set(str(L[i])) ## for j in range(i + 1, len(L)): ## b = set(str(L[j])) ## if a != b: ## continue ## for k in range(j + 1, len(L)): ## c = set(str(L[k])) ## if b != c: ## continue ## if abs(L[i] - L[j]) != abs(L[k] - L[j]): ## continue ## print(L[i],L[j],L[k]) ##Problem_51 from math import sqrt def primes(m,n): L = [] n_index = (n - 1) // 2 primes_sieve = [True] * (n_index + 1) for k in range(1, (round(sqrt(n)) + 1) // 2): if primes_sieve[k]: for i in range(2 * k * (k + 1), n_index + 1, 2 * k + 1): primes_sieve[i] = False for j in range(1, n_index + 1): if primes_sieve[j]: if 2 * j + 1 >= m: L.append(2 * j + 1) return L L = primes(10000000,99999999) print(len(L))
cf8327bee6d65bbf426355b4398ae3407d4798e6
roman-baldaev/elastic_vs_sphinx_test
/src/parsers/file-parser.py
486
3.796875
4
import textract def parse_file(path_to_file, encoding_for_return="utf-8"): """ Method parses the file and returns the contents as a string with the specified encoding. :param path_to_file: path to file for parse by textract :param encoding_for_return: encoding of the returned string (textract.process return 'bytes') :return: string """ text = textract.process(path_to_file) return text.decode(encoding_for_return) if __name__ == "__main__": ...
b44c9311edb4f000f3464b4338fa25cbbaec2203
ladosamushia/PHYS639F19
/NathanMarshall/Warmup2/Numerical Derivatives.py
1,294
4.46875
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 3 13:06:11 2019 Nathan Marshall This program contains functions that compute the numerical 1st and 2nd derivatives of a function f(x). As an example, f(x) is set to x**3 to test if the derivative functions are working properly. """ #%% dx = 0.0001 #the step size in x used to compute derivatives x = 1 #the value of x to compute the derivatives of f(x) at def fx(x): '''Defining the function f(x) to compute derivatives of.''' return(x**3) #I chose the function x**3 def dfdx(x, dx, fx): '''Computes the approximate derivative of f(x) at a given x value''' return((fx(x+dx)-fx(x-dx))/(dx*2)) #evaluating the difference quotient of f(x) at the given x value using #the step size dx gives us an approximation of the derivative def d2fdx(x, dx, fx, dfdx): return((dfdx(x+dx, dx, fx)-dfdx(x-dx, dx, fx))/(dx*2)) #evaluating the difference quotient of df/dx(x) at the given x value using #the step size dx gives us an approximation of the 2nd derivative print('The actual derivative of x**3 at x = 1 is 3') print('The numerical derivative of x**3 at x = 1 is', dfdx(x,dx,fx)) print('The actual 2nd derivative of x**3 at x = 1 is 6') print('The numerical 2nd derivative of x**3 at x = 1 is', d2fdx(x,dx,fx, dfdx))
9df28ee801b330150de42ac4556cc8f43fa7615d
jiangxiao24/onlinestudy
/day17/17生成器.py
3,425
3.953125
4
#__author__:jiangqijun #__date__:2018/11/17 #1、列表生成式,可以在前边加入表达式或者函数 # a = [x*2 for x in range(10)] # print(a) # # def f(n): # return n*n*n # b = [f(x) for x in range(10)] # print(b) #2、a.生成器,每次使用得时候才会计算,每次只能取下一个而不能跳跃取值.生成器就是一个可以迭代得对象 #下边得i取值得是接着上边一起取得,由于上边已经取完了所以下边就没有了 #在循环中,i这个变量每次只引用一个值,所以只有一个值是占用内存,前面得引用都消失 #在循环中,最后一个变量时,会自己捕获到异常,从而自动停止 # a = (x*2 for x in range(3)) # print(type(a)) #<class 'generator'> # print(next(a)) # print(next(a)) # print(next(a)) # #print(next(a)) #StopIteration # for i in a: # print(i) #b.迭代器得两种生成方式 # a = (x*2 for x in range(10)) #yield关键字,在这个关键字相当于return方法,不同之处是,调用next()时,在执行到这里得时候会保存函数得状态 #下次继续从该状态执行下去 # def foo(): # print('NO1') # yield 1 # print('NO2') # yield 2 # # s = foo() # print(s) #这里得s就是一个生成器,直接执行得时候是不会打印出来得,调用next(s)方法得时候才会执行 # next(s) #执行生成器,返回第一个生成器得值 # next(s) # print(next(s)) # def f(max): # n, before, after = 0, 0, 1 # while(n<max): # print(before) # before, after = after, before+after #这里先计算after before+after,再进行赋值 # n = n+1 # f(3) #迭代器实现斐波拉序列 # def f(max): # n, before, after = 0, 0, 1 # while(n<max): # yield after # before, after = after,before+after # n = n+1 # # for i in f(5): # print(i) #c.生成器得send方法,s.send('abc')方法等于next(s),调用s.send得时候,首先要进入才能将值传入。如果是send进入得话 #则首次需要使用s.send(None),否则报错。或者通过next(s)来调用。后边得值才会传入 # def f(): # print('ok1') # count1 = yield 1 # print('ok2') # count2 = yield 2 # # s = f() # #c1 = s.send(None) # c1 = next(s) # print(c1) # c2 = s.send('aaa') #这里得aaa赋值给了count1 # print(c2) # def get_file_length(filepath): # with open(filepath, 'r', encoding='utf-8') as f: # while True: # str = f.readline() # if str: # str_length = len(str) # yield str_length # else: # return # # # max = 0 # index = 0 # index_temp = 0 # # for i in get_file_length("2018-11-23-info.txt"): # index_temp = index_temp+1 # if i>max: # max = i # index = index_temp # print(next(get_file_length("2018-11-23-info.txt"))) # # print(next(get_file_length("2018-11-23-info.txt"))) # with open("2018-11-23-info.txt", 'r', encoding='utf-8') as f: # print(f) # # [max(len(x)) for x in open("2018-11-23-info.txt", 'r', encoding='utf-8')] # # # [x*x for x in range(10)] # print(type(open("2018-11-23-info.txt", 'r', encoding='utf-8'))) def add(s, x): return s + x def gen(): for i in range(4): yield i base = gen() for n in [1, 10]: base = (add(i, n) for i in base) print(base) for i in base: print(i) #print(list(base))
6c54029057a7358bb4135ed4ac46ce78c3ce9439
lexm/hackerrank-code
/Python/Regex_and_Parsing/re-group-groups.py
105
3.515625
4
import re input1 = re.search(r'([a-zA-Z0-9])(\1+)', input()) print(input1.group(0)[1] if input1 else -1)
75a178edf1c8cbb907abb7afb4705aacfb5e245a
Esot3riA/KHU-Algorithm-2019
/0926_Merge_Sort.py
2,057
3.6875
4
class MergeSortAlgorithm: def mergeSort(self, n, S): h = int(n / 2) m = n - h if n > 1: U = S[:h] V = S[h:] self.mergeSort(h, U) self.mergeSort(m, V) self.merge(h, m, U, V, S) def merge(self, h, m, U, V, S): i, j, k = 0, 0, 0 while i <= h - 1 and j <= m - 1: if U[i] < V[j]: S[k] = U[i] i += 1 else: S[k] = V[j] j += 1 k += 1 if i > h - 1: for iterator in range(j, m): S[k - j + iterator] = V[iterator] else: for iterator in range(i, h): S[k - i + iterator] = U[iterator] globalS = [] def setGlobalS(self, S): self.globalS = S def mergeSort2(self, low, high): if low < high: mid = int((low + high) / 2) self.mergeSort2(low, mid) self.mergeSort2(mid+1, high) self.merge2(low, mid, high) def merge2(self, low, mid, high): print(low, mid, high) i = low j = mid + 1 k = 0 U = [0] * (high - low + 1) while i <= mid and j <= high: if self.globalS[i] < self.globalS[j]: U[k] = self.globalS[i] i += 1 else: U[k] = self.globalS[j] j += 1 k += 1 if i > mid: for iterator in range(j, high + 1): U[k - j + iterator] = self.globalS[iterator] else: for iterator in range(i, mid + 1): U[k - i + iterator] = self.globalS[iterator] for iterator in range(low, high + 1): self.globalS[iterator] = U[iterator - low] s = [3, 5, 2, 9, 10, 14, 4, 8] mergeSortAlgorithm = MergeSortAlgorithm() mergeSortAlgorithm.mergeSort(8, s) print(s) s3 = [3, 5, 2, 9, 10, 14, 4, 8] mergeSortAlgorithm.setGlobalS(s3) mergeSortAlgorithm.mergeSort2(0, 7) print(mergeSortAlgorithm.globalS)
5c1676eb19cf1beaba16d1f53a008329974086fb
ChrisDuhan/2143-OOP-Duhan
/Assignments/homework-02.py
8,871
3.578125
4
""" Name: Chris Duhan Email: [email protected] Assignment: Homework 2 - War card game Due: 17 Feb @ 11:59 p.m. """ """ So this was a fun program, it's still got a few things that could be implimented more effectivly, plus it goes on till the last card, meaning that the game could possibly end during war. I also had real trouble getting the hidden card to fit nicely with the card in play on the "table" so I scraped that idea for now. Maybe later. """ import os import time import random #Source for cards and card class: http://codereview.stackexchange.com/questions/82103/ascii-fication-of-playing-cards CARD = """\ ┌───────┐ │{} │ │ │ │ {} │ │ │ │ {}│ └───────┘ """.format('{trank:^2}', '{suit: <2}', '{brank:^2}') TEN = """\ ┌───────┐ │{} │ │ │ │ {} │ │ │ │ {}│ └───────┘ """.format('{trank:^3}', '{suit: <2}', '{brank:^3}') FACECARD = """\ ┌───────┐ │{}│ │ │ │ {} │ │ │ │{}│ └───────┘ """.format('{trank:<7}', '{suit: <2}', '{brank:>7}') """ @Class Card @Description: This class represents a single card. """ class Card(object): def __init__(self, suit, rank): """ :param suit: The face of the card, e.g. Spade or Diamond :param rank: The value of the card, e.g 3 or King """ self.ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"] self.card_values = { '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11, # value of the ace is high until it needs to be low } self.str_values = { '2': CARD, '3': CARD, '4': CARD, '5': CARD, '6': CARD, '7': CARD, '8': CARD, '9': CARD, '10': TEN, 'Jack': FACECARD, 'Queen': FACECARD, 'King': FACECARD, 'Ace': FACECARD, # value of the ace is high until it needs to be low } self.suits = ['Spades','Hearts','Diamonds','Clubs'] self.symbols = { 'Spades': '♠', 'Diamonds': '♦', 'Hearts': '♥', 'Clubs': '♣', } if type(suit) is int: self.suit = self.suits[suit] else: self.suit = suit.capitalize() self.rank = str(rank) self.symbol = self.symbols[self.suit] self.points = self.card_values[str(rank)] self.ascii = self.__str__() def __str__(self): symbol = self.symbols[self.suit] trank = self.rank+symbol brank = symbol+self.rank return self.str_values[self.rank].format(trank=trank, suit=symbol,brank=brank) def __cmp__(self,other): return self.ranks.index(self.rank) < self.ranks.index(other.rank) def __lt__(self,other): return self.__cmp__(other) """ @Class Deck @Description: This class represents a deck of cards. @Methods: pop_cards() - removes a card from top of deck add_card(card) - adds a card to bottom of deck shuffle() - shuffles deck sort() - sorts the deck based on value, not suit (could probaly be improved based on need) """ class Deck(object): def __init__(self): #assume top of deck = 0th element self.cards = [] for suit in range(4): for rank in ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"]: self.cards.append(Card(suit,rank)) def __str__(self): cards_on_screen = [] for card in self.cards: cards_on_screen.append(str(card)) return "".join(cards_on_screen) def pop_card(self): return self.cards.pop(0) def add_card(self,card): self.cards.append(card) def shuffle(self): random.shuffle(self.cards) def sort(self): self.cards = sorted(self.cards) """ @Class Hand @Description: This class represents a players' hand of cards. @Methods: join_lines() - desciption below play_card() - removes a card from top of deck add(card) - adds a card to bottom of deck shuffle() - shuffles the hand """ class Hand(list): def __init__(self, cards=None): """Initialize the class""" super().__init__() if (cards is not None): self._list = list(cards) else: self._list = [] def __str__(self): return self.join_lines() def join_lines(self): """ Stack strings horizontally. This doesn't keep lines aligned unless the preceding lines have the same length. :param strings: Strings to stack :return: String consisting of the horizontally stacked input """ liness = [card.ascii.splitlines() for card in self._list] return '\n'.join(''.join(lines) for lines in zip(*liness)) def add(self,card): self._list.append(card) def play_card(self): return self._list.pop(0) def shuffle(self): random.shuffle(self._list) """ @Class Game @Description: This class represents a game of War @Methods: game_start() - prepares the players hands play() - a card from each palyer is compared and the winner takes both, if war occurs it makes a war stack and plays again play() is currently set up to auto-play the whole game, if you want to play each round yourself you can uncomment the commands below that ask for input and that pause """ class Game(object): def __init__(self,player_name): self.D = Deck() self.D.shuffle() self.CH = Hand() self.PH = Hand() self.war_stack = [] self.winner = None self.rounds = 0 self.deal() self.play() def deal(self): for i in range(26): self.CH.add(self.D.pop_card()) self.PH.add(self.D.pop_card()) def play(self): while(len(self.CH._list) and len(self.PH._list)): os.system('cls') os.system('clear') PC = self.PH.play_card() CC = self.CH.play_card() if PC.__lt__(CC): print("Computer") print(CC) print(PC) print(player_name) print() print("You lost") #input("Press enter to play a round") self.CH.add(PC) self.CH.add(CC) for i in self.war_stack: self.CH.add(self.war_stack.pop()) elif CC.__lt__(PC): print("Computer") print(CC) print(PC) print(player_name) print() print("You won") #input("Press enter to play a round") self.PH.add(PC) self.PH.add(CC) for i in self.war_stack: self.PH.add(self.war_stack.pop()) else: print("Computer") print(CC) print(PC) print(player_name) print() print("War!") self.war_stack.append(PC) self.war_stack.append(CC) self.war_stack.append(self.PH.play_card()) self.war_stack.append(self.CH.play_card()) #time.sleep(2) #input("Press enter to play a war round") os.system('cls') self.play() self.rounds = self.rounds + 1 if (self.rounds % 26 == 0): self.PH.shuffle() self.CH.shuffle() if len(self.CH._list) == 0: self.winner = "You" if len(self.PH._list) == 0: self.winner = "The computer" # time.sleep(.5) print("Welcome to the game of") print(" _ _ ___ ______ _\n| | | | / _ \ | ___ \| |\n| | | |/ /_\ \| |_/ /| |\n| |/\| || _ || / | |\n\ /\ /| | | || |\ \ |_|\n \/ \/ \_| |_/\_| \_|(_)") print() input("Press enter to begin") os.system('cls') os.system('clear') player_name = input("Please type your name: ") new_game = Game(player_name) os.system('cls') os.system('clear') print('%s won the game' % new_game.winner) print('Game finished after %d rounds'% new_game.rounds)
c8896aa0bc61c8ea6144569f683c1da47a9b0130
vmirisas/Python_Lessons
/lesson8/part5/exercise4.py
966
3.6875
4
string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sed libero vitae est rhoncus cursus at eget eros. Phasellus laoreet lobortis suscipit. Duis pretium felis quis tristique lacinia. Nulla id convallis dolor, ac dapibus lectus. Maecenas gravida ut arcu sit amet ultrices. Quisque ut massa sit amet nibh placerat tempor. Vivamus lacus felis, iaculis et nunc id, condimentum dapibus ligula." print(string) str_list = list(string) print(type(str_list)) print(str_list) dictionary = {} for char in str_list: if char not in dictionary: dictionary[char] = 0 else: dictionary[char] += 1 print(dictionary) max_num = 0 for values in dictionary: if dictionary[values] >= max_num: max_num = dictionary[values] print(max_num) print(max(list(dictionary.values()))) for key, value in dictionary.items(): if value == max_num: if key == " ": print("blank") else: print(key)
d321a965bea65065fa2a0462efdff86c1f5f97a4
dygksquf5/python_study
/Algorithm_python/Permutations.py
1,027
3.640625
4
# 꼭 복습 해보기!! import itertools from typing import List def permute(nums: List[int]) -> List[List[int]]: result = [] prev_elements = [] def dfs(elements): # 리프 노드일 때 결과 추가 if len(elements) == 0: # 변수를 그대로 넣지말고, 안에있는 값을 복사해서 넣는식으로 넣자! 파이썬은 객체를 참고하는 형태로 처리되니까 에러방지! result.append(prev_elements[:]) for e in elements: next_elements = elements[:] next_elements.remove(e) prev_elements.append(e) dfs(next_elements) prev_elements.pop() dfs(nums) return result print(permute([1,2,3])) # 하지만 파이썬은 itertools 라는 좋은 모듈을 재공하고있음!!! 반복자 생성에 최적화된 모듈임! def permute_itertools(nums: List[int]) -> List[List[int]]: return list(map(list, itertools.permutations(nums))) print(permute_itertools([1,2,3,]))
cd498860827e743e7d355c37d6bbe01c1c83a578
SravanKumarMenthula/Python
/DSA/LinkedList/Swap.py
1,630
4.125
4
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def swap(self,x,y): currentX = self.head currentY = self.head prevX = None prevY = None #find X while(currentX!=None and currentX.data!=x): prevX = currentX currentX = currentX.next while(currentY!=None and currentY.data!=y): prevY = currentY currentY = currentY.next if currentX==None or currentY==None : return if prevX!=None: #X is not head prevX.next = currentY else: self.head = currentY if prevY!=None: #Y is not head prevY.next = currentX else: self.head = currentX temp = currentX.next currentX.next = currentY.next currentY.next = temp def push(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while(temp!=None): print(temp.data,end=" ") temp = temp.next print() if __name__ == '__main__': llist = LinkedList() #creates a LinkedList llist.push(6) llist.push(7) llist.push(1) llist.push(4) llist.push(8) llist.push(2) print("List before swap:", end = ' ') llist.printList() llist.swap(8,7) print("List after swap:", end = ' ') llist.printList()
6870e3e6844dc748da5c6d394100727dff6916f6
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/grhisa001/question3.py
845
3.953125
4
""" Bella Gorham voting 20/04/2014""" # empty lists parties = [] finalparties= [] answerlist= [] vote="" # ask for input until done print("Independent Electoral Commission\n--------------------------------\nEnter the names of parties (terminated by DONE):") while vote != "DONE": vote=input() parties.append(vote) parties.sort() parties.remove("DONE") pair=[] for i in parties: #make count parties answer = parties.count(i) if [i,answer] in answerlist: # elimainate dulpicates continue #new list of parties and votes pair = [i, answer] answerlist.append(pair) print() print("Vote counts:") final = "{0:<10} - {1}" for p in answerlist: #spliting list partyname = p[0] votes = p[1] #format for display print(final.format(partyname,votes))
096e39b381e13cc6621c50f45d3fb38d37bc3502
nuttapol-kor/Final-project-Year1-Semester1
/games/Pok_deng.py
12,800
3.625
4
import sys class Deck: def __init__(self): """ Initialzing a deck for play """ self.__rank = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"] self.__suit = ["Clubs", "Diamonds", "Hearts", "Spades"] self.__deck = [] for rank in self.__rank: for suit in self.__suit: card = rank + ' ' + suit self.__deck += [card] @property def deck(self): return self.__deck def shuffle_cards(self): import random n = len(self.__deck) for i in range(n): r = random.randrange(i, n) temp = self.__deck[r] self.__deck[r] = self.__deck[i] self.__deck[i] = temp class Hand: def __init__(self): """ Initializing hand/ val / etc. use for play """ self.__hand = [] self.__val = 0 self.__real_val = 0 self.__hit = 1 self.__pok8 = False self.__pok9 = False self.__straight_flush = False self.__tong = False @property def hand(self): return self.__hand @property def val(self): return self.__val @property def real_val(self): return self.__real_val @property def hit(self): return self.__hit @property def pok8(self): return self.__pok8 @property def pok9(self): return self.__pok9 @property def tong(self): return self.__tong @property def straight_flush(self): return self.__straight_flush @val.setter def val(self,val): self.__val = val @real_val.setter def real_val(self,real_val): self.__real_val = real_val @hit.setter def hit(self,hit): self.__hit = hit def draw_cards(self,deck, n): """ just draw a card, when you draw a card that card will move from the deck to you hand, that mean the card from deck disappear by drawing. """ for _ in range(n): self.__hand.append(deck.pop()) def display_cards(self): """ show the cards in the hand with suit symbol """ display_str = [] for each_card in self.__hand: ltemp = each_card.split() if ltemp[1] == 'Clubs': display_str += [ltemp[0] + '\u2663' + ' '] elif ltemp[1] == 'Diamonds': display_str += [ltemp[0] + '\u2666' + ' '] elif ltemp[1] == 'Hearts': display_str += [ltemp[0] + '\u2665' + ' '] else: assert ltemp[1] == 'Spades', 'Spades expected' display_str += [ltemp[0] + '\u2660' + ' '] for i in display_str: print(i,end="") print("") def calculate_hand_value(self): """ culculate the vulue form card """ for card in self.__hand: ltemp = card.split() if ltemp[0] in ['2', '3', '4', '5', '6', '7', '8', '9', '10']: self.__val += int(ltemp[0]) elif ltemp[0] in ['Jack', 'Queen', 'King']: self.__val += 10 elif ltemp[0] in ['Ace']: self.__val += 1 if self.__val >= 10: self.__real_val += self.__val % 10 else: self.__real_val += self.__val def calcuate_suit(self): """ calcuate suit cards in hand """ suit = [] for card in self.__hand: ltemp = card.split() suit.append(ltemp[1]) nTemp = suit[0] bEqual = True for i in suit: if nTemp != i: bEqual = False break if bEqual: self.__hit = len(suit) def check_pok8(self): """ check pok 8 from cards in each hand """ if self.__real_val == 8: self.__pok8 = True def check_pok9(self): """ check pok 9 from cards in each hand """ if self.__real_val == 9: self.__pok9 = True def add_more_card(self,deck): """ this function will return True when you want to draw more card, and will return False when you not want to draw anymore. """ while True: do = input("Draw More?(Yes/No): ") do.lower() if do == "yes": self.draw_cards(deck,1) break elif do == "no": break else: print("Invalid Choice") def check_straight_flush_and_tong(self): """ check straight flush and tong and set True when it is """ blank_list = [] num = 0 for card in self.__hand: ltemp = card.split() blank_list.append(ltemp[0]) for i in blank_list: if i in ['Jack', 'Queen', 'King']: num += 1 if len(blank_list) == num: self.__straight_flush = True nTemp = blank_list[0] bEqual = True for i in blank_list: if nTemp != i: bEqual = False break if bEqual: self.__tong = True def bot_fight(self,deck): """ bot will draw more when cards in hand less than 4 """ if self.__real_val < 4: self.draw_cards(deck,1) def reset(self): """ set attributes like when game start """ self.__hand = [] self.__val = 0 self.__real_val = 0 self.__hit = 1 self.__pok8 = False self.__pok9 = False self.__straight_flush = False self.__tong = False class Pok_Deng: def __init__(self,player): """ Initializing player """ self.__player = player def play(self): """ play the game """ playing = True while playing: # initialze a deck of cards self.deck = Deck() # shuffle the deck self.deck.shuffle_cards() #draw a player hand self.player_hand = Hand() self.player_hand.draw_cards(self.deck.deck,2) #draw the computer hand self.computer_hand = Hand() self.computer_hand.draw_cards(self.deck.deck,2) self.player_hand.calcuate_suit() self.computer_hand.calcuate_suit() # display player_hand print(f"{self.__player.name} hand: ", end = '') self.player_hand.display_cards() print(f"{self.player_hand.hit} Deng") # # display computer_hand # print("Computer hand: ", end = '') # self.computer_hand.display_cards() #calculate value self.player_hand.calculate_hand_value() self.computer_hand.calculate_hand_value() # self.player_hand.real_val # self.computer_hand.real_val # print(f"Player val: {self.player_hand.real_val}") # print(f"Com val: {self.computer_hand.real_val}") #check pok self.player_hand.check_pok8() self.computer_hand.check_pok8() self.player_hand.check_pok9() self.computer_hand.check_pok9() if self.player_hand.pok9 and self.computer_hand.pok9: print("Both tie") elif self.player_hand.pok9: print(f"{self.__player.name} wins") self.__player.update_num_wins(3,1*self.player_hand.hit) elif self.computer_hand.pok9: print("Computer wins") if self.player_hand.pok8 and self.computer_hand.pok8: print("Both tie") elif self.player_hand.pok8: print(f"{self.__player.name} wins") self.__player.update_num_wins(3,1*self.player_hand.hit) elif self.computer_hand.pok8: print("Computer wins") if self.player_hand.pok9 or self.computer_hand.pok9 or self.player_hand.pok8 or self.computer_hand.pok8: print("Computer hand: " , end="") self.computer_hand.display_cards() print(f"{self.computer_hand.hit} Deng") break #draw 3 cards self.player_hand.add_more_card(self.deck.deck) if self.computer_hand.real_val < 4: self.computer_hand.draw_cards(self.deck.deck,1) self.player_hand.hit = 1 self.computer_hand.hit = 1 self.player_hand.calcuate_suit() self.computer_hand.calcuate_suit() print(f"{self.__player.name} hand: ", end = '') self.player_hand.display_cards() print(f"{self.player_hand.hit} Deng") # print("Computer hand: ", end = '') # self.computer_hand.display_cards() #reset val for calculate again self.player_hand.val = 0 self.player_hand.real_val = 0 self.computer_hand.val = 0 self.computer_hand.real_val = 0 self.player_hand.calculate_hand_value() self.computer_hand.calculate_hand_value() self.player_hand.val self.player_hand.real_val self.computer_hand.val self.computer_hand.real_val self.player_hand.check_straight_flush_and_tong() self.computer_hand.check_straight_flush_and_tong() # print(self.player_hand.real_val) # print(self.computer_hand.real_val) #check tong self.player_hand.real_val self.computer_hand.real_val if self.player_hand.tong and self.computer_hand.tong: print("Both tie") elif self.player_hand.tong: print(f"{self.__player.name} wins") self.__player.update_num_wins(3,5) elif self.computer_hand.tong: print("Computer wins") if self.player_hand.tong or self.computer_hand.tong: print("Computer hand: " , end="") self.computer_hand.display_cards() print(f"{self.computer_hand.hit} Deng") break self.player_hand.real_val self.computer_hand.real_val if self.player_hand.straight_flush and self.computer_hand.straight_flush: print("Both tie") elif self.player_hand.straight_flush: print(f"{self.__player.name} wins") self.__player.update_num_wins(3,3) elif self.computer_hand.straight_flush: print("Computer wins") if self.player_hand.straight_flush or self.computer_hand.straight_flush: print("Computer hand: " , end="") self.computer_hand.display_cards() print(f"{self.computer_hand.hit} Deng") break self.player_hand.real_val self.computer_hand.real_val if self.player_hand.real_val == self.computer_hand.real_val: print("Both tie") print("Computer hand: " , end="") self.computer_hand.display_cards() print(f"{self.computer_hand.hit} Deng") break elif self.player_hand.real_val > self.computer_hand.real_val: print(f"{self.__player.name} wins") self.__player.update_num_wins(3,1*self.player_hand.hit) print("Computer hand: " , end="") self.computer_hand.display_cards() print(f"{self.computer_hand.hit} Deng") break elif self.player_hand.real_val < self.computer_hand.real_val: print("Computer wins") print("Computer hand: " , end="") self.computer_hand.display_cards() print(f"{self.computer_hand.hit} Deng") break self.__player.update_num_plays(3) self.__player.update_balance(-10) # import sys # d = Deck() # d.shuffle_cards() # # print(d.deck) # p1 = Hand() # p1.draw_cards(d.deck,2) # print(f"player hand: {p1.hand}") # p1.display_cards() # p1.calculate_hand_value() # print(f"player val: {p1.val}") # print(f"player real val: {p1.real_val}") # p1.calcuate_suit() # p1.check_pok() # print(f"Pok : {p1.pok}") # print(f"player hit: {p1.hit}") # if p1.pok: # sys.exit() # else: # p1.add_more_card() # game = Pok_Deng() # game.play()
16383c707c0d2146b5cb3d88683788e5d80b899a
malhotraguy/FUN_WITH_JSON
/code.py
1,739
3.515625
4
import json import requests response = requests.get('https://jsonplaceholder.typicode.com/todos') todos = json.loads(response.text) # Map of userId to number of complete TODOs for that user todos_by_user = {} print("todos[:5]=",todos[:5]) # Increment complete TODOs count for each user. for todo in todos: if todo["completed"]: try: # Increment the existing user's count. todos_by_user[todo["userId"]] += 1 except KeyError: # This user has not been seen. Set their count to 1. todos_by_user[todo["userId"]] = 1 # Create a sorted list of (userId, num_complete) pairs. print("todos_by_user=",todos_by_user) top_users = sorted(todos_by_user.items(),key=lambda x: x[1], reverse=True) #sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons. print("top_users=",top_users,type(top_users)) # Get the maximum number of complete TODOs. max_complete = top_users[0][1] # Create a list of all users who have completed # the maximum number of TODOs. users = [] for user, num_complete in top_users: if num_complete < max_complete: break users.append(str(user)) max_users = ' and '.join(users) print("max_users =",max_users ) # Define a function to filter out completed TODOs # of users with max completed TODOS. def keep(todo): is_complete = todo["completed"] has_max_count = todo["userId"] in users return is_complete and has_max_count # Write filtered TODOs to file. with open("filtered_data_file.json", 'w') as data_file: filtered_todos = list(filter(keep, todos))#filter creates a list of elements for which a function returns true json.dump(filtered_todos, data_file, indent=2)
6de0b8f9eff5e0eee722726db9f9dd31d2b80377
e7k8v12/ProjectEuler
/0001_0100/0024/0024.py
1,379
3.75
4
# https://projecteuler.net/problem=24 # A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, # 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The # lexicographic permutations of 0, 1 and 2 are: # 012   021   102   120   201   210 # What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? # https://euler.jakumo.org/problems/view/24.html # Перестановка - это упорядоченная выборка объектов. К примеру, 3124 является одной из возможных перестановок из цифр # 1, 2, 3 и 4. Если все перестановки приведены в порядке возрастания или алфавитном порядке, то такой порядок будем # называть словарным. Словарные перестановки из цифр 0, 1 и 2 представлены ниже: # 012   021   102   120   201   210 # Какова миллионная словарная перестановка из цифр 0, 1, 2, 3, 4, 5, 6, 7, 8 и 9? # # 2783915460 from itertools import permutations print(sorted([''.join(x) for x in permutations('0123456789')])[999999])
d154b81b26a9b77011ac618c035f4cde2e4ef677
ne0de/passner
/src/database.py
2,528
3.546875
4
import sqlite3 from sqlite3 import Error class PassnerDatabase(): def __init__(self, path): self.path = path self.conn = None self.cursor = None self.mainTable = """ CREATE TABLE IF NOT EXISTS main ( id integer PRIMARY KEY, user text NOT NULL, password text NOT NULL, info text ); """ self.keyMasterTable = " CREATE TABLE IF NOT EXISTS keyMaster ( key text NOT NULL); " def existTables(self): try: self.cursor.execute("SELECT name FROM sqlite_master WHERE type = 'table'") r = self.cursor.fetchall() if len(r) != 2: return False return True except Error as e: print(e) def getAccounts(self): try: self.cursor.execute("SELECT * FROM main") r = self.cursor.fetchall() if len(r) == 0: return False return r except Error as e: print(e) def getKeyMaster(self): try: self.cursor.execute("SELECT key FROM keyMaster") rows = self.cursor.fetchall() if len(rows) == 0: return False print(rows[0][0]) return rows[0][0] # old with b64 -> return [key[:87], key[87:]] except Error as e: print(e) def deleteAccount(self, id): try: self.cursor.execute(f'DELETE FROM main WHERE id = {id};') self.conn.commit() return True except Error as e: print(e) return False def addAccount(self, data): try: self.cursor.execute(f'INSERT INTO main (user, password, info) VALUES (?, ?, ?)', data) self.conn.commit() return True except Error as e: print(e) return False def addKeyMaster(self, key): try: self.cursor.execute(f'INSERT INTO keyMaster (key) VALUES (?)', (key,)) self.conn.commit() except Error as e: print(e) def createTables(self): self.cursor.execute(self.mainTable) self.cursor.execute(self.keyMasterTable) def createConnection(self): try: self.conn = sqlite3.connect(self.path) self.cursor = self.conn.cursor() return True except Error as e: print(e) return False def closeConnection(self): if self.conn: self.conn.close()
9795f1767285ef52dbe3ee8b60a2087c75e6a97a
ViktorWase/TootieRootie
/dual_numbers.py
1,627
3.578125
4
from math import sin, cos, exp, log, sqrt, asin, acos from sys import version_info class DualNumber(): """ A dual number is a+b*e, where e*e=0. It's very useful for automatic differentiation. """ def __init__(self, a, b): self.a = a self.b = b # Overloads the standard operations: +, -, *, /. def __add__(self, other): return DualNumber(self.a+other.a, self.b+other.b) def __sub__(self, other): return DualNumber(self.a-other.a, self.b-other.b) def __mul__(self, other): return DualNumber(self.a*other.a, self.b*other.a + self.a*other.b) if version_info >= (3,0): def __truediv__(self, other): return DualNumber(self.a/other.a, (self.b*other.a-self.a*other.b)/(other.a*other.a)) else: def __div__(self, other): return DualNumber(self.a/other.a, (self.b*other.a-self.a*other.b)/(other.a*other.a)) def __str__(self): if self.b>=0: return str(self.a)+"+"+str(self.b)+"e" else: return str(self.a)+""+str(self.b)+"e" # Standard functions for dual numbers def sind(x): return DualNumber(sin(x.a), x.b*cos(x.a)) def cosd(x): return DualNumber(cos(x.a), -x.b*sin(x.a)) def expd(x): return DualNumber(exp(x.a), x.b*exp(x.a)) def logd(x): return DualNumber(log(x.a), x.b/x.a) def sqrtd(x): return DualNumber(sqrt(x.a), x.b*0.5/sqrt(x.a)) def powd(x, k): return DualNumber(pow(x.a, k), k*pow(x.a, k-1.0)*x.b) def acosd(x): return DualNumber(acos(x.a), -x.b/sqrt(1.0-x.a*x.a)) def asind(x): return DualNumber(asin(x.a), x.b/sqrt(1.0-x.a*x.a)) if __name__ == '__main__': x = DualNumber(1.0, 1.0) print(cosd(x)) from math import cos print((cos(1.0001)-cos(1.0))/0.0001)
01ecad8bd5b5f6a8d4cf667035ff3e225c444453
rubyclaguna/Intro-Python-II
/src/player.py
904
3.609375
4
# Write a class to hold player information, e.g. what room they are in # currently. from item import Item class Player: def __init__(self, name, room): self.name = name self.room = room self.inventory = [] def move(self, direction): if direction in ['n', 's', 'e', 'w']: next_room = self.room.get_direction(direction) if next_room is not None: self.room = next_room print(self.room) else: print("Oops! Can't move in that direction.") def display_inventory(self): print(f"{self.name}'s inventory: ") for item in self.inventory: print(item) def add_item(self, item): item.on_take() self.inventory.append(item) def drop_item(self, item): item.on_drop() self.inventory.remove(item)
15d088d1411f7534c77b0658f9e8e9d55387b733
conservativeghosts/CT_codesandstuff
/listAppV2.py
2,599
4.3125
4
import random """ Program Goals: 1. Get the input from the user! 2. Convert that input to an INT 3. Add that input to a list 4. Pull values from a specific intex positions """ listyBoi = [] def mainProgram(): while True: try: print("yo, we're gonna work with some lists now") print("Apparently we're still working on this thing, so...") print("Choose one of the following options Type a number ONLY!") choice = input("""1. Add to list, 2. Add a bunch of stuff to list 3. Return a value at an index position 4. print list 5. randomly search an item from your list 6. search for a specific item 7. end program """) if choice == "1": addToList() elif choice == "2": addMuchStuff() elif choice == "3": indexValues() elif choice == "4": print(listyBoi) elif choice == "5": randoSearch() elif choice == "6": painSearch() #why, this is pain. Thanks god else: break except: print("An error occurred") def addToList(): try: whatAdd = input("What number would you like to add to your list ") listyBoi.append(int(whatAdd)) print(listyBoi) except: print("Bro, you need to type a number") def addMuchStuff(): print("let's add a bunch of numbers to our list") numAdd = input("how many items would you like to add? ") numRange = input("What is the largest number possible that you want to be in your list? ") for x in range (0, int(numAdd)): listyBoi.append(random.randint (0, int(numRange))) print("the list is compleate") def indexValues(): try: indexPos = input("What index position would you like to pull a number from? ") print(mylist[int(indexPos)]) except: print("I'm sorry you need to start counting with the number 0") def randoSearch(): print("Here's a random walue from you list") print(listyBoi[random.randint(0, len(listyBoi)-1)]) def painSearch(): print("this is bad people don/'t realy do this/, but let us search bad") searchThing = input("What number are you looking to find") for x in range (len(listyBoi)): if listyBoi[x] == int(searchThing): print("your idem is at index position {}".format(x)) if __name__== "__main__": mainProgram()
e5604b1991ceacd307b40f140c57ab94d72b4a03
nymoral/euler
/p59.py
1,100
3.53125
4
import itertools def char_table(): chars = [] for c in range(128): good = False if 32 <= c < 127: good = True chars.append(good) return chars def guess_keys(cipher): table = char_table() src = tuple(range(97, 123)) step = 3 for key in itertools.product(src, repeat=step): good = True for i, c in enumerate(cipher): k = key[i % len(key)] if not table[k ^ c]: #print('Failing after {} tries because {}'.format(i, k ^ c)) good = False break if good: yield key def apply_key(cipher, key): chars = [] s = 0 for i, c in enumerate(cipher): k = key[i % len(key)] chars.append(chr(k ^ c)) s += k ^ c return s, ''.join(chars) if __name__ == '__main__': cipher = [] with open('p059_cipher.txt', mode='r') as f: for line in f.readlines(): cipher.extend(int(i) for i in line.split(',')) for pwd in guess_keys(cipher): print(pwd, apply_key(cipher, pwd))
d5a329edec5ccbce37ab1f77ea254eaff74c9433
dimikout3/ComputationalGeometry
/jimBeam.py
415
3.671875
4
def areaTriangle(x1,y1,x2,y2): return abs(x1*y2 - x2*y1)/2 if __name__ == '__main__': x1, y1 = 2,2 x2, y2 = 3,3 xm, ym = 1,1 OAOM = areaTriangle(x1,y1,xm,ym) OMOB = areaTriangle(xm,ym,x2,y2) OAOB = areaTriangle(x1,y1,x2,y2) MAMB = areaTriangle(x1-xm,y1-ym,x2-xm,y2-ym) # coolinear if (OAOM + OMOB) == (OAOB + MAMB): print('NO') else: print('YES')
99654b9c3230de9e712d5b33104a550e47b52351
kbhat1234/Python-Project
/python/dictionary1.py
225
3.890625
4
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print Dict.keys() print Dict.values() print Dict print Dict['Tiffany'] Dict1 = {10: 2008,5: 2007,15:2009, 1:2010} print Dict1.keys() print Dict1.values() print Dict1
59895778cbd8ad4d0ef745f973b1814cef22b865
anandvimal/data-structures-and-algorithms
/1 Algorithmic toolbox/week2/lcm.py
586
3.78125
4
def gcd_eucledian(a,b): if a==0: #print(f"return b:{b}") return b if b==0: #print(f"return a:{a}") return a #print(f"a:{a} b:{b}") holder = a%b a=b b=holder #print(f"a:{a} b:{b} holder:{holder}") return gcd_eucledian(a,b) if __name__ == "__main__": a, b = map(int, input().split()) #print(lcm(a,b)) if a >= b: pass else: holder = a a = b b = holder gcd=gcd_eucledian(a,b) #print(f"{gcd}") product = a*b lcm = product/gcd print(f"{int(lcm)}")
9d865b16e709e1e6718fe4da86fac786940be836
dltmdtn0128/Python_Programming
/Ch7/Ch7_1.py
135
3.609375
4
for i in range(1,101): if i%5==0 and i%7==0: print('FizzBuzz',i) elif i%5==0: print('Fizz',i) elif i%7==0: print('Buzz',i)
4d38bac22a93371b5d0040bd280788b52816d374
Robinzzs/pythonlearning
/basic-function-learning/format.py
149
3.53125
4
# -*- coding: utf-8 -*- print('%2d-%02d'%(3,1)) print('%.2f'%3.1415926) a='hello,{0},update{1:.1f}'.format('xiaoming',90.4534) print(a)
f4973e8b36ed07b2b91af5cc2eff46436bf9e8f7
AdamZhouSE/pythonHomework
/Code/CodeRecords/2736/58585/317751.py
500
3.703125
4
a=input() b=input() c=input() d=input() if a=='8 3' and b=='13 32 11 34 7 22 45 12': print(22) print(13) elif a=='5 3' and b=='3 2 1 4 7' and c=='Q 1 4 3': print(3) print(6) elif a=='5 3' and b=='3 2 1 4 7' and c=='Q 1 5 3' and d=='C 1 0': print(3) print(2) elif a=='5 3' and b=='3 2 1 4 7' and c=='Q 1 5 1': print(1) print(0) else: print(3) print(3)
6d8aaa7cab5626baf5b8c55bff48d3b567d1bca6
shuai-yang/SVM-classifier
/svm.py
3,391
3.953125
4
# Scikit-learn’s make_blobs function allows us to generate the two clusters/blobs of data from sklearn.datasets import make_blobs # Scikit-learn’s train_test_split function allows us to split the generated dataset into a part for training and a part for testing from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt # Define configuration options # The random seed for our blobs ensures that we initialize the pseudorandom numbers generator with the same start initialization blobs_random_seed = 42 # The centers represent the (X, y) positions of the centers of the blobs we’re generating centers = [(0,0), (5,5)] # The cluster standard deviation shows how scattered the centers are across the two-dimensional mathematical space. # The lower, the more condensed the clusters are cluster_std = 1 # The fraction of the test split shows what percentage of our data is used for testing purposes frac_test_split = 0.2 # The number of features for samples shows the number of classes we wish to generate data for # For binary classifier, that is 2 classes num_features_for_samples = 2 # The number of samples in total shows the number of samples that are generated in total num_samples_total = 1000 '''(1) Generating a dataset''' # Call make_blobs with the configuration options # Variable inputs will store the features and variable targets will store class outcomes inputs, targets = make_blobs(n_samples = num_samples_total, centers = centers, n_features = num_features_for_samples, cluster_std = cluster_std) print(inputs) # array([1,0,]) print(len(input)) print(len(targets)) # Split the inputs and targets into training and testing data. X_train, X_test, y_train, y_test = train_test_split(inputs, targets, test_size=frac_test_split, random_state=blobs_random_seed) # Save and load temporarily (optional) np.save('./data.npy', (X_train, X_test, y_train, y_test)) X_train, X_test, y_train, y_test = np.load('./data.npy', allow_pickle=True) # Now, if you run the code once, then comment np.save, you’ll always have your code run with the same dataset # Generate scatter plot for training data plt.scatter(X_train[:,0], X_train[:,1]) plt.title('Linearly separable data (using 2 features)') plt.xlabel('X1') plt.ylabel('X2') plt.show() '''(2) Building the SVM classifier''' from sklearn import svm # Initialize SVM classifier clf = svm.SVC(kernel='linear') # Fit training data to the classifier clf = clf.fit(X_train, y_train) '''(3) Using SVM to predict new data samples''' # Predict the test set predictions = clf.predict(X_test) # Generate confusion matrix from sklearn.metrics import plot_confusion_matrix matrix = plot_confusion_matrix(clf, X_test, y_test, cmap=plt.cm.Blues, normalize='true') plt.title('Confusion matrix for my classifier') plt.show() '''(4) Finding the support vectors of the trained SVM ''' # Get support vectors support_vectors = clf.support_vectors_ print(support_vectors) # Visualize support vectors plt.scatter(X_train[:,0], X_train[:,1]) plt.scatter(support_vectors[:,0], support_vectors[:,1], color='red') plt.title('Linearly separable data with support vectors') plt.xlabel('X1') plt.ylabel('X2') plt.show() '''(5) Visualizing the decision boundary''' from mlxtend.plotting import plot_decision_regions # Plot decision boundary plot_decision_regions(X_test, y_test, clf=clf, legend=2) plt.show()
56bc5ec2c21cf4081d47d175b23aec54770e0424
JansenRachel/functions_intermediate1
/functions_intermediate1.py
286
3.65625
4
import random def randInt(min=0, max=100): num = random.random()*(max-min) + min return round(num) print(randInt()) # print(randInt(max=35)) # print(randInt(min=66)) # print(randInt(min=16, max=85)) print(randInt(max=5)) print(randInt(min=95)) print(randInt(min=20, max=25))
a805b2df50168e571d46fa5edb514f9b2da6095a
davidchuck08/InterviewQuestions
/src/NthUglyNumber.py
501
3.53125
4
#!/usr/bin/python def getNthUglyNumber(n): if n is None: return 0 if n<=0: return 0 list=[] list.append(1) i=0 j=0 k=0 while len(list)<n: m2=list[i]*2 m3=list[j]*3 m5=list[k]*5 minNum = min(m2, min(m3,m5)) if minNum == m2: i+=1 if minNum ==m3: j+=1 if minNum ==m5: k+=1 list.append(minNum) return list n=10 print getNthUglyNumber(n)
81582ed1fd71ce8d246ca41c7c36b77700baeaeb
RainingComputers/pykitml
/pykitml/datasets/boston.py
2,823
3.546875
4
import os from urllib import request from numpy import genfromtxt from .. import pklhandler ''' This module contains helper functions to download and load the boston housing dataset. ''' def get(): ''' Downloads the boston dataset from https://archive.ics.uci.edu/ml/machine-learning-databases/housing/ and saves it as a pkl file `boston.pkl`. Raises ------ urllib.error.URLError If internet connection is not available or the URL is not accessible. OSError If the file cannot be created due to a system-related error. KeyError If invalid/unknown type. Note ---- You only need to call this method once, i.e, after the dataset has been downloaded and you have the `boston.pkl` file, you don't need to call this method again. ''' # Url to download the dataset from url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data' # Download the dataset print('Downloading housing.data...') request.urlretrieve(url, 'housing.data') print('Download complete.') # Parse the data and save it as a pkl file pklhandler.save(genfromtxt('housing.data'), 'boston.pkl') # Delete unnecessary files os.remove('housing.data') print('Deleted unnecessary files.') def load(): ''' Loads the boston housing dataset from pkl file. The inputs have following columns: - CRIM : per capita crime rate by town - ZN : proportion of residential land zoned for lots over 25,000 sq.ft. - INDUS : proportion of non-retail business acres per town - CHAS : Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) - NOX : nitric oxides concentration (parts per 10 million) - RM : average number of rooms per dwelling - AGE : proportion of owner-occupied units built prior to 1940 - DIS : weighted distances to five Boston employment centres - RAD : index of accessibility to radial highways - TAX : full-value property-tax rate per $10,000 - PTRATIO : pupil-teacher ratio by town - B : 1000(Bk - 0.63)^2 where Bk is the proportion of black by town - LSTAT : % lower status of the population The outputs are - MEDV : Median value of owner-occupied homes in $1000's Returns ------- inputs_train : numpy.array outputs_train : numpy.array inputs_test : numpy.array outputs_test : numpy.array ''' data_array = pklhandler.load('boston.pkl') inputs_train = data_array[0:500, :-1] outputs_train = data_array[0:500, -1] inputs_test = data_array[500:, :-1] outputs_test = data_array[500:, -1] return inputs_train, outputs_train, inputs_test, outputs_test
cff7a455e2d46fd02528d2eb583d3a568a810e0c
kgaurav123/Python-Projects
/course/seven.py
751
4.09375
4
while True: try: number=int(input("Enter a number")) break except ValueError: print("You didn't entered any number") except: print("Unknown error occured") print("Thanks for your response") secret_number=7 while True: n=int(input("Enter a number")) if(n==secret_number): print("Bravo!you guessed it correct") break print("Sorry Guess again") #from decimal import Decimal as D from decimal import * sum=Decimal(4) sum+=Decimal("0.02") sum+=Decimal("0.05") sum-=Decimal("0.07") print("sum={}".format(sum)) sum_1=Decimal(0) sum_1+=Decimal("0.0111111111111111") sum_1+=Decimal("0.0111111111111111") print("sum=",sum_1) sum_1-=Decimal("0.0222222222222222") print("sum=",sum_1)
f2a1cccafced8623596a883abd65cf966f49c5a7
mnogom/python-project-lvl1
/brain_games/engine.py
1,836
3.984375
4
"""Module create templates for game status and describe engine of any game.""" import prompt COUNT_OF_ROUNDS_TO_WIN = 3 TEMPLATE_QUESTION = "Question: {task}" TEMPLATE_ON_RIGHT_ANSWER = "Correct!" TEMPLATE_ON_WRONG_ANSWER = ("'{user_answer}' is wrong answer ;(. " "Correct answer was '{right_answer}'.\n" "Let's try again, {username}!") TEMPLATE_ON_WIN = "Congratulations, {username}!" TEMPLATE_WELCOME = "Welcome to the Brain Games!" TEMPLATE_GREETING = "Hello, {}!" TEMPLATE_GET_NAME = "May I have your name? " TEMPLATE_GET_ANSWER = "Your answer: " def play(game) -> None: """Main function to start the game. At the start game welcomes User and ask his name. Then engine shows to him description of current game and first question. For win User must give right answers for 3 questions. If any answer is wrong - User lost. :param game: module with game rules. Module must contain DESCRIPTION and function generate_task (that must return the question and the right answer) """ print(TEMPLATE_WELCOME) username = prompt.string(TEMPLATE_GET_NAME) print(TEMPLATE_GREETING.format(username)) # -- Show to user Description print(game.DESCRIPTION) # -- Main game mechanic for _ in range(COUNT_OF_ROUNDS_TO_WIN): game_question, right_answer = game.generate_round() print(TEMPLATE_QUESTION.format(task=game_question)) user_answer = prompt.string(TEMPLATE_GET_ANSWER) if user_answer != right_answer: print(TEMPLATE_ON_WRONG_ANSWER.format( username=username, user_answer=user_answer, right_answer=right_answer)) return print(TEMPLATE_ON_RIGHT_ANSWER) print(TEMPLATE_ON_WIN.format(username=username))
43fd0b72dd8b594ace0936201a9d4499656d7b1c
0318648DEL/python-practice
/untitled/13.1.py
215
3.59375
4
filename=input("파일 이름을 입력하세요 : ") f=open(filename) erase=input("제거할 단어를 입력하세요 : ") content=f.read() new=content.replace(erase,"") f.close() f=open(filename,"w") f.write(new)
2b0039eb72257642ed9c2a3125a741d455a7f555
CollinsMbogori/SYSC3010_collinsmwenda_mbogori
/Lab 2/temp_emulator.py
209
3.90625
4
import random def get_temperature(): temp = random.randint(-1,41) if temp >= 0 or temp <= 40: print("Temperature within range", temp) else: print("Temperature out of range", temp)
3b26ca32ac3ac1d798a951b82a7b5670f2e53ee7
WinrichSy/Codewars_Solutions
/Python/6kyu/CountLettersInString.py
181
3.53125
4
#Count Letters in String #https://www.codewars.com/kata/5808ff71c7cfa1c6aa00006d import collections def letter_count(s): s = collections.Counter(list(s.lower())) return s
96f7499a9736e2a0e2dff903d5ffb9480f672814
BertDaNerd/IntroToPython
/madlib.py
428
3.71875
4
print("""Welcome to Madlibs You ll be asked for different nouns and verbs, try to make' em funny""") plural_noun = raw_input("please provide a plural noun:") noun1 = raw_input("please provide a noun:") noun2 = raw_input("please provide a noun:") song = raw_input("please provide the title of a song:") verb = raw_input("please provide a verb:") madlibs = ("""Learning to drive is a tricky process. There are a f) 1. Keep two %s
5ee6a24923051820f028beb82f09f4a1d0bef2f9
pavanmsvs/hackeru-python
/capitalise-string.py
139
3.75
4
name = input("Enter a name \n") n=list(name.split(" ")) j=[] for i in n: j=i[0].upper()+i[1:len(i)] print(j,end=" ")
aa46dfc57fd0a402f8810f2560c2aed9f358dda5
Teinstein/mathstein
/Mathstein/mathmatcalc.py
5,601
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[36]: def mataddition(A,B): """ Adds two matrices and returns the sum :param A: The first matrix :param B: The second matrix :return: Matrix sum """ if(len(A)!=len(B) or len(A[0])!=len(B[0])): return "Addition not possible" for i in range(len(A)): for j in range(len(A[0])): A[i][j]=A[i][j]+B[i][j] return A def matsubtraction(A,B): """ Subtracts matrix B from matrix A and returns difference :param A: The first matrix :param B: The second matrix :return: Matrix difference """ if(len(A)!=len(B) or len(A[0])!=len(B[0])): return "Subtraction not possible" for i in range(len(A)): for j in range(len(A[0])): A[i][j]=A[i][j]-B[i][j] return A def matmultiplication(A,B): """ Returns the product of the matrix A * B :param A: The first matrix - ORDER MATTERS! :param B: The second matrix :return: The product of the two matrices """ if(len(A[0])!=len(B)): return "Multiplication not possible" result = [[sum(a * b for a, b in zip(A_row, B_col)) for B_col in zip(*B)] for A_row in A] return result def zeros_matrix(rows, cols): """ Creates a matrix filled with zeros. :param rows: the number of rows the matrix should have :param cols: the number of columns the matrix should have :return: list of lists that form the matrix """ M = [] while len(M) < rows: M.append([]) while len(M[-1]) < cols: M[-1].append(0.0) return M def copy_matrix(M): """ Creates and returns a copy of a matrix. :param M: The matrix to be copied :return: A copy of the given matrix """ rows = len(M) cols = len(M[0]) MC = zeros_matrix(rows, cols) for i in range(rows): for j in range(cols): MC[i][j] = M[i][j] return MC def matdeterminant(A, det=0): """ Find determinant of a square matrix using full recursion :param A: the matrix to find the determinant for :param total=0: safely establish a total at each recursion level :returns: the running total for the levels of recursion """ indices = list(range(len(A))) if len(A) == 2 and len(A[0]) == 2: val = A[0][0] * A[1][1] - A[1][0] * A[0][1] return val for fc in indices: As = copy_matrix(A) As = As[1:] height = len(As) for i in range(height): As[i] = As[i][0:fc] + As[i][fc+1:] sign = (-1) ** (fc % 2) # F) sub_det = matdeterminant(As) det += sign * A[0][fc] * sub_det return det def mataddition(A,B): """ Adds two matrices and returns the sum :param A: The first matrix :param B: The second matrix :return: Matrix sum """ if(len(A)!=len(B) or len(A[0])!=len(B[0])): return "Addition not possible" for i in range(len(A)): for j in range(len(A[0])): A[i][j]=A[i][j]+B[i][j] return A def matsubtraction(A,B): """ Subtracts matrix B from matrix A and returns difference :param A: The first matrix :param B: The second matrix :return: Matrix difference """ if(len(A)!=len(B) or len(A[0])!=len(B[0])): return "Subtraction not possible" for i in range(len(A)): for j in range(len(A[0])): A[i][j]=A[i][j]-B[i][j] return A def matmultiplication(A,B): """ Returns the product of the matrix A * B :param A: The first matrix - ORDER MATTERS! :param B: The second matrix :return: The product of the two matrices """ if(len(A[0])!=len(B)): return "Multiplication not possible" result = [[sum(a * b for a, b in zip(A_row, B_col)) for B_col in zip(*B)] for A_row in A] return result def zeros_matrix(rows, cols): """ Creates a matrix filled with zeros. :param rows: the number of rows the matrix should have :param cols: the number of columns the matrix should have :return: list of lists that form the matrix """ M = [] while len(M) < rows: M.append([]) while len(M[-1]) < cols: M[-1].append(0.0) return M def copy_matrix(M): """ Creates and returns a copy of a matrix. :param M: The matrix to be copied :return: A copy of the given matrix """ rows = len(M) cols = len(M[0]) MC = zeros_matrix(rows, cols) for i in range(rows): for j in range(cols): MC[i][j] = M[i][j] return MC def matdeterminant(A, det=0): """ Find determinant of a square matrix using full recursion :param A: the matrix to find the determinant for :param total=0: safely establish a total at each recursion level :returns: the running total for the levels of recursion """ indices = list(range(len(A))) if len(A) == 2 and len(A[0]) == 2: val = A[0][0] * A[1][1] - A[1][0] * A[0][1] return val for fc in indices: As = copy_matrix(A) As = As[1:] height = len(As) for i in range(height): As[i] = As[i][0:fc] + As[i][fc+1:] sign = (-1) ** (fc % 2) # F) sub_det = matdeterminant(As) det += sign * A[0][fc] * sub_det return det # In[ ]: # In[ ]:
09338353395039297870a5a0cc37d2fd71371c81
AdamZhouSE/pythonHomework
/Code/CodeRecords/2686/60627/299554.py
109
3.546875
4
n = int(input()) for i in range(n): k = input() input() num=input() s = k + num print(s)
ef8c036ea6cbbada34a9965c22667fc2d79103bc
seanschneeweiss/RoSeMotion
/app/resources/b3d/math3d.py
5,557
3.6875
4
import math # Converts angle from degree to radian def to_radian(angle): return angle / 180.0 * math.pi # Constructs a quaternion from a rotation of degree 'angle' around vector 'axis' def quaternion(axis, angle): angle *= 0.5 sinAngle = math.sin(to_radian(angle)) return normalize((axis[0] * sinAngle, axis[1] * sinAngle, axis[2] * sinAngle, math.cos(to_radian(angle)))) # Normalizes quaternion 'q' def normalize(q): length = math.sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]) return (q[0] / length, q[1] / length, q[2] / length, q[3] / length) # Multiplies 2 quaternions : 'q1' * 'q2' def multiply_quat(q1, q2): return (q1[3] * q2[0] + q1[0] * q2[3] + q1[1] * q2[2] - q1[2] * q2[1], q1[3] * q2[1] + q1[1] * q2[3] + q1[2] * q2[0] - q1[0] * q2[2], q1[3] * q2[2] + q1[2] * q2[3] + q1[0] * q2[1] - q1[1] * q2[0], q1[3] * q2[3] - q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2]) # Converts quaternion 'q' to a rotation matrix def matrix_from_quat(q): x2 = q[0] * q[0] y2 = q[1] * q[1] z2 = q[2] * q[2] xy = q[0] * q[1] xz = q[0] * q[2] yz = q[1] * q[2] wx = q[3] * q[0] wy = q[3] * q[1] wz = q[3] * q[2] return (1.0 - 2.0 * (y2 + z2), 2.0 * (xy - wz), 2.0 * (xz + wy), 0.0, 2.0 * (xy + wz), 1.0 - 2.0 * (x2 + z2), 2.0 * (yz - wx), 0.0, 2.0 * (xz - wy), 2.0 * (yz + wx), 1.0 - 2.0 * (x2 + y2), 0.0, 0.0, 0.0, 0.0, 1.0) # Constructs a translation matrix def matrix_from_trans(trans): return (1, 0, 0, trans[0], 0, 1, 0, trans[1], 0, 0, 1, trans[2], 0, 0, 0, 1) # Returns an identity matrix def identity_matrix(): return (1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) # Multiplies 2 Mat4 : 'm1' * 'm2' def multiply_matrix(m1, m2): res = [] for i in range(0, 4): for j in range(0, 4): res.append(m1[i * 4] * m2[j] + m1[i * 4 + 1] * m2[j + 4] + m1[i * 4 + 2] * m2[j + 8] + m1[i * 4 + 3] * m2[j + 12]) return res # Multiplies matrix 'm' by vector 'v' def multiply_mat_by_vec(m, v): w = 1.0 if len(v) == 4: w = v[3] return (m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * w, m[4] * v[0] + m[5] * v[1] + m[6] * v[2] + m[7] * w, m[8] * v[0] + m[9] * v[1] + m[10] * v[2] + m[11] * w, m[12] * v[0] + m[13] * v[1] + m[14] * v[2] + m[15] * w) # Transposes matrix 'm' def transpose(m): return (m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14], m[3], m[7], m[11], m[15]) # Calculates inverse of matrix m # Reimplement of gluInvertMatrix def invert_matrix(m): inv = [] inv.append(m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10]) inv.append(-m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10]) inv.append(m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6]) inv.append(-m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6]) inv.append(-m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10]) inv.append(m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10]) inv.append(-m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6]) inv.append(m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6]) inv.append(m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9]) inv.append(-m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9]) inv.append(m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5]) inv.append(-m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5]) inv.append(-m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9]) inv.append(m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9]) inv.append(-m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5]) inv.append(m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]) det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12] if det == 0: return None det = 1.0 / det mOut = [] for i in range(16): mOut.append(inv[i] * det) return mOut # Calculates length^2 of vector 'v' def length2(v): return v[0] * v[0] + v[1] * v[1] + v[2] * v[2] # Calculates vector dot product : 'v1' * 'v2' def dot(v1, v2): return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2] # Calculates vector cross product : 'v1' x 'v2' def cross(v1, v2): return (v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0]) # Normalizes vector 'v' def normalize_vec(v): l2 = length2(v) if l2 == 0: return (0, 0, 0) l = math.sqrt(l2) return (v[0] / l, v[1] / l, v[2] / l)
5fc4e39a1bee76d12b39b8e5d55640f8c338798b
aidanrfraser/CompSci106
/sumList.py
192
3.859375
4
from cisc106 import assertEqual def sum_list(alist): """ Sums all elements in a list """ if not alist: return 0 else: return alist[0] + sum_list(alist[1:])
a9436c5b003d394405d5604ed2d7057a1b06c5aa
xndong1020/python3-deep-dive-02
/8. itertools/4.infinite_iterator.py
1,094
3.71875
4
from itertools import count count1 = count(10) # start from 10, step default to 1 print(count1) # lazy, infinite iterator ### 10 11 12 13 14 15 16 17 18 19 ### for _ in range(10): print(next(count1)) count2 = count(1, 2) for _ in range(10): print(next(count2)) ### 1 3 5 7 9 11 13 15 17 19 ### count3 = count(10.6, 0.1) for _ in range(10): print(next(count3)) ### 10.6 10.7 10.799999999999999 10.899999999999999 10.999999999999998 11.099999999999998 11.199999999999998 11.299999999999997 11.399999999999997 11.499999999999996 ### from itertools import cycle cycled = cycle(["a", "b", "c"]) print(cycled) # <itertools.cycle object at 0x00000196D3EDF3C0> for _ in range(5): print(next(cycled)) # a b c a b from itertools import repeat # infinite iterator infinite_spam = repeat("spam") # Lazy iterator for _ in range(10): print(next(infinite_spam)) # spam spam spam spam spam spam spam spam spam spam # Optionally, you can specify a count to make the iterator finite finite_spam = repeat("spam", 3) print(list(finite_spam)) # ['spam', 'spam', 'spam']
d0cf8346c5aa4fad44093bb5b339b2e8edc7b0dd
eshaw2/SoftwareDesign
/fermat.py
552
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 9 14:47:52 2014 Based on user input, this program verifies whether Fermat's Last Theorem holds for the inputted values. @author: elena """ # part 1 def check_fermat(a,b,c,n): summ = a**n+b**n expo= c**n if n > 2 and summ == expo: print 'Holy smokes, Fermat was wrong!' else: print "No, that doesn't work" check_fermat(1,1,1,3) # part 2 a= int(raw_input('a?')) b= int(raw_input('b?')) c= int(raw_input('c?')) n= int(raw_input('n?')) check_fermat(a,b,c,n)
6270d6ea71e4323a47d68ade434cc04f85cf5f0d
GourBera/ProjectPython3
/ProjectPython3/OOPS/OOPS2.py
1,187
3.921875
4
''' Created on Mar 7, 2018 @author: berag ''' class Student(): no_of_Std = 0 per_rise = 1.05 def __init__(self, first, last, marks): self.first = first self.last = last self.marks = marks self.email = first + '.' +last + '@gmail.com' Student.no_of_Std += 1 def fullname(self): return '{} {}'.format(self.first, self.last) def apply_percentage_rise(self): self.marks = int(self.marks * 1.05) Std1 = Student('Gour', 'Bera', 80) Std2 = Student('Tulsi', 'raman', 60) Std3 = Student('Tulsi', 'raman', 60) print(Std1.email) print(Std1.marks) Std1.apply_percentage_rise() print(Std1.marks) print(Student.no_of_Std) ''' Inheretance ''' class Dumb(Student): per_rise = 1.10 #pass def __init__(self, first, last, marks, PLanguage): super().__init__(first, last, marks) self.PLanguage = PLanguage Std3 = Dumb('Dhanush', 'kumar', 70, 'Java') print(Std3.PLanguage)
011362f6a420257421f28ecda74353e7d06cdb4b
Anson008/Think_Python_Exercise
/Exercise_6_5.py
220
4.03125
4
def gcd(a, b): """Take parameters a and b and returns their greatest common divisor. a, b: integer """ r = a % b if r == 0: return b else: return gcd(b, r) print(gcd(6, 8))
58b846f75bbf29ee0f882f9a318740778af09f03
DevJ5/CS50
/reference.py
1,722
4.03125
4
from sys import argv print(argv[0]) print("Enter a number: ") x = int(input()) print("Enter a number: ") y = int(input()) print(f"x + y = {x + y}") print(f"x / y = {x / y:.2f}") print(f"x // y = {x // y}") # For flooring division. print("Enter y or n: ") answer = input() if answer == "y" or answer == "Y": print("You answered yes.") elif answer == "n" or answer == "N": print("You answered no.") else: print("That wasn't an answer") def cough(): print("cough ", end="") # To negate the newline character, default is end="\n" if not False: # Using the not keyword a = " *okay* " print(a.upper().strip()) # Strip is like trim, removes whitespace. # Can just iterate over a string or a list for that matter. for i in "abc": cough() def getNames(): print("Enter a name: ") student = {"name": input()} student["age"] = input() print(f"Name = {student['name']}, age = {student['age']}") getNames() # Files: # file = open("somefile.txt", r) # for line in file: # words.add(line.rstrip("\n")) # List of tuples: presidents = [ ("George Washington", 1789), ("John Adams", 1797), ("Thomas Jefferson", 1801), ("James Madison", 1809), ] for president, year in presidents: print(f"{president} ({year})") # This approach apparantly solves problems: # if __name__ == "__main__": # main() # -- Creating a Virtual Environment -- # # python -m venv project_env # . activate # pip list # deactivate (there is a new shell command created when we activated the environment) with open("registered.csv", "r") as file: reader = csv.reader(file) students = list(reader) return render_template("registered.html", students=students) jsonify(words) # from flask library
90140bcaa185ec3016c4fe23c1694f1eb45fee35
yoBuhler/POOFacul
/LISTA 9 - Encapsulamento/main.py
1,815
3.75
4
class Conta: def __init__(self, cpf, nome, saldo): self._cpf = cpf self._nome = nome self._saldo = saldo self._numero_alteracoes = 0 @property def cpf(self): return self._cpf @cpf.setter def cpf(self, cpf): self._cpf = cpf self._numero_alteracoes += 1 @property def nome(self, nome): return self._nome @nome.setter def nome(self, nome): self._nome = nome self._numero_alteracoes += 1 @property def numero_alteracoes(self): return self._numero_alteracoes @numero_alteracoes.setter def numero_alteracoes(self, numero_alteracoes): self._numero_alteracoes = numero_alteracoes def deposita(self, valor): self._saldo += valor c = Conta('1111', 'João', 1000.0) print(c.numero_alteracoes) c.cpf = '1111111' print(c.numero_alteracoes) c.nome = 'Maria' print(c.numero_alteracoes) class Veiculo: def __init__(self, modelo, ano, qtde_litros_no_tanque): self.__modelo = modelo self.__ano = ano self.__qtde_litros_no_tanque = qtde_litros_no_tanque @property def modelo(self): return self.__modelo @modelo.setter def modelo(self, modelo): self.__modelo = modelo @property def ano(self): return self.__ano @ano.setter def ano(self, ano): self.__ano = ano @property def qtde_litros_no_tanque(self): return self.__qtde_litros_no_tanque @qtde_litros_no_tanque.setter def qtde_litros_no_tanque(self, qtde_litros_no_tanque): self.__qtde_litros_no_tanque = qtde_litros_no_tanque def abastecer(self, qtde): self.qtde_litros_no_tanque += qtde v = Veiculo('celta', '2010', 12.0) v.ano = '2010' v.__ano = '2010'
8a0511a700895b69ed4daa9200ace9a6dd4be70d
Vignettes/PythonBootcamp
/Section_20_Lambdas_and_Built_In_Functions.py/abs_sum_round.py
2,235
4.40625
4
### abs ### stands for absolute value. Returns the absolute value of a number. ### The argument may be an integer or a floating point number. print(abs(-23)) # You can import math to turn everything to float first import math print(math.fabs(-4)) # returns 4.0 ### Sum ### takes an iterable and an optional start. ### Returns the sum of start and the items of an iterable from left to right and returns ### the total. Start by default is 0. print(sum([1,2,3])) # 6 print(sum([1,2,3], 10)) # 16, starts at 10 adds 1+2+3 ### Round ### Round will take a number and round it to ndigits precision after the decimal point ### If ndigits is omitted or is none, it returns the nearest integer to it's input. print(round(3.51234)) # 4 print(round(3.51234, 3)) #3.512 ### Write a function called "max_magnitute" that accepts a single list full of numbers. ### It should return the magnitude of the number with the largest magnitude (furthest from ### zero). ### e.x. max_magnitude([300, 20, -900]) #900 ##### I need an explanation why the below doesn't work on Udemy### def max_magnitude(x): return abs(max(x)) print(max_magnitude([2,54,4])) ################################################################## # The supposed correct way # def max_magnitude(nums): return max(abs(num) for num in nums) ### Write a function called "sum_even_values". This function should accept a variable number ### of arguments and return the sum of all the arguments that are divisible by 2. If ### there are no numbers divisible by 2, the function should return 0. To be clear, it accepts ### all the numbers as individual arguments. ### sum_even_values(1,2,3,4,5,6) # 12; 2+4+6=12 def sum_even_values(*nums): return sum(num for num in nums if num % 2 == 0) # Return the sum of the nums if the num in nums divide by 2 == 0 (even) sum_even_values(1,2,3,4,5,6) #12 ### Write a function called "sum_floats". This function should accept a variable number ### of arguments. The function should return the sum of all the parameters that are floats. ### If there are no floats the function should return 0 ### sum_floats(1.5, 2.4, 'awesome', [], 1) # 3.9 def sum_floats(*floats): return float(sum(num for num in floats if )))
c58ea977b1f3d7ed33b64ca329d3d7647e229cd8
suifengqjn/python_study
/12file/file_deep.py
2,671
3.640625
4
# # # open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。 # # open(file, mode='r') # 完整的语法格式为: # # open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) # 参数说明: # # file: 必需,文件路径(相对或者绝对路径)。 # mode: 可选,文件打开模式 # buffering: 设置缓冲 # encoding: 一般使用utf8 # errors: 报错级别 # newline: 区分换行符 # closefd: 传入的file参数类型 # opener: #常用model # t 文本模式 (默认)。 # x 写模式,新建一个文件,如果该文件已存在则会报错。 # + 打开一个文件进行更新(可读可写)。 # r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 # r+ 打开一个文件用于读写。文件指针将会放在文件的开头。 # w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 # w+ 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 # a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 #file 对象常用方法 # 1 # file.close() # # 关闭文件。关闭后文件不能再进行读写操作。 # # 2 # file.flush() # # 刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。 # # 3 # file.fileno() # # 返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。 # # 6 # file.read([size]) # # 从文件读取指定的字节数,如果未给定或为负则读取所有。 # # 7 # file.readline([size]) # # 读取整行,包括 "\n" 字符。 # # 8 # file.readlines([sizeint]) # # 读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。 # # 9 # file.seek(offset[, whence]) # # 设置文件当前位置 # # 10 # file.tell() # # 返回文件当前位置。 # # 12 # file.write(str) # # 将字符串写入文件,返回的是写入的字符长度。 # # 13 # file.writelines(sequence) # # 向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。 filePth = "./3.txt" f = open(filePth, "a+") f.writelines("qwe\n")
52cc76a89a90743c1d3eb18a31af7c5599e8c374
linfangzhi/py
/00003.py
325
3.6875
4
def Dec2Bin(dec): temp = [] result = '' while dec: quo = dec % 2 # 取余 dec = dec // 2 # 地板除 temp.append(quo) while temp: result += str(temp.pop()) # 移除最后的一个字符 return result Dec2Bin1 = input("heiheihei") a = int(Dec2Bin1) print(Dec2Bin(a))
7394c5c6319a8656dc6040037af8cd9f7b64f11f
Liang-Jian/EKIA
/python/ModelDesign/door/door_marry.py
4,149
3.609375
4
''' page57 门面模式的应用 ''' # # class EventManager(object): # def __init__(self): # print("Event Manager :: Let me talk to the folks \n") # def arrange(self): # self.hotelier = Hotelier() # self.hotelier.bookHotel() # # self.florist = Florist() # self.florist.setFlowerRequirements() # # self.caterer = Caterer() # self.caterer.setCuisine() # # self.musician = Musician() # self.musician.setMusicType() # # class Hotelier(object): # def __init__(self): # print("Arranging the hotel for Marriage?--") # # def __isAvailable(self): # print("Is the hotel free for the event on given day") # return True # def bookHotel(self): # if self.__isAvailable(): # print("Registered the booking \n") # class Florist(object): # def __init__(self): # print("Flower Decorations for the Event ?--") # def setFlowerRequirements(self): # print("Carnations,roses and lilies would be used for Decorations \n\n") # class Caterer(object): # def __init__(self): # print("Food Arrangements for the Event ---") # def setCuisine(self): # print("Chinese & Continental Cuisine to be served \n\n") # class Musician(object): # def __init__(self): # print("Musical Arrangements for the Marriage --") # def setMusicType(self): # print("Jazz and Classical will be played \n\n") # # class You(object): # def __init__(self): # print("YOU:: Whoa! Marriage Arrangements??!!") # def askEventManager(self): # print("You:: Let's Contact the Event Manager \n\n") # em = EventManager() # em.arrange() # def __del__(self): # print("YOU:: Thanks to Event Manager,All preparations done! Phew!") # # you = You() # you.askEventManager() import os,sys,time,subprocess,pickle,platform,logging import tempfile,shutil,pymysql,multiprocessing,threading # import win32api,win32com,win32gui,win32con from selenium.webdriver.support.select import Select caseID = "11" from decimal import Decimal from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import pymysql # from PIL import ImageGrab,Image sep = os.path.sep # \ AGENT_PATH = os.path.abspath(os.path.join(os.getcwd(),"./")) # agent home python ac/sel/pro/exe.py PIC_PATH = AGENT_PATH + "\\result\\images\\"+caseID # pic home LOG_PATH = AGENT_PATH + "\\result\\log\\"+caseID # log home from selenium import webdriver if not os.path.exists(LOG_PATH) : os.makedirs(LOG_PATH) timeout = TIME_OUT = 30 kEys ='0x2c' global logger,path BasePath = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) Flie_Path = os.path.join(BasePath,"porjtect") path = Flie_Path if platform.system() == "Windows" else "/home/jettech/Agent/execute" infoTable = model = ifInstallMonkey = ifRunMonkey = None open(LOG_PATH + "\\processLog.txt", 'w') # open log file logger = logging.getLogger("jettech") # create logger logger.setLevel(logging.INFO) fh = logging.FileHandler(LOG_PATH+ "\\processLog.txt") # create handle ,write2file formatter = logging.Formatter('%(message)s') # define handle 's formatter fh.setFormatter(formatter) logger.addHandler(fh) # add logger to handle # driver = webdriver.Ie() driver = webdriver.Ie() driver.get("http://221.226.73.174:10580/jettechHomePage/") driver.maximize_window() driver.implicitly_wait(10) logger.info("get url success") driver.find_element_by_id("username").send_keys("370303199011026610") driver.implicitly_wait(5) driver.find_element_by_id("password").send_keys("798513") driver.implicitly_wait(5) driver.find_element_by_id("btn_login").click() driver.implicitly_wait(5) pngPATH=os.path.abspath('.') + "\\result\\image"
a94469345630c5d14a329c9b85e465e5395825e2
anikahussen/algorithmic_excercises
/functions/myfunctions.py
4,541
4.375
4
#line drawing module def horizontal_line(width): ''' Create horizontal line based on width value parameter ''' print ("*" * width) def vertical_line(shift, height): ''' Create vertical line based on the shift and height value paramaters ''' for line in range(0, height): print (" " * ((shift) - 1)+"*") def two_vertical_lines (width, height): ''' Create two verical line based on width and height parameters ''' for line in range(0, height): print ("*" + " " * (width - 2) + "*") #----------------------------------------------------------------------# #digital numbers module def number_0 (width): ''' prints the number 0 as it would appear on a digital display using the supplied width value ''' print() horizontal_line(width) two_vertical_lines (width, 3) horizontal_line(width) print() def number_1 (width): ''' prints the number 1 as it would appear on a digital display using the supplied width value ''' print() vertical_line(width, 5) print() def number_2 (width): ''' prints the number 2 as it would appear on a digital display using the supplied width value ''' print() horizontal_line(width) vertical_line(width, 1) horizontal_line(width) vertical_line(0, 1) horizontal_line(width) print() def number_3 (width): ''' prints the number 3 as it would appear on a digital display using the supplied width value ''' print() horizontal_line(width) vertical_line(width, 1) horizontal_line(width) vertical_line(width, 1) horizontal_line(width) print() def number_4 (width): ''' prints the number 4 as it would appear on a digital display using the supplied width value ''' print() two_vertical_lines (width, 2) horizontal_line(width) vertical_line(width, 2) print() def number_5 (width): ''' prints the number 5 as it would appear on a digital display using the supplied width value ''' print() horizontal_line(width) vertical_line(0, 1) horizontal_line(width) vertical_line(width, 1) horizontal_line(width) print() def number_6 (width): ''' prints the number 6 as it would appear on a digital display using the supplied width value ''' print() horizontal_line(width) vertical_line(0, 1) horizontal_line(width) two_vertical_lines (width, 1) horizontal_line(width) print() def number_7 (width): ''' prints the number 7 as it would appear on a digital display using the supplied width value ''' print() horizontal_line(width) vertical_line(width, 4) print() def number_8 (width): ''' prints the number 8 as it would appear on a digital display using the supplied width value ''' print() horizontal_line(width) two_vertical_lines (width, 1) horizontal_line(width) two_vertical_lines (width, 1) horizontal_line(width) print() def number_9 (width): ''' prints the number 9 as it would appear on a digital display using the supplied width value ''' print() horizontal_line(width) two_vertical_lines (width, 1) horizontal_line(width) vertical_line(width, 2) print() #----------------------------------------------------------------------# #operators module def addition (width): ''' prints the addition symbol as it would appear on a digital display using the supplied width value ''' print() vertical_line(int(width)//2 + 1 , 2) horizontal_line(width) vertical_line(int(width)//2 + 1, 2) print() def subtraction (width): ''' prints the subtraction symbol as it would appear on a digital display using the supplied width value ''' print() horizontal_line(width) print() #----------------------------------------------------------------------# #check answers module def check_answer(number1,number2,answer,operator): '''processing: determines if the supplied expression is correct.''' expression = True if operator == "+": a = number1 + number2 if answer == a: expression = True elif answer != a: expression = False elif operator == "-": a = number1 - number2 if answer == a: expression = True elif answer != a: expression = False return expression
dad3c01797dcfdea61b05d6c984d722043bafb29
PyStudyGroup/clases
/Unidad 2/Desafios/Sem2Des1_KelvinProvincia.py
686
4.28125
4
#! /usr/bin/env python #version de python 3 #obtener numero decimal a partir de un numero binario def getDecimal( binario ): contador = 0 acumulador = 0 #invertimos el binario: 110 -> 011 binarioInvertido = "" for i in binario: binarioInvertido = i + binarioInvertido #trabajamos con el binario invertido for i in binarioInvertido: acumulador += ( int(i) * ( 2 ** contador ) ) contador += 1 return acumulador def convertirBinarioADecimal(): binario = input("Dame un binario: "); #llmamos a la funcion que nos devuelve el numero en sistema decimal print( getDecimal(binario) ) convertirBinarioADecimal();
c1f6e2d38b920a9f052479ad26af08ec44ea06cb
Kso-ai/school
/initDev/td2.2.3.py
1,411
3.875
4
from math import e def methode_1(): x = -1 while x != 0: while x < 0: x = int(input("Entrez une valeur: ")) if x > 0: a = int(x) for i in range(1, 101): a = 0.5 * (a + x/a) print(f"La racine carrée de {x} est {a}.") def methode_2(): '''J'ai pas réellement compris l'intérêt ni le fonctionnement de cette fonction mais bon...''' x = int(input("Entrez une valeur: ")) while x < 0: x = int(input("Entrez une valeur: ")) if x != 0: a = int(x) for i in range(1, 101): a = 0.5 * (a + x/a) print(f"La racine carrée de {x} est {a}.") while x != 0: x = int(input("Entrez une valeur: ")) while x < 0: x = int(input("Entrez une valeur: ")) if x != 0: a = int(x) for i in range(1, 101): a = 0.5 * (a + x/a) print(f"La racine carrée de {x} est {a}.") def methode_3(): tol = 1 * e - 2 x = -1 while x < 0: x = int(input("Entrez une valeur: ")) if x > 0: a = int(x) aprev = a - (tol + 1) while abs(a - aprev) > tol: aprev = a a = 0.5 * (a + x/a) print(f"La racine carrée de {x} est {a}.") def main(): # methode_1() # methode_2() methode_3() return if __name__ == "__main__": main()
b9db59fd650648fb101bb6b082ff29d7c362136a
udaraweerasinghege/ADT-methods
/LinkedListRec/Non-mutating/4suml.py
267
3.671875
4
from linkedlistrec import LinkedListRec, EmptyValue def sum(L): if L.first is EmptyValue: return 0 else: return L.first + sum(L.rest) test = LinkedListRec([0]) print(sum(test) == 0) test1 = LinkedListRec([0,1,2,3,4]) print(sum(test1) == 10)
5f79d35de2b7d43ab1259232d5bdce9e1981bad4
haominhe/Undergraduate
/CIS210 Computer Science I/Projects/p6/grid.py
6,423
4.03125
4
""" Grid display. Displays a rectangular grid of cells, organized in rows and columns with row 0 at the top and growing down, column 0 at the left and growing to the right. A sequence of unique colors for cells can be chosen from a color wheel, in addition to colors 'black' and 'white' which do not appear in the color wheel. Michal Young ([email protected]), October 2012, for CIS 210 at University of Oregon Uses the simple graphics module provided by Zelle, which in turn is built on the Tk graphics package (and which should therefore be available on all major Python platforms, including Linux, Mac, and all flavors of Windows at least back to XP). """ from graphics import * # Zelle's simple OO graphics global win # The window we are drawing the grid in global cell_width, cell_height # The size of a cell in the grid global color_wheel color_wheel = [ color_rgb(255,0,0), color_rgb(0,255,0), color_rgb(0,0,255), color_rgb(255,255,0), color_rgb(255,0,255), color_rgb(0,255,255), color_rgb(127,255,0), color_rgb(0,127,255), color_rgb(127,0,255), color_rgb(255,127,0), color_rgb(0,255,127), color_rgb(255,0,127), color_rgb(127,127,0), color_rgb(127,0,127), color_rgb(0,127,127), color_rgb(255,255,127), color_rgb(255,127,255), color_rgb(127,255,255) ] global cur_color cur_color = 0 global black, white, red, green, blue black = color_rgb(0,0,0) white = color_rgb(255,255,255) red = color_rgb(200,0,0) green = color_rgb(0,200,0) blue = color_rgb(0,0,200) global nrows nrows = 1 def make( rows, cols, width, height ) : """Create the grid display, initially all white. rows, cols are the grid size in rows and columns. width, height are the window size in pixels. Args: rows: number of rows of cells in the grid (vertical divisions) cols: number of columns of cells in the grid (horizontal divisions) width: horizontal width of window in pixels height: vertical height of window in pixels Returns: nothing """ global win, cell_width, cell_height, nrows win = GraphWin("Grid", width, height ) win.setCoords(0, 0, rows, cols) bkgrnd = Rectangle( Point(0,0), Point(width,height) ) bkgrnd.setFill( color_rgb(255,255,255) ) # White background cell_width = width / cols cell_height = height / rows nrows = rows def get_cur_color(): """Return the currently chosen color in the color wheel. The color wheel is a list of colors selected to be contrast with each other. The first few entries are bright primary colors; as we cycle through the color wheel, contrast becomes less, but colors should remain distinct to those with normal color vision until the color wheel cycles all the way around in 18 choices and starts recycling previously used colors. The color wheel starts out in position 0, so get_cur_color() may be called before get_next_color() has been called. Args: none Returns: a 'color' that can be passed to fill_cell FIXME: The color wheel should produce colors of contrasting brightness as well as hue, to maximize distinctness for dichromats (people with "color blindness". Maybe generating a good color wheel can be part of a project later in CIS 210. (This is not a required or expected change for the week 4 project.) """ return color_wheel[cur_color] def get_next_color(): """Advance the color wheel, returning the next available color. The color wheel is a list of colors selected to be contrast with each other. The first few entries are bright primary colors; as we cycle through the color wheel, contrast becomes less, but colors should remain distinct to those with normal color vision until the color wheel cycles all the way around in 18 choices and starts recycling previously used colors. Args: none Returns: a 'color' that can be passed to fill_cell """ global cur_color cur_color += 1 if cur_color >= len(color_wheel) : cur_color = 0 return color_wheel[cur_color] def fill_cell(row, col, color): """Fill cell[row,col] with color. Args: row: which row the selected cell is in. Row 0 is the top row, row 1 is the next row down, etc. Row should be between 0 and one less than the number of rows in the grid. col: which column the selected cell is in. Column 0 is the leftmost row, column 1 is the next row to the right, etc. Col should be between 0 and one less than the number of columns in the grid. color: What color to fill fill the selecte cell with. Valid colors include grid.white, grid.black, and values returned by grid.get_next_color() and grid.get_cur_color() """ global nrows, win left = col right = col + 1 top = nrows - (row + 1) bottom = nrows - row mark = Rectangle( Point(left,bottom), Point(right,top) ) mark.setFill(color) mark.draw(win) def label_cell(row, col, text, color=black): """Place text label on cell[row,col]. Args: row: which row the selected cell is in. Row 0 is the top row, row 1 is the next row down, etc. Row should be between 0 and one less than the number of rows in the grid. col: which column the selected cell is in. Column 0 is the leftmost row, column 1 is the next row to the right, etc. Col should be between 0 and one less than the number of columns in the grid. text: string (usually one character) to label the cell with color: Color of text label """ global nrows, win xcenter = col + 0.5 ycenter = nrows - (row + 1) + 0.5 label = Text( Point(xcenter, ycenter), text) label.setFace("helvetica") label.setSize(20) ## Is there a better way to choose text size? label.setFill(color) label.draw(win) def wait() : """ Hold the display window open until the user clicks on it. After finishing a drawing, call "grid.wait()" to display it. The display will close when the user clicks on the grid display with the mouse. Args: none Returns: nothing """ global win win.getMouse() win.close()
daa830c71d61d18ddd464c6de80395ecef6e7e90
kr0t/ya_algo
/combination.py
456
3.78125
4
NUMBERS = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } def combination(numbers: str, s: str, length: int, idx: int) -> str: if length == 0: print(s, end=' ') else: for symbol in NUMBERS[numbers[idx]]: combination(numbers, s + symbol, length - 1, idx + 1) if __name__ == '__main__': combination('23456', '', len('23456'), 0)
caba112b6f4e703fe30d1254cf36502782353bab
MelihCelik00/GEO106E
/geo106e_lab projeler/LabWork13/resection.py
3,541
4.21875
4
# -*- coding: utf-8 -*- """ Created on Tue May 08 14:12:43 2018 @author: isiler """ import math x1 = float(input("ENTER THE X COORDINATES OF KNOWN POINT P1: ")) y1 = float(input("ENTER THE Y COORDINATES OF KNOWN POINT P1: ")) x2 = float(input("ENTER THE X COORDINATES OF KNOWN POINT P2: ")) y2 = float(input("ENTER THE Y COORDINATES OF KNOWN POINT P2: ")) dist1 = float(input("ENTER THE MEASURED HORIZONTAL DISTANCE IN METER UNIT FROM UNKNOWN POINTS A TO P1:")) dist2 = float(input("ENTER THE MEASURED HORIZONTAL DISTANCE IN METER UNIT FROM UNKNOWN POINTS A TO P2:")) beta = float(input("ENTER THE MEASURED HORIZONTAL ANGLE IN GRAD UNIT AT UNKNOWN POINTS A:")) # CALCULATE THE AZIMUTH VALUE FROM KNOWN POINT P1 TO KNOWN POINT P2 # azimuth: açıklık açısı if x1 == x2 and y1>y2: azimuth = 300 elif x1==x2 and y1<y2: azimuth = 100 elif y1==y2 and x1>x2: azimuth = 200 elif y1==y2 and x1<x2: azimuth=0 else: azimuth=(math.atan(abs(y2-y1)/abs(x2-x1))*200/math.pi) #1. Quadrant if (y2 - y1)>0 and (x2-x1)>0: azimuth = azimuth #2. Quadrant elif (y2-y1)>0 and (x2-x1)<0: azimuth = 200 - azimuth #3.Quadrant elif (y2-y1)<0 and (x2-x1)<0: azimuth = 200 + azimuth #4.Quadrant elif (y2-y1)<0 and (x2-x1)>0: azimuth = 400 - azimuth print("Azimuth from P1 to P2:",format(azimuth,'.4f'),"grad") # dist 3 is the horizontal distance from P1 to P2. dist3 = math.sqrt((x2-x1)**2+(y2-y1)**2) print("Horizontal distance from P1 to P2:",format(dist3,'.2f'),"meter") # CALCULATE THE INTERIOR ANGLES AT P1 AND P2 # USE THE SINUS THEOREM FOR P1 P2 A # alfa for P2 and teta for P1 alfa = math.asin((dist1*math.sin(beta*(math.pi/200)))/dist3) #convert alfa to grad unıt alfa = alfa * (200/math.pi) print("alfa:",format(alfa,'.4f'),"grad") teta = math.asin((dist2*math.sin(beta*(math.pi/200)))/dist3) # convert to teta in grad unit teta = teta * (200/math.pi) print("teta:",format(teta,'.4f'),"grad") #check the total interior angle total_angle = beta+teta+alfa total_angle=float(format(total_angle,".4f")) if total_angle ==200: print (" Total İnterior Angle is 200 grad","OK") else: print ("Check the Angles") # CALCULATE THE AZIMUTH FROM P1 TO A azimuth2 = azimuth + teta if azimuth2>400: azimuth2= azimuth2-400 print ("Azimuth from P1 to A:",format(azimuth2,'.4f'),"grad") #CALCULATE THE COORDINATES OF POINT A xA1 = x1 + dist1*math.cos(azimuth2*math.pi/200) yA1 = y1 + dist1*math.sin(azimuth2*math.pi/200) print("Coordinates of A:","X:",format(xA1,'.2f'),"meter","Y:",format(yA1,'.2f'),"meter") #Control of coordinates of point A #Calculate the corrdinate of point A from starting point P2 #At first calculate the azimuth from P2 to P1 if azimuth < 200: azimuth3 = azimuth+200 elif azimuth >200: azimuth3 = azimuth-200 print("Azimuth from P2 to P1:",format(azimuth3,'.4f'),"grad") #CALCULATE THE AZIMUTH FROM P2 TO A azimuth4 = azimuth3 - alfa if azimuth4>400: azimuth4= azimuth3-400 print("Azimuth from P2 to A:", format(azimuth4,'.4f'),"grad") #CALCULATE THE COORDINATES OF POINT A xA2= x2 + dist2*math.cos(azimuth4*math.pi/200) yA2 = y2 + dist2*math.sin(azimuth4*math.pi/200) print("Control of Coordinates of Point A") print("Coordinates of A:","X:",format(xA2,'.2f'),"Y:",format(yA2,'.2f'),"meter") """ sample input: x1:1000 y1:1000 x2:1008 y2:1006 dist1:6 dist2:8 beta:100 grad """
4c418fd67a626f395eb5141b4158a71214b7466c
ibirdman/PythonLearning
/linear_regression.py
1,379
3.71875
4
import numpy as np W = [0.3, 0.1, 0.2] # 线性参数列表 (W[0] is bias) DIM = len(W) - 1 # 属性数量 # sample point count for training. m = 30 x_data = np.float32(np.random.rand(m, DIM)) # 随机输入 w_data = np.array(W[1:]).reshape(DIM, 1) y_data = np.dot(x_data, w_data) + W[0] # print(x_data) # print(y_data) # Points x-coordinate and dummy value (x0, x1). X = np.hstack((np.ones((m, 1)), x_data)).reshape(m, DIM + 1) # Points y-coordinate y = y_data.reshape(m, 1) # The Learning Rate alpha. alpha = 0.5 def error_function(theta, X, y): '''Error function J definition.''' diff = np.dot(X, theta) - y return (1./2*m) * np.dot(np.transpose(diff), diff) def gradient_function(theta, X, y): '''Gradient of the function J definition.''' diff = np.dot(X, theta) - y return (1./m) * np.dot(np.transpose(X), diff) def gradient_descent(X, y, alpha): '''Perform gradient descent.''' theta = np.ones((DIM + 1, 1)) gradient = gradient_function(theta, X, y) count = 0 while not np.all(np.absolute(gradient) <= 1e-6): theta = theta - alpha * gradient gradient = gradient_function(theta, X, y) count = count + 1 print("loop=" + str(count)) return theta optimal = gradient_descent(X, y, alpha) print('optimal:\n', optimal) print('error function:', error_function(optimal, X, y)[0,0])
b70018e815ec7178c40ab088582788e3456746ea
jeffreytjs/100DayOfCode
/condition_and_loop/construct_number_pattern.py
375
4.0625
4
# Day 10 - Problem 13 # Challenge # Write a Python program to construct the following pattern, # using a nested loop number. # Example # 1 # 22 # 333 # 4444 # 55555 # 666666 # 7777777 # 88888888 # 999999999 def num_pattern(n): """ Print a pattern as above with a loop. :params n: """ for i in range(n + 1): print(str(i) * i) num_pattern(9)
e3782f893ba68dd5e196a68e66ec014033d6ebf7
ramanaditya/beginners
/python/bmi_calculator.py
619
4.5
4
# getting input from the user and assigning it to user height = float(input("Enter height in meters: ")) weight = float(input("Enter weight in kg: ")) # the formula for calculating bmi bmi = weight/(height**2) # ** is the power of operator i.e height*height in this case print("Your BMI is: {0} and you are: ".format(bmi), end='') #conditions if ( bmi < 16): print("severely underweight") elif ( bmi >= 16 and bmi < 18.5): print("underweight") elif ( bmi >= 18.5 and bmi < 25): print("Healthy") elif ( bmi >= 25 and bmi < 30): print("overweight") elif ( bmi >=30): print("severely overweight")
9b762ae8abcf5d4c14d94c4677519b52827996f8
hyu-likelion/Y1K3
/week1/hyungeun/0-1/2908.py
119
3.671875
4
a, b = input().split() num1 = int(a[::-1]) num2 = int(b[::-1]) if num1 > num2: print(num1) else: print(num2)
9615920dca520c085b93739cc2a1fe54d305ad19
varun1414/Xformations
/Scrappers/to_csv.py
467
3.625
4
import csv def convert(data,name): csv_columns = ['comp','date','result','teams','score','formation'] dict_data = data csv_file = name try: with open(csv_file, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() for data in dict_data: writer.writerow(data) except IOError: print("I/O error")
665430b853fbdc5a616d8036cd3a20bc6a8e8738
ballaneypranav/ucsd-dsa
/1-algo-toolbox/2-algorithmic-warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.py
1,475
3.609375
4
# Uses python3 import sys def fibonacci_partial_Sum(from_, to): period = -1 fibListMod = [0, 1] if from_ < 2 and to >= 1 : Sum = 1 else: Sum = 0 for i in range(2, to+1): fibListMod.append((fibListMod[i-1] + fibListMod[i-2]) % 10) if fibListMod[i] == 1 and fibListMod[i-1] == 0: period = i-1 break if i >= from_: Sum = (Sum + fibListMod[i]) % 10 if period == -1: return Sum Sum_all = sum(fibListMod) - 1 quotient1 = from_ // period remainder1 = from_ % period quotient2 = to // period remainder2 = to % period if quotient1 == quotient2: for i in range(remainder1, remainder2+1): Sum = (Sum + fibListMod[i]) % 10 else: for i in range(remainder1, period +1): Sum = (Sum + fibListMod[i]) % 10 if quotient2 != quotient1 + 1: Sum = (Sum + (Sum_all * (quotient2 - quotient1 - 1))) % 10 for i in range(1, remainder2+1): Sum = (Sum + fibListMod[i]) % 10 return Sum def fibonacci_partial_Sum_naive(from_, to): Sum = 0 current = 0 next = 1 for i in range(to + 1): if i >= from_: Sum = (Sum + (current % 10)) % 10 current, next = next, current + next return Sum % 10 if __name__ == '__main__': from_, to = map(int, input().split()) print(fibonacci_partial_Sum(from_, to))
153290c7fc7494fb260a1601a6e9ac87ac70bdb6
niteenmore/python-npci-assignments
/AtmTransaction.py
1,215
3.53125
4
fixedCash=60000 userbalnce=70000 n=3 lst=[] def main(): print("Total amount in ATM :",fixedCash) print("Total amount in your account",userbalnce) amount=int(input("How much amount you want to withdraw ?")) def withdraw(amount): global fixedCash global userbalnce global n if(amount>userbalnce or amount>(90*fixedCash)/100): print("Insufficient balance") else: n=n-1 userbalnce=userbalnce-amount fixedCash=fixedCash-amount lst.append(amount) print(amount,"debited from your account") if(n!=0): print("You can do ",n," more transations") amount=int(input("How much amount you want to withdraw ?")) withdraw(amount) else: i=input("Do you want to see your last 3 transaction and Total balance, Y|N ? ") if(i=="Y"): print("Balnace amount :",userbalnce) for i in range(0,3): print("Transaction ",i+1 ,"is", lst[i]) withdraw(amount) main()
884e411f308b4f9d157054cac4310d94d04cb6d9
karbekk/Python_Data_Structures
/Interview/DSA/Array/max_sum_subarray.py
354
3.6875
4
def max_sub_array(my_array): max_sum = 0 max_now = 0 for i in range(0,len(my_array)): max_now = max_now + my_array[i] if max_now < 0: max_now = 0 elif max_now > max_sum: max_sum = max_now if max_sum <= 0: return 5 return max_sum print max_sub_array(my_array=[-2, -3,10,2])