blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
ebae530067112644455692feaf151a8c0811de5d
yiliang-Liu/LinkedIn-Automatically-Send-Invite
/LinkedIn Automatically Send Invite.py
2,278
3.5
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 11 01:01:25 2018 @author: yl_33 """ from selenium import webdriver # Change the information in the below dictionary Info = { # Your account info 'username': 'XXX', 'password': 'XXX', # the homepage link of the person you want to add 'target_link': 'https://www.linkedin.com/in/XXX', } # The invitation text you want to send, No more than 300 words invite_text = "XXX" def LinkedIn_Add_Connect(Info, invite_text): """ func: automatically add people and send invitation text """ # the path of chromedriver chromedriver = 'path' # Open LinkedIn url = 'https://www.linkedin.com' browser = webdriver.Chrome(chromedriver) browser.get(url) # Sing in LinkedIn username_field = browser.find_element_by_id('login-email') password_field = browser.find_element_by_id("login-password") username = Info.get('username') password = Info.get('password') username_field.send_keys(username) browser.implicitly_wait(1) password_field.send_keys(password) browser.implicitly_wait(1) # Click for sign in browser.find_element_by_id('login-submit').click() # Check tab title print("Tag title: " + browser.title) # Open new page browser.execute_script("window.open('{}', 'new_window')".format(Info.get('target_link'))) # Switch to the new page # https://stackoverflow.com/questions/37088589/selenium-wont-open-a-new-url-in-a-new-tab-python-chrome browser.switch_to.window(browser.window_handles[1]) # Check title print("Tag title: " + browser.title) # Click Connect browser.find_element_by_class_name('pv-s-profile-actions').click() # Click add note browser.find_element_by_class_name('send-invite__actions').click() invite_field = browser.find_element_by_id('custom-message') # Write message invite_field.send_keys(invite_text) # Click send message button browser.find_element_by_css_selector('.button-primary-large.ml1').click() # Quick browser.quit() print('Success!') if __name__ == "__main__": LinkedIn_Add_Connect(Info, invite_text)
339a9997e6ae6797efee64918cb3c381ab24a389
tanmaybanga/Carleton-University
/COMP-1405/Tutorials/Tutorial3/Task1.py
370
4.125
4
# This Will Save Our Input Varibles FirstName = input("Please Enter Your First Name ") YearBorn = int(input("Please Enter Your Year Born ")) #Taking The Sum Of Current Year - YearBord #Creating the "Inbetween Age" Sum1 = (2016 - YearBorn) Sum2 = Sum1 - 1 #Printing Our Final Values print ("Your Name Is", FirstName, "Your Current Age Is Between", Sum1, "And", Sum2)
c1fbde2ffc136c50e993b144ca2cb8fc78866417
bespokeeagle/Cousera-Python-re-up
/strings.py
528
3.90625
4
# Write code using find() and string slicing to extract the number at the end of the line below. # Convert the extracted value to a floating point number and print it out. text = "X-DSPAM-Confidence: 0.8475 " # code to find the position/index of the semicolon in text and save to colonpos colonpos = text.find(":") # code to slice text starting from the index after the colon numpos = text[colonpos+1:] #code to strip the whitespaces the number string to floating point fnum = float( (numpos.strip())) print (fnum)
e59a1d19c8dfeaedb63c0caa98dceb4605520236
JoshuaStanley308/CP1404_Practicals1
/prac_05/word_counter.py
384
4
4
words_collection = {} text = input("Text: ") words = text.split() for word in words: try: words_collection[word] += 1 except KeyError: words_collection[word] = 1 word_list = list(words_collection) word_list.sort() max_length = max(len(word) for word in words) for word in word_list: print("{:{}}: {}".format(word,max_length, words_collection[word]))
2a5f833640dbf300f4dafb845b43f5c6d3448a4b
rahuladream/ElementsofProgramming
/String/rangoli.py
633
3.671875
4
""" create rangoli """ import string def print_rangoli(size): start_range = 97 end_range = 123 looking_characters = chr(start_range+size) mid = size - 1 for i in range(size-1, 0, -1): row = ['-'] * (2 * size - 1) for j in range(size - i): row[mid - j] = row[mid + j] = chr(start_range+j+i) print('-'.join(row)) for i in range(0, size): row = ['-'] * (2 * size - 1) for j in range(0, size - i): row[mid - j] = row[mid + j] = chr(start_range+j+i) print('-'.join(row)) if __name__ == '__main__': n = int(input()) print_rangoli(n)
d918cefed9dafc9f91543f22f4da17c66dda130f
chanyoonzhu/leetcode-python
/1218-Longest_Arithmetic_Subsequence_of_Given_Difference.py
2,635
3.515625
4
""" - dynamic programming - dp(i) - Longest Arithmetic Subsequence of Given Difference ending at index i (i needs to be included) - O(n^2), O(n) """ class Solution: def longestSubsequence(self, arr: list[int], difference: int) -> int: @lru_cache(None) def dp(i): if i < 0: return 0 count = 1 for k in range(i-1, -1, -1): if arr[k] + difference == arr[i]: count += dp(k) break # greedily match the first satisfying return count return max(dp(i) for i in range(len(arr))) """ - dynamic programming (buttom-up) - dp(i) - Longest Arithmetic Subsequence of Given Difference ending at index i (i needs to be included) - O(n^2), O(n) """ class Solution: def longestSubsequence(self, arr: List[int], difference: int) -> int: dp = defaultdict(lambda: defaultdict(int)) #dp[x][idx] = length res = 0 for idx, x in enumerate(arr): dp[x][idx] = max([dp[x-difference][idx2] for idx2 in dp[x-difference]], default = 0) + 1 res = max(res, dp[x][idx]) return res """ - dynamic programming (buttom-up) - O(n), O(n) """ class Solution: def longestSubsequence(self, arr: list[int], difference: int) -> int: dp = [1] * len(arr) number_last_pos = {} res = 1 for i, x in enumerate(arr): if x - difference in number_last_pos: dp[i] = dp[number_last_pos[x - difference]] + 1 res = max(res, dp[i]) number_last_pos[x] = i return res """ - hashmap - O(n), O(n) """ class Solution: def longestSubsequence(self, arr: list[int], difference: int) -> int: memo = {} for x in arr: memo[x] = memo[x-difference] + 1 if x-difference in memo else 1 return max(memo.values()) """ - follow-up: difference can be from 1 to difference (where difference > 0) """ class SolutionFollowUp: def longestSubsequence(self, arr: list[int], difference: int) -> int: dp = [1] * len(arr) number_last_pos = {} res = 1 for i, x in enumerate(arr): for diff in range(1, difference + 1): if x - diff in number_last_pos: dp[i] = max(dp[i], dp[number_last_pos[x - diff]] + 1) res = max(res, dp[i]) number_last_pos[x] = i return res s = SolutionFollowUp() print(s.longestSubsequence([3, 1, 2, 5, 8, 13, 10], 3)) # 5 => [1, 2, 5, 8, 10]
a722746d991d956a92cf476cabb5046f27e8dfbb
kristamp/article
/venv/vocabulary.py
3,158
3.734375
4
visited=[] class Word: def __init__(self, word, position): self.word=word self.positions=[position] def add_position(self, position): self.positions.extend(position) def __str__(self): return self.word class Digraph(object): """Represents a directed graph of Node and Edge objects""" def __init__(self): self.nodes = set([]) self.edges = {} # must be a dict of Node -> list of edges def __str__(self): edge_strings = [] for edges in self.edges.values(): for edge in edges: edge_strings.append(str(edge)) edge_strings = sorted(edge_strings) # sort alphabetically return '\n'.join(edge_strings) # concat edge_strings with "\n"s between them def get_edges_for_node(self, node): return self.edges[node] def has_node(self, node): return node in self.nodes def add_node(self, word): new_word=self.find(word) if new_word: new_word.add_position(word.positions) return (new_word) else: self.nodes.add(word) return (word) def add_edge(self, edge): """Adds an Edge or WeightedEdge instance to the Digraph. Raises a ValueError if either of the nodes associated with the edge is not in the graph.""" if edge.src not in self.nodes: self.add_node(edge.src) if edge.dest not in self.nodes: self.add_node(edge.dest) if edge.src not in self.edges.keys(): self.edges[edge.src]=[edge] else: self.edges[edge.src].append(edge) def find (self, word): for test in self.nodes: if word.word==test.word: return (test) return (None) def find_word(self,str): for test in self.nodes: if str == test.word: return test return None def find_min_distance (self, start_node, end_node, depth, min_depth) global visited if min_depth if depth>min_depth: return min_depth if depth>59: return none visited.append(start_mode) edges = self.get_edges_for_node(start_node) for edge in edges: if edge.depth==end.node: return depth for edge in edges: if edge not in visited: end_depth=self.find_min_distance(edge.dest, end_node, depth, min_depth) if end_depth and (not min_depth or end_depth < min_depth): min_depth=end_depth return min_depth def find_distance(self, start, end): start_node = self.find_word(start) end_node = self.find_word(end) if not start_node or end_node: raise ValueError return self.find_min_distance(start_node, end_node, 1, None) class Edge(object): """Represents an edge in the dictionary. Includes a source and a destination.""" def __init__(self, src, dest): self.src = src self.dest = dest def get_source(self): return self.src def get_destination(self): return self.dest def __str__(self): return f'{self.src}->{self.dest}'
fca5acdb7f03452636c043c61d95e5c76ad96faf
Tlwhisper/yympyLevel0110
/01_xiao_jia_yu/028_file.py
458
3.53125
4
# 文件操作 #f = open('/home/yym/python_code/yympyLevel0110/README.md') f = open('./README.md') tem = f.read() #print(tem) # seek(offset, from) # from 0:开头。 1 当前位置。2:代表文件末尾。 tem2 = f.read() # 读不到东西, print(tem2) print(f.tell()) f.seek(0,0) print(f.tell()) print(f.readline()) # 打印读出来的一行 tem3 = f.read() print(tem3) # 迭代每一行读取 f.seek(0,0) for each_line in f: print(each_line)
8ee2c02f223d658f855bf21ab7d45651173c6d79
Owl-jun/studyAlgorithm
/onetosix.py
272
3.9375
4
# 주사위 시뮬레이터 import random coin = False print('please insert coin.') ic = input('coin 을 입력하시면 코인이 충전됩니다.') if ic.lower() == 'coin': coin = True if coin: result = random.randint(1,6) print(f'result = {result}')
77ba141ef63795ab2a51f9e457d53086c2f214a7
DannyShien/DC-python-exercise
/odd_num.py
160
4.0625
4
# Print each odd number between 1 and 10. STOP = 10 counter = 0 while counter <= STOP: if (counter % 2 != 0): print(counter) counter = counter + 1
4e41e830b93e46054422c52c23e84114035f4631
benbdon/Python_Practice
/greetings/greetings.py
200
3.625
4
# Chap 2 Flow Control: greetings.py raw_input = input('Give me some input\n') spam = int(raw_input) if spam == 1: print('Hello') elif spam == 2: print('Howdy') else: print('Greetings!')
76da365ec70518e419e6f6b812910e4c7283438d
tvanderplas/project-euler-python
/Challenges/functions.py
3,818
3.796875
4
from decimal import getcontext, Decimal from math import sqrt def fibonacci(n: int, precision: int = 1000): getcontext().prec = precision phi = Decimal((1 + sqrt(5)) / 2) f = (phi ** n - (-phi) ** -n) / (2 * phi - 1) return int(f) def fibonacci_generator(x): """generates list of fibonacci numbers under x""" numbers = [1, 1] while numbers[-1] + numbers[-2] < int(x): numbers.append(numbers[-1] + numbers[-2]) return numbers def get_primes(limit: int = 1000000): if limit < 2: return [] _primes = [2] for number in range(max(_primes), limit + 1): for prime in _primes: if number % prime == 0: break elif number % prime != 0 and prime >= sqrt(number): _primes.append(number) break return _primes def get_prime_factors(x: int, _answer: list = [], _primes: list = []): if len(_primes) == 0: _answer.clear() _primes = get_primes(int(sqrt(x) if x > 4 else x)) for p in _primes: if x % p == 0 and x != p: _answer.append(p) return get_prime_factors(x // p, _answer, _primes) elif p == _primes[-1]: _answer.append(x) return _answer return _answer def collatz(n: int): """returns chain length of collatz sequence""" chains = dict() for x in range(1, n): chain = 1 p = x while x > 1: if x % 2 == 0: x //= 2 if x in chains: chain += chains[x] - 1 x = 1 else: x *= 3; x += 1 chain += 1 chains.update({p: chain}) return chains def catalan(x: int): pascal = [1, 1] for _ in range(x * 2 - 1): pascal = [pascal[i] + pascal[i + 1] for i, v in enumerate(pascal) if i != len(pascal) - 1] pascal.append(1) pascal.insert(0, 1) return pascal[len(pascal) // 2] def count_letters(x: int): """returns number of letters for integers up to 1000""" map_ones = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4] map_tens = [0, 4, 6, 6, 5, 5, 5, 7, 6, 6] digits = [int(d) for d in str(x)[::-1]] if len(digits) > 3: digits[3] = map_ones[digits[3]] + 8 if len(digits) > 2 and digits[2] != 0: if digits[:2] == [0, 0]: digits[2] = map_ones[digits[2]] + 7 else: digits[2] = map_ones[digits[2]] + 10 if len(digits) > 1: if digits[:2] in [[0, 1], [1, 1], [2, 1], [3, 1], [5, 1], [8, 1]]: digits[1] = 3 else: digits[1] = map_tens[digits[1]] digits[0] = map_ones[digits[0]] return sum(digits) def max_path(triangle: list): for i, row in enumerate(triangle[1:]): for ii in range(1, len(row) + 1): if 0 < ii < len(row) - 1: triangle[i + 1][ii] += max(triangle[i][ii - 1:ii + 1]) elif ii == 0: triangle[i + 1][ii] += triangle[i][ii] elif ii == len(row) - 1: triangle[i + 1][ii] += triangle[i][ii - 1] return max(triangle[-1]) def is_leap_year(year: int): if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False return True else: return False def days_in_month(month: int = 4, year: int = 1900): num_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] num_days_ly = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] return num_days[month] if not is_leap_year(year) else num_days_ly[month] def factorial(x: int): if x > 0: x *= factorial(x - 1) return x else: return 1 def divisors(x: int): if x > 1: answer = [1] for n in range(2, int(sqrt(x)) + 1): if x % n == 0: answer.extend([n, x // n]) return [x for x in sorted(set(answer))] else: return [x for x in []] def permutations(word: str): if len(word) < 2: return [word] base = word[:2] answer = [] answer.extend([base, base[::-1]]) next_answer = [] for x in range(2, len(word)): for item in answer: for n in range(len(item) + 1): an_item = list(item) an_item.insert(n, word[x]) next_answer.append(''.join([x for x in an_item])) answer.clear() answer.extend(next_answer) next_answer.clear() answer.sort() return answer
c1e43a0e158a742218993b39556670e1e9367e30
john-brown-bjss/advent-of-code
/2020/day 1/solution.py
745
3.890625
4
import os from itertools import combinations from math import prod def sanitise_input(input): return int(input.replace('/n', '')) def get_sum_of_multiples(x): path = os.path.join(os.path.dirname(__file__), 'inputs.txt') with open(path, 'r') as file_handle: data = file_handle.readlines() all_combinations = combinations(data, x) for multiples in all_combinations: santised_multiples = [sanitise_input(multiple) for multiple in multiples] if sum(santised_multiples) == 2020: return prod(santised_multiples) if __name__ == "__main__": part_1 = get_sum_of_multiples(2) part_2 = get_sum_of_multiples(3) print(f'Part 1: {part_1}\nPart 2: {part_2}')
8707d39996d832a07189903a68628d05a5651242
Casera-Meow/PAT-PRACTICE
/Baisc Level/Python3/B1001.py
281
3.546875
4
# This Problem is about Callatz Guest guestNum = eval(input()) paces = 0 # The number of steps in while loop while guestNum > 1: if guestNum % 2 == 0: guestNum /= 2 paces += 1 else: guestNum = (guestNum * 3 + 1) / 2 paces += 1 print(paces)
7b5d95ca219944c91718a78bc824bbdfd0bcd62d
shashanknayak/py-learn
/sort/selection-sort.py
456
3.71875
4
def main(): inp = [4,3,1,-1,9,16,7] print "Unsorted List: ", inp sort(inp) def sort(inp): count = len(inp) for i in range(0,count-1): min_ele = inp[i] min_ind = i for j in range(i+1, count): if min_ele>inp[j]: min_ele = inp[j] min_ind = j tmp = inp[i] inp[i] = inp[min_ind] inp[min_ind] = tmp print "run #"+str(i+1)+": ", inp print "Sorted List: ", inp if __name__ == "__main__": main()
f1f999bff3beffa014e672859015050afb2daad6
MrHamdulay/csc3-capstone
/examples/data/Assignment_4/ncbden001/ndom.py
1,154
3.59375
4
import ndom def ndom_to_decimal (a): string = str(a) a= 1 while a < len(string): if len(string)== 4: converter =(int(string[0])*216) + (int(string[1])*36)+(int(string[2])*6)+(int(string[3])*1) a+=1 elif len(string) == 3: converter =((int(string[0])*36)+(int(string[1])*6)+(int(string[2])*1)) a+=1 elif len(string) == 2: converter =((int(string[0])*6)+(int(string[1])*1)) a+=1 elif len(string) == 1: converter =((int(string[0])*1)) a+=1 return converter def decimal_to_ndom(a): calculator = a string = "" while calculator >0 : lastdigit= calculator%6 calculator= calculator//6 string += str(lastdigit) return int(string[::-1]) def ndom_add (a, b): number1 = ndom.ndom_to_decimal(a) number2 = ndom.ndom_to_decimal(b) decimal = number1 + number2 value = ndom.decimal_to_ndom(decimal) return value def ndom_multiply (a, b): number1 = ndom.ndom_to_decimal(a) number2 = ndom.ndom_to_decimal(b) decimal = number1 * number2 value = ndom.decimal_to_ndom(decimal) return value
570d4a812dceb013d981b508d0e13f3c8c96113b
sinking8/Python-Problems
/fibowords.py
1,288
4.40625
4
''' Fibonacci Words The program must accept the integer N as the input. The program must print the first N Fibonacci words formed by repeating them in the same way as generating Fibonacci Numbers. The first term and the second term of the Fibonacci words is ‘a’ and ‘b’. INPUT: Input contains N which denotes the number of Fibonacci terms. OUTPUT: Display N Fibonacci Terms separated by a space. CONSTRAINTS: 1 <= N <= 25 SAMPLE INPUT: 6 SAMPLE OUTPUT: A ab ba bab babba babbabab EXPLANATION: Here N = 6 and first two terms in the Fibonacci words are ‘a’ and ‘b’. The 3rd term in the Fibonacci words is ba (“b”+”a”). The 4th term in the Fibonacci words is bab(“ba” +”b”) The 5th term in the Fibonacci words is babba(“bab” + “ba”) The 6th term in the Fibonacci words is babbabab(“babba” + “bab”). SAMPLE INPUT 1: 2 SAMPLE OUTPUT 1: a b SAMPLE INPUT 2: 5 SAMPLE OUTPUT 2: a b ba bab babba SAMPLE INPUT 3: 6 SAMPLE OUTPUT 3: a b ba bab babba babbabab SAMPLE INPUT 4: 8 SAMPLE OUTPUT 4: a b ba bab babba babbabab babbababbabba babbababbabbababbabab SAMPLE INPUT 5: 1 SAMPLE OUTPUT 5: a ''' N = int(input()) a,b = 'a', 'b' print(a,b,end=" ",sep=" ") s = None for _ in range(N-2): s = b + a print(s,end=" ") a = b b = s
88f65fe516f92393bed4ca19ddf3d8e3fafd7fe1
JRVSTechnologies/hackerrank_solutions
/easy/challanges/stairCases.py
429
4.15625
4
#!/bin/python3 import math import os import random import re import sys # Complete the staircase function below. def staircase(n): x = 1 while x <= n: spaces = (n - x) stairBlock = "" for _ in range(spaces): print(" ", end="") for _ in range(x): stairBlock += "#" print(stairBlock) x += 1 if __name__ == '__main__': n = 6 staircase(n)
ab10d76493ceeb2d11f5e437069a7e60a95cd031
Dikshantdhall/pythonModule
/task3.py
3,026
3.765625
4
# ////// 1 elementList = [10, "welcome", 30.0, 10 + 20j, 40, 50.0,"to", "Python", 40 -10j, 100] # ////// 2 elements = ["10",40, 30.0, "hello", "world"] print(elements[0]) print(elements[2:4]) print(elements[4:5]) # ////// 3 numberList = [10, 20, 30, 50] sum = 0 mult = 1 for i in numberList: sum = sum + i mult = mult * i print(sum) print(mult) # ///////4 listInfo = [-1, -10, 150, 20, 100, 40] print(min(listInfo)) print(max(listInfo)) # ///////5 listInfo = [1,2,4,8, 11, 15, 21] listOdd = [] for i in listInfo: if i%2 != 0: listOdd.append(i) print(listOdd) # ///////// 6 listSquare = [] for i in range(1, 31): if i * i < 31: listSquare.append(i) print(listSquare) # //////// 7 list1 = [1,3, 5, 7, 9, 10] list2 =[2, 4, 6, 8] list1[-1: ] = list2 print(list1) # //////// 8 a = { 1: 10 , 2: 20} b = {3: 30, 4:40} a.update(b) print(a) # //////// 9 dict1 = { } for i in range(1, 6): dict1[i] = i * i print(dict1) # //////// 10 x = "34, 67, 55, 33, 12, 98" list1 = x.split() tupp = tuple(list1) print(list1) print(tupp) # //////// 11 elementList = [10, "welcome", 30.0, 10 + 20j, 40, 50.0,"to", "Python", 40 -10j, 100] # /////// 12 elements = ["10",40, 30.0, "hello", "world"] print(elements[0]) print(elements[2:4]) print(elements[4:5]) # /////// 13 x = [100, 200, 300, 400, 500,[1,2,3,4,5,[10,20,30,40,50],6,7,8,9],600, 700, 800] # part 1 print(x[5][0:4]) # part 2 print(x[6:8]) # part 3 print(x[0:len(x):2]) # part 4 print(x [::-1]) # part 5 print(x[5][5][0:1]) #part 6 print(x[:-0]) # //////14 list1 = [] for i in range(1000): print(i) # ////// 15 Tuple advantages: immutable consumes less memory Can use in a dictionary as key but its not possible with lists # ////// 16 for i in range(1, 101): if i%3 == 0 and i%2 ==0: print(i) # ////// 17 str1 = "helloworld" str1 =str1.lower() print(str1[::-1]) for i in range(len(str1)): if str1[i] =="a" or str1[i] == "e" or str1[i] == "i" or str1[i]=="o" or str1[i] =="u": print(i, str1[i]) # ////// 18 str1 = "hello my name is abcde" str1 = str1.split() for i in str1: if len(i) % 2 == 0: print(i) # /////// 19 x = [1,2,3,4,5,6,7,8,9,-1] for i in range(len(x)): for j in range(i+1,len(x)): if x[i] + x[j] == 8: print(x[i], x[j]) # /////// 20 evenList = [2,4,6,8,10,16] oddList = [1,3,5,9,11] for i in range(10): num = int(input("Enter the number in the range of 1-50")) if num % 2 ==0 : evenList.append(num) elif num %3 == 0: oddList.append(num) print(sum(evenList)) print(max(evenList)) print(sum(oddList)) print(max(oddList)) # //////21 str1 = "12abcbacbaba344ab" dict1 ={} for i in str1: if i.isalpha(): if i in dict1: dict1[i] = dict1[i] + 1 else: dict1[i] = 1 for i in dict1: print(str(i) +"="+ str(dict1[i])) # ////// 22 x = (1,2,3,4,5,6,7,8,9,10) x1 = [] for i in x: if i % 2 ==0: x1.append(i) x1 = tuple(x1) print(x1)
a84893a6f84baaa928407fe25cc2198121ddd3c2
Virgil-YU/learning_note_python
/07_08数据类型.py
608
4.34375
4
""" 数值形: int(整形);float(浮点型(小数)) 布尔型: True(真);False(假) 字符串: str 列表: list 元组: tuple 集合: set 字典: dict """ # 验证数据类型 type num1 = 1 # int num2 = 1.1 # float a = "hello world" b = True c = [10, 20, 30] # list----列表 d = (10, 20, 30) # tuple-----元组 e = {10, 20, 30} # set----集合 f = {"name": "tom", "age": 18} # dict----字典----键值对 print(type(num1)) print(type(num2)) print(type(a)) print(type(b)) print(type(c)) print(type(d)) print(type(e)) print(type(f))
9a7d9e5987f613f3d721d457f2dc5d6507453627
derekianrosas/homework63
/dundermethods.py
602
3.9375
4
#double underscore is how python works with private and protected classes #private methods #str method, python looks for the defined class and returns whats inside/ the goal is to help you get some visibility class Invoice: def __init__(self, client, total): self.client = client self.total = total def __str__(self): return f'Invoice from {self.client} for {self.total}' def __repr__(self): return f'Invoice <value: client: {self.client}, total: {self.total}>' inv = Invoice('google', 500) print(str(inv)) print(repr(inv)) #string for nice output and repr true raw data in the class
06b4644429dc52326979e8bcb2fa637fab29fa12
gmrdns03/Python-Introductory-Course_Minkyo
/Python_Pandas_Basics/Pandas09_PracticeChk06_김민교.py
629
3.53125
4
# coding: utf-8 # In[1]: import pandas as pd # 시리즈이름.str.contains('a', case=False) #시리즈 안에서 a를 불린 형식으로 찾아주는 메소드 #case=False를 하면 대소문자 구별하지 않는다. # In[2]: s1 = pd.Series(['Mouse', 'dog', 'house and parrot', '23']) s1.str.contains('og') # In[5]: ind = pd.Index(['Mouse', 'dog', 'house and parrot', '23.0']) ind.str.contains('23') # In[6]: s1.str.contains('oG', case=False) # In[7]: s1.str.contains('house|dog') # In[8]: s1.str.contains('\\d') # In[9]: s2 = pd.Series(['40', '40.0', '41', '41.0', '35']) s2.str.contains('.0')
4416ca54b0ffb89217cf5055f3055787173560ee
simonzhang0428/Book_Think_Python
/class_function.py
2,257
4.21875
4
import copy from datetime import datetime class Time: """Represents the time of day. attributes: hours, minutes, second """ time = Time() time.hour = 11 time.minute = 59 time.second = 30 time2 = Time() time2.hour = 9 time2.minute = 00 time2.second = 00 def print_time(t: Time): print('%.2d : %.2d : %.2d' % (t.hour, t.minute, t.second)) print_time(time) def valid_time(time): if time.hour < 0 or time.minute < 0 or time.second < 0: return False if time.minute >= 60 or time.second >= 60: return False return True # pure function, not modify parameter, has no effect(display, get input...) def add_time(t1: Time, t2: Time): sum = Time() sum.hour = t1.hour + t2.hour sum.minute = t1.minute + t2.minute sum.second = t1.second + t2.second if sum.second >= 60: sum.second -= 60 sum.minute += 1 if sum.minute >= 60: sum.minute -= 60 sum.hour += 1 return sum # modifier, change the parameter. def increment1(time, seconds): time.second += seconds if time.second >= 60: time.second -= 60 time.minute += 1 if time.minute >= 60: time.minute -= 60 time.hour += 1 def time_to_int(time): minutes = time.hour * 60 + time.minute seconds = minutes * 60 + time.second return seconds def int_to_time(seconds): time = Time() minutes, time.second = divmod(seconds, 60) # returns the quotient and remainder as a tuple time.hour, time.minute = divmod(minutes, 60) return time print_time(int_to_time(time_to_int(time))) def add_time(t1, t2): assert valid_time(t1) and valid_time(t2) seconds = time_to_int(t1) + time_to_int(t2) return int_to_time(seconds) def increment(time, seconds): seconds += time_to_int(time) return int_to_time(seconds) print_time(increment(time, 11)) print_time(time) print_time(add_time(time, time2)) def is_after(t1, t2): """Returns True if t1 is after t2; false otherwise.""" return (t1.hour, t1.minute, t1.second) > (t2.hour, t2.minute, t2.second) print('True:', is_after(time, time2)) time3 = Time() time3.hour = 9 time3.minute = 00 time3.second = 00 add_time(time, time3) b1 = datetime(1987, 4, 28) print(b1)
e1c7555ce7a429da40c1b42aff20f79a0c11e08b
enterpriseih/algorithm016
/Week_04/127.Word Ladder.py
1,438
3.546875
4
from collections import defaultdict class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: def visit_word(q, visited, other_visited): current_word, level = q.pop(0) for i in range(n): intermediate_word = current_word[:i] + '*' + current_word[i+1:] for word in all_combo_dict[intermediate_word]: if word in other_visited: return level + other_visited[word] if word not in visited: visited[word] = level+1 q.append((word, level+1)) return None if not endWord or not wordList or endWord not in wordList: return 0 n = len(beginWord) all_combo_dict = defaultdict(list) for word in wordList: for i in range(n): intermediate_word = word[:i] + '*' + word[i+1:] all_combo_dict[intermediate_word].append(word) q_begin = [(beginWord, 1)] q_end = [(endWord, 1)] visited_begin = {beginWord: 1} visited_end = {endWord: 1} while q_begin and q_end: res = visit_word(q_begin, visited_begin, visited_end) if res: return res res = visit_word(q_end, visited_end, visited_begin) if res: return res return 0
d4e72a9e2724d41d85f4c5ad7b900e68e6b8fe71
gdorelo/holbertonschool-higher_level_programming
/0x0B-python-input_output/3-to_json_string.py
173
3.53125
4
#!/usr/bin/python3 ''' json encoding module ''' import json def to_json_string(my_obj): ''' encode an object (string) to json format ''' return json.dumps(my_obj)
50fd8d6fc0e8b1685c4ef987249772f6570208f9
maro525/aizu-online-judge
/alds1_5_c.py
755
3.71875
4
''' コッホ曲線 ''' from math import * class Point: def __init__(self, x, y): self.x = x self.y = y def koch(n, a, b): if n == 0: return x = (2.0 * a.x + 1.0 * b.x) / 3 y = (2.0 * a.y + 1.0 * b.y) / 3 s = Point(x, y) x = (1.0 * a.x + 2.0 * b.x) / 3 y = (1.0 * a.y + 2.0 * b.y) / 3 t = Point(x, y) th = pi * 60 / 180 x = (t.x-s.x) * cos(th) - (t.y-s.y) * sin(th) + s.x y = (t.x-s.x) * sin(th) - (t.y-s.y) * cos(th) + s.y u = Point(x, y) koch(n-1, a, s) print(s.x, s.y) koch(n-1, s, u) print(u.x, u.y) koch(n-1, u, t) print(t.x, t.y) koch(n-1, t, b) n = int(input()) a = Point(0, 0) b = Point(100, 0) print(a.x, a.y) koch(n, a, b) print(b.x, b.y)
6912cb5169c560fc865276e21458605824542b63
jdegrand/AdventOfCode
/2018/Day1/1.py
955
3.8125
4
""" @author: Joe DeGrand Advent Of Code 2018 Day 1: Frequency Problem """ def main(): """ Main function in charge of the looping of the program """ total = 0 dic = {} dic[0] = True first = True frequency = 0 loop = True while first is not False: for line in open("input.txt"): line = line.strip() operator = line[0] value = int(line[1:]) if operator == "-": total -= value else: total += value if total in dic.keys() and first is True: print("First Repeated Frequency: " + str(total)) first = False elif first is False: pass else: dic[total] = True if loop is True: frequency = total loop = False print("Total frequency is: " + str(frequency)) if __name__ == '__main__': main()
ca7f502e928eede578ff47eeaa6f609ccff6d916
yajian/ml_by_numpy
/rnn/train.py
794
3.515625
4
# coding=utf-8 # Reference:********************************************** # @Time    : 2020/8/17 4:59 PM # @Author  : huangyajian # @File    : train.py # @Software : PyCharm # @Comment : # Reference:********************************************** import preprocess from rnn import RNN import numpy as np dat = [] data = preprocess.Dataset() rnn = RNN(data.vocabulary_size) x = data.X_train[20006] print(x) np.random.seed(10) # Train on a small subset of the data to see what happens print("正在训练...") losses = RNN.train(rnn, data.X_train[1:2], data.Y_train[1:2], nepoch=10, evaluate_loss_after=1) predict = rnn.predict(x) print("predict shape = " + str(predict.shape)) print(predict) array_of_words = " ".join([data.index_to_word[x] for x in predict]) print(array_of_words)
729a6a23f5dc6367c9f93b3775f5786ad533f0dd
readbrent/AdventOfCode2017
/day3/day3.py
1,689
4.0625
4
import math def get_smallest_odd_square_greater(target): current_square = 3 while True: squared = current_square ** 2 if squared > target: return squared current_square += 2 def get_manhattan_distance(target): if target == 1: return 0 ring_corner = get_smallest_odd_square_greater(target) # Iterate counterclockwise until we hit the target ring_size = int(math.sqrt(ring_corner)) x_dist = (ring_size - 1) / 2 y_dist = (ring_size - 1) / 2 # Walk left current_val = ring_corner if current_val == target: return abs(x_dist) + abs(y_dist) for _ in range(ring_size - 1): current_val -= 1 x_dist -= 1 if current_val == target: return abs(x_dist) + abs(y_dist) # Walk up for _ in range(ring_size - 1): current_val -= 1 y_dist -= 1 if current_val == target: return abs(x_dist) + abs(y_dist) # Walk right for _ in range(ring_size - 1): current_val -= 1 x_dist += 1 if current_val == target: return abs(x_dist) + abs(y_dist) # Walk down for _ in range(ring_size - 1): current_val -= 1 y_dist += 1 if current_val == target: return abs(x_dist) + abs(y_dist) # Error! return -1 def run_manhattan_distance_tests(): assert get_manhattan_distance(1) == 0 assert get_manhattan_distance(12) == 3 assert get_manhattan_distance(1024) == 31 def run_tests(): run_manhattan_distance_tests() print (get_manhattan_distance(361527)) def main(): run_tests() if __name__ == "__main__": main()
18742a037f0e62d9c32a813ae1b667a66c89e1d1
domino14/euler
/factorize.py
895
3.6875
4
from eratosthenes import sieve # This will factorize up until some large number. s = sieve(1000000) def p_factorize(n): """ Return prime factors as an ordered list. >>> p_factorize(857) [857] >>> p_factorize(646) [2, 17, 19] >>> p_factorize(644) [2, 2, 7, 23] >>> p_factorize(15) [3, 5] >>> p_factorize(645) [3, 5, 43] """ s_index = 0 factors = [] while n != 1: #print 'tryng to divide', n, s[s_index] quo, rem = divmod(n, s[s_index]) if rem != 0: #print 'remainder was not 0, increase index', s_index s_index += 1 else: #print 'remainder was 0, set n', quo n = quo #print 'append factor', s[s_index] factors.append(s[s_index]) return factors if __name__ == "__main__": import doctest doctest.testmod()
e0ebad3ad24a59b9ef378d5fdb851c433bca91ca
cjbt/Intro-Python-I
/src/14_cal.py
1,573
4.34375
4
""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py month [year]` and does the following: - If the user doesn't specify any input, your program should print the calendar for the current month. The 'datetime' module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys import calendar import datetime calendar.setfirstweekday(0) cal = calendar.Calendar() def makeCal(*args): year = int(str(datetime.datetime.today())[:4]) month = int(str(datetime.datetime.today())[5:7]) if len(args) > 1: print(calendar.TextCalendar(firstweekday=0).formatmonth( int(args[1]), int(args[0]))) elif len(args) == 1 and args[0] != '': print(calendar.TextCalendar(firstweekday=0).formatmonth( year, args[0])) elif args[0] == '': print(calendar.TextCalendar(firstweekday=0).formatmonth( year, month)) print('must take in a month and a date separated by commas: month,year') sys.exit() print(makeCal(*sys.argv[1:]))
20666dcb4897240008cb60b2d01618b246db6734
kamit17/Python
/W3Resource_Exercises/lists/ex19.py
308
4.3125
4
#Python program to get the difference between two lists list1 = [1,2,3,4,5,6] list2=[2,3,4,11,15] list_diff=[] # for i in list1 + list2: # if i not in list1 or i not in list2: # list_diff.append(i) list_diff=[i for i in list1 + list2 if i not in list1 or i not in list2] print(list_diff)
840cfd3c122dba5807f38e7bb62b39bc952f126a
Krishna219/Fundamentals-of-computing
/Principles of Computing (Part 2)/Week 2/my_solution.py
2,154
3.84375
4
def triangular_sum(num): """ Sum of n numbers """ if num == 0: #base case return 0 else: return num + triangular_sum(num - 1) #recursive case for i in range(11): print triangular_sum(i) def number_of_threes(num): if num//10 == 0: if num == 3: return 1 else: return 0 else: if num%10 == 3: return 1 + number_of_threes(num//10) else: return number_of_threes(num//10) print number_of_threes(3453433) def is_member(my_list, elem): if len(my_list) == 1: return my_list[0] == elem else: if elem == my_list[0]: return True else: return is_member(my_list[1:], elem) print is_member(['c', 'a', 't'], 'q') def remove_x(my_string): if len(my_string) == 1: if my_string == 'x': return "" else: return my_string else: if my_string[0] == 'x': return remove_x(my_string[1:]) else: return my_string[0] + remove_x(my_string[1:]) print remove_x("catxxdogx") def insert_x(my_string): if len(my_string) == 2: return my_string[0] + "x" + my_string[1] else: return my_string[0] + "x" + insert_x(my_string[1:]) print insert_x("catdog") def list_reverse(my_list): if len(my_list) == 1: return my_list else: return [my_list[-1]] + list_reverse(my_list[0:-1]) print list_reverse([2, 3, 1]) def gcd(num1, num2): if num2 > num1: return gcd(num2, num1) else: if num2 == 0: return num1 else: return gcd(num2, num1 - num2) print gcd(1071, 462) def slice(my_list, first, last): if first > len(my_list) or last > len(my_list) or first >= last: return [] else: first_elem = my_list[first] print first_elem return [first_elem] + slice(my_list, first + 1, last) print slice(['a', 'b', 'c', 'd', 'e'], 2, 4) print slice([10,21,34,56,78,90,101,23,45,67,89], 5, 9), [10,21,34,56,78,90,101,23,45,67,89]
136009cadee197858944f9dc4489625d529603a4
WandersonGomes/URIJudge
/problem_1893.py
365
3.59375
4
#PROBLEM 1893 #link = https://www.urionlinejudge.com.br/judge/pt/problems/view/1893 #PYTHON 3 noite1, noite2 = input().split() noite1, noite2 = int(noite1), int(noite2) if noite2 <= 2: print("nova") elif noite2 >= 3 and noite2 <= 96: if noite1 <= noite2: print("crescente") else: print("minguante") elif noite2 >= 97: print("cheia")
74ec37b572dfeb317553bfa6f1fc375f0e1125bc
ferryleaf/GitPythonPrgms
/strings/palindrome_strings.py
488
3.859375
4
def Solution(element): length = len(element) mid_idx = int(length/2) f_str= element[:mid_idx] s_str="" # To Handle String with odd length if(length%2!=0): mid_idx = mid_idx+1 for i in range(mid_idx,length): s_str= element[i] + s_str if(f_str==s_str): print("Yes a Palindrome") else: print("Not a Palindrome") if __name__=='__main__': element = input().strip() if(len(element)!=0): Solution(element)
afefe7cb7022bd5367a4af3075082050ddc601c9
WangXiaoyugg/Learn-Pyhton
/python-advanced/one/2-4.py
184
3.640625
4
def f(x): return x**2 print map(f,[1,2,3,4,5,6,7,8,9]) def format_name(s): return s[0].upper() + s[1:].lower() names = ['adam','LISA','barY'] print map(format_name,names)
b9ddec92e24704f43ad2547744d266f6c03a937b
bupthl/Python
/Python从菜鸟到高手/chapter6/demo6.01.py
1,568
3.703125
4
''' --------《Python从菜鸟到高手》源代码------------ 欧瑞科技版权所有 作者:李宁 如有任何技术问题,请加QQ技术讨论群:264268059 或关注“极客起源”订阅号或“欧瑞科技”服务号或扫码关注订阅号和服务号,二维码在源代码根目录 如果QQ群已满,请访问https://geekori.com,在右侧查看最新的QQ群,同时可以扫码关注公众号 “欧瑞学院”是欧瑞科技旗下在线IT教育学院,包含大量IT前沿视频课程, 请访问http://geekori.com/edu或关注前面提到的订阅号和服务号,进入移动版的欧瑞学院 “极客题库”是欧瑞科技旗下在线题库,请扫描源代码根目录中的小程序码安装“极客题库”小程序 关于更多信息,请访问下面的页面 https://geekori.com/help/videocourse/readme.html ''' ''' names = ["Bill", "Mike", "John", "Mary"] numbers = ["1234", "4321", "6645", "7753"] print(numbers[names.index("Mike")]) print(names[numbers.index("6645")]) phoneBook = {"Bill":"1234", "Bill1":"4321", "John":"6645","Mary":"7753"} print(phoneBook["Bill"]) items = [["Bill","1234"], ("Mike","4321"),["Mary", "7753"]] d= dict(items) print(d) items = dict(name = "Bill", number = "5678", age = 45) print(items) #items = dict([names, numbers]) #print([names, numbers]) ''' items = [] while True: key = input("请输入Key:") if key == "end": break; value = input("请输入value:") keyValue = [key, value] items.append(keyValue) d = dict(items) print(d)
529e540e4cbc06e83a0bddeb884f88eb22aabba0
sealzjh/algorithm
/gradient_descent_n.py
843
3.59375
4
# -*- encoding: utf8 -*- class GradientDecent: def __init__(self, rate): self.__rate = rate def f(self, x): return x[0] + 2 * x[1] + 4 def loss(self, x): return (self.f(x) - 0) ** 2 def gradient_descent(self, x): delta = 0.00000001 derivative = {} derivative[0] = (self.loss([x[0] + delta, x[1]]) - self.loss(x)) / delta derivative[1] = (self.loss([x[0], x[1] + delta]) - self.loss(x)) / delta x[0] = x[0] - self.__rate * derivative[0] x[1] = x[1] - self.__rate * derivative[1] return x def run(self, x): for i in range(150): x = self.gradient_descent(x) print "x = %f, %f, fx = %f" % (x[0], x[1], self.f(x)) if __name__ == '__main__': gd = GradientDecent(0.01) x = [-0.5, -1.0] gd.run(x)
5e72de31ad13287965eb9558237b0d1f0cac1d5c
nunes-moyses/Projetos-Python
/Projetos Python/pythonexercicios/des092.py
513
3.65625
4
from random import randint from time import sleep from operator import itemgetter t = 0 jogos = {'jogador1': randint(1, 6), 'jogador2': randint(1, 6), 'jogador3': randint(1, 6), 'jogador4': randint(1, 6)} ranking = list() print('JOGOS SORTEADOS') for k, v in jogos.items(): print(f'O {k} tirou {v}') sleep(1) ranking = sorted(jogos.items(), key=itemgetter(1), reverse=True) print('Ranking:') for i, m in enumerate(ranking): print(f'O {i+1}° colocado é {m[0]} com {m[1]}')
e53cf9dcea60b0f8eb127f4173cf128087c996fc
orenlivne/euler
/euler/problem131.py
768
3.5
4
''' ============================================================ http://projecteuler.net/problem=131 There are some prime values, p, for which there exists a positive integer, n, such that the expression n3 + n2p is a perfect cube. For example, when p = 19, 83 + 8219 = 123. What is perhaps most surprising is that for each prime with this property the value of n is unique, and there are only four such primes below one-hundred. How many primes below one million have this remarkable property? ============================================================ ''' from problem035 import is_prime pnum = lambda N: sum(1 for a in xrange(1, int((-3 + (12 * N - 3) ** 0.5) / 6.) + 1) if is_prime(3 * a * (a + 1) + 1)) if __name__ == "__main__": print pnum(10 ** 6)
ef903840f00195376ec02146257d8e9ce4706cbf
wan-h/Brainpower
/Code/CS/DesignPatterns/StatePattern.py
1,055
3.796875
4
# coding: utf-8 # Author: wanhui0729@gmail.com # 创建一个接口。 class State(object): def doAction(self): pass # 创建实现接口的实体类。 class StartState(State): def doAction(self, context): print("Player is in start state") context.setState(self) def toString(self): return "Start State" class StopState(State): def doAction(self, context): print("Player is in stop state") context.setState(self) def toString(self): return "Stop State" # 创建 Context 类。 class Context(object): def __init__(self): self.state = None def setState(self, state): self.state = state def getState(self): return self.state # 使用 Context 来查看当状态 State 改变时的行为变化。 if __name__ == '__main__': context = Context() startState = StartState() startState.doAction(context) print(context.getState().toString()) stopState = StopState() stopState.doAction(context) print(context.getState().toString())
f0d2b5f09a96745307e2188ecb6b20dcb47500af
gopalagarwal3/search-highlights
/viewer/es_search.py
1,818
3.625
4
from datetime import datetime from elasticsearch import Elasticsearch from typing import List import json document_text = """The easiest way to learn how to use Streamlit is to try things out yourself. As you read through this guide, test each method. As long as your app is running, every time you add a new element to your script and save, Streamlit’s UI will ask if you’d like to rerun the app and view the changes. This allows you to work in a fast interactive loop: you write some code, save it, review the output, write some more, and so on, until you’re happy with the results. The goal is to use Streamlit to create an interactive app for your data or model and along the way to use Streamlit to review, debug, perfect, and share your code.""" es = Elasticsearch() def search_es(search_query, search_text) -> List[str]: doc = { 'id': '2', 'content': search_text } res = es.index(index="test-offset", id=2, body=doc) print(res['result']) es.indices.refresh(index="test-offset") es_query = """{ "query": { "query_string": { "query": "%s" } }, "highlight": { "fields": { "content": { "type": "offset" } }, "fragment_size": 50 } }""" % (search_query) res = es.search(index="test-offset", body=json.loads(es_query)) print("Got %d Hits:" % res['hits']['total']['value']) snippets = [] for hit in res['hits']['hits']: for snippet in hit["highlight"]["content"]: snippets.append(snippet) return snippets print(search_es('the', document_text))
54851fec2a0a990396a6acd1db3af357fd2f48ee
CodeLagos/Batch-Five
/Point Of Grace/Python/Mayowa Adeoye OXFORD MULTI-MULTIPLICATION TABLE.py
861
4.28125
4
print("welcome to the ADE-MAYOWA OXFORD MULTI-MULTIPLICATION TABLE") print("Please enter the number you want to view the multiplication table") print("Please Enter Whole Number") print(" ") value=int(input("Please enter a number: ")) for i in range(1,21,1): print(value,"*",i,"=",value*i) value=int(input("Please enter a number: ")) for i in range(1,21,1): print(value,"*",i,"=",value*i) value=int(input("Please enter a number: ")) for i in range(1,21,1): print(value,"*",i,"=",value*i) value=int(input("Please enter a number: ")) for i in range(1,21,1): print(value,"*",i,"=",value*i) value=int(input("Please enter a number: ")) for i in range(1,21,1): print(value,"*",i,"=",value*i) value=int(input("Please enter a number: ")) for i in range(1,21,1): print(value,"*",i,"=",value*i) print ("THE END")
b22b3c20bdf85a4497623469cb6bf00084b97b54
mhasan3420/02_python_challenge
/PyBank/Resources/main.py
1,764
3.796875
4
import csv import os budget_data = os.path.join('..','Resources','budget_data.csv') #add lists totalmonths = [] netprofit = [] profitchange = [] # Open and read csv file with open("budget_data.csv","r") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") next(csvreader) #for lope for row in csvreader: totalmonths.append(row[0]) netprofit.append(int(row[1])) for i in range(len(netprofit)-1): profitchange.append(netprofit[i+1]-netprofit[i]) # max and min values increase = max(profitchange) decrease = min(profitchange) monthlyincrease = profitchange.index(max(profitchange))+1 monthlydecrease = profitchange.index(min(profitchange))+1 # print results print("Financial Analysis") print("-------------------") print(f"Total Months:{len(totalmonths)}") print(f"Total: ${sum(netprofit)}") print(f"Average Change:{round(sum(profitchange)/len(profitchange),2)}") print(f"Greatest Increase in Profits: {totalmonths[monthlyincrease]} (${(str(increase))})") print(f"Greatest Decrease in Profits: {totalmonths[monthlydecrease]} (${(str(decrease))})") # export text file output = "output.txt" with open("output","w") as new: new.write("Financial Analysis") new.write("\n") new.write("--------------------") new.write("\n") new.write(f"Total Months:{len(totalmonths)}") new.write("\n") new.write(f"Total: ${sum(netprofit)}") new.write("\n") new.write(f"Average Change: {round(sum(profitchange)/len(profitchange),2)}") new.write("\n") new.write(f"Greatest Increase in Profits: {totalmonths[monthlyincrease]} (${(str(increase))})") new.write("\n") new.write(f"Greatest Decrease in Profits: {totalmonths[monthlydecrease]} (${(str(increase))})")
17d92d5dffe391a803ad91ffc2be07de7c08ef43
FCHSCompSci/dictionaryinaction-Kadijatu6345201
/Choose your own adventure-Enter the Kingdom.py
3,485
3.546875
4
import random import time game_stats = { "level_up": 35000, "kingdom_coins": 10000, } STATS = { "Level": 1, "Weapon": "Knife", "xp": 0, "coins": 0, } monsters = { "Nyarlathotep":"monster1", "Azathoth": "monster2", "Dagon": "monster3", "Hastur": "monster4", "Aiueb Gnshal": "monster5", "C'thalpa": "monster6", "Cxaxukluth": "monster7", "Kaajh'Kaalbh": "monster8", "Ycnàgnnisssz": "monster9", } player = input("Welcome, player, to floating castle. Before we begin our journey, I need a name to call you by. Can't call you 'The Player' for the whole game."\ " Type in the name you'd like to go by: ") print("Alright then, " +player+ ". Your story begins just outside of the walls of the great city of Avaral. You came all the way from your home kingdom of Solvir to visit a friend of yours."\ " Anamore was her name, and she resided in the castle of the royal family, and as she is one of the best witches in the country, acted as the head of magical research. You hadn't seen her"\ " in quiet a bit of time, and had decided to come for a visit. When you came to the large gates of the kingdom, however, you found yourself faced with an entry fee of 10,000 coins that"\ " didn't exist last time you visited. You unfortunately had used up all of your money on resources on your way here, so you had 0 coins on your person. to check how many coins you have at"\ " any given momnet, along with how much xp, what weapon you have equipped, and what level your on, simply type STATS in all caps. Go ahead and give it a try.") while True: stat = input("Type STATS: ") if stat == "STATS": print ("Great! Like knowing that your currently weaker then the weakest eldritch beast?") break else: print ("I'm not letting you leave until you check your stats") print("Moving on, you heard through the grapevine that monsters"\ " in the forests surounding Avaral drop coins when you fought them.") time.sleep(2) while True: monfight = random.choice(list(monsters.keys())) fight = input("Explore the forests of Avaral? [Y]es/[N]o: ") if fight == "y": STATS["xp"] = STATS["xp"] + random.choice(range(500,1000)) STATS["coins"] = STATS["coins"] + random.choice(range(100,500)) print ("You walk through the forests and come across " +monfight+ ". You kill the Eldritch beast and gain coins and xp. you now have " +str(STATS["coins"])+ \ " coins and " +str(STATS["xp"])+ " xp. Good job!") else: print ("You can't get into the kingdom without money, so either stand outside those walls forever and starve to death, or get your lazy butt in that forest and slay some Eldritch beasts!") if STATS["xp"] == game_stats["level_up"]: STATS["Level"] = STATS["Level"] + 1 print("You went up one level! Your doing great sweety~") else: print("Nothing happened. Your close though!") if STATS["coins"] == game_stats["kingdom_coins"]: print("You have enough coins to get into the kingdom now! You can keep grinding for coins and xp t be able to level up and buy stuff in the kingdom market." \ " Whenever your ready to head into the kingdom, type ENTER KINGDOM in all caps. You can come back to grind at any time.") else: print("keep going, you still need more coins to enter the kingdom") #need to add that last section to the while loop
52d0918cad2d5115cfd07e9c51d070d87803f126
geenafong/Python-Tech-Degree
/Project1/guessing_game.py
2,880
4.40625
4
""" Python Web Development Techdegree Project 1 - Number Guessing Game -------------------------------- For this first project we will be using Workspaces. NOTE: If you strongly prefer to work locally on your own computer, you can totally do that by clicking: File -> Download Workspace in the file menu after you fork the snapshot of this workspace. """ import random high_score_list = [] def get_random_number(): random_number = random.randint(1,10) return random_number def start_game(): """Psuedo-code Hints When the program starts, we want to: ------------------------------------ 1. Display an intro/welcome message to the player. 2. Store a random number as the answer/solution. 3. Continuously prompt the player for a guess. a. If the guess greater than the solution, display to the player "It's lower". b. If the guess is less than the solution, display to the player "It's higher". 4. Once the guess is correct, stop looping, inform the user they "Got it" and show how many attempts it took them to get the correct number. 5. Let the player know the game is ending, or something that indicates the game is over. ( You can add more features/enhancements if you'd like to. ) """ # write your code inside this function. print("Welcome to the number guessing game! Let's begin...") if len(high_score_list) == 0: print("No current high score") else: print("Current highscore is: ", str(min(high_score_list))) guess_number = "" random_number = get_random_number() count = 1 while guess_number != random_number: try: guess_number = int(input("Please guess a number from 1 to 10: ")) except ValueError: print("Oops! That was not a valid number. Try again...") else: if guess_number > 10 or guess_number < 1: print("Your number was not between 1 to 10.") elif guess_number > random_number: count+=1 print("It is lower.") elif guess_number < random_number: count+=1 print("It is higher.") else: print(f'Congratulations! You got it. It only took you {count} try(ies). The game is now over.') current_score = count high_score_list.append(current_score) print("Current highscore is: ", str(min(high_score_list))) play_again = str(input("See if you can beat your score. Play again? yes or no: ").lower()) if play_again == "yes": start_game() else: print("Thanks for playing") break if __name__ == '__main__': # Kick off the program by calling the start_game function. start_game()
e8dd99e74ad830b46a8f8c313408253c0eab0b8d
genghisken/gkspecies
/inchi/code/tools/python/roman_numerals.py
1,034
4.25
4
# convert an integer to a roman numeral # keep it reasonable since from 5000 on special characters are used # see also: http://en.wikipedia.org/wiki/Roman_numerals # tested with Python24 vegaseat 25jan2007 # 2011-06-20 KWS Roman numerals required to set spectroscopic ionization status for elements. # We have a list of many ions from the VALD database. def int2roman(number): numerals = { 1 : "I", 4 : "IV", 5 : "V", 9 : "IX", 10 : "X", 40 : "XL", 50 : "L", 90 : "XC", 100 : "C", 400 : "CD", 500 : "D", 900 : "CM", 1000 : "M" } result = "" for value, numeral in sorted(numerals.items(), reverse=True): while number >= value: result += numeral number -= value return result #print int2roman(input("Enter an integer (1 to 4999): "))
d0cf14b39ca7468ac3899ba8f178e09aecfb431a
prathik-kumar/python
/Fundamentals/func_overload.py
641
3.59375
4
class ServiceInfo(object): def __init__(self, id, name, description): self.id = id self.name = name self. description = description #default arguments for omitting calling arguments def alter(self, id, name = None, description = None): self.id = id if name != None: self.name = name if description != None: self.description = description #string representation for printing def __str__(self): return f'{self.id} {self.name}: {self.description}' s = ServiceInfo(1021, 'synchronization-job', 'File synchronization process') print(s) s.alter(1021, 'sync-job', 'File sync process') print(s) s.alter(1051) print(s)
fdf71bc27ee9fba157d6defa34a5ca71b839ec2d
georggoetz/hackerrank-py
/Python/Math/find_angle_mbc.py
359
3.90625
4
# http://www.hackerrank.com/contests/python-tutorial/challenges/find-angle import math ab = int(input()) bc = int(input()) # hypotenuse ac = math.sqrt(ab ** 2 + bc ** 2) mc = ac / 2.0 # median mb = math.sqrt(2.0 * (ab**2 + bc**2) - ac**2) / 2.0 theta = math.acos((mb**2 + bc**2 - mc**2) / (2.0 * mb * bc)) print(str(int(round(math.degrees(theta)))) + '°')
12ef367f31a0bf3640b9a891f5a717ac9cbd8385
McCarthyCode/Python
/Fundamentals/scores_and_grades.py
520
4.1875
4
import random def score_grade(x): if x <= 100 and x >= 90: print "Score: " + "{}".format(str(x)).rjust(3) + "; Your grade is A" elif x <= 89 and x >= 80: print "Score: " + str(x) + "; Your grade is B" elif x <= 79 and x >= 70: print "Score: " + str(x) + "; Your grade is C" elif x <= 69 and x >= 60: print "Score: " + str(x) + "; Your grade is D" print "Scores and Grades" for i in range(10): score_grade(random.randint(60,100)) print "End of the program. Bye!"
332b5493baea31268b0612be39cbb968f6699bc4
ElvisKwok/code
/python_test/beginning_python/2.py
1,498
3.6875
4
#!/usr/bin/env python # coding: utf-8 #edward = ['Edward Gumby', 42] #john = ['John Smith', 50] #database = [edward, john] #print database #months = [ # 'January', # 'February', # 'March', # 'April', # 'May', # 'June', # 'July', # 'August', # 'September', # 'October', # 'November', # 'December' #] # #endings = ['st', 'nd', 'rd'] + 17 * ['th'] \ # + ['st', 'nd', 'rd'] + 7 * ['th'] \ # + ['st'] # #year = raw_input("Year: ") #month = raw_input("Month (1-12):") #day = raw_input("Day (1-31):") # #month_number = int(month) #day_number = int(day) # #month_name = months[month_number-1] #ordinal = day + endings[day_number-1] # #print month_name + ' ' + ordinal + ', ' + year #sequence = [None] * 10 #print sequence #sentence = raw_input("Sentence: ") # #screen_width = 80 #text_width = len(sentence) #box_width = text_width + 6 #left_margin = (screen_width - box_width) // 2 # #print #print ' ' * left_margin + '+' + '-' * (box_width-4) + '+' #print ' ' * left_margin + '| ' + ' ' * text_width + ' |' #print ' ' * left_margin + '| ' + sentence + ' |' #print ' ' * left_margin + '| ' + ' ' * text_width + ' |' #print ' ' * left_margin + '+' + '-' * (box_width-4) + '+' #print database = [ ['Elvis', '1234'], ['Smith', '2313'], ['Jones', '3434'] ] username = raw_input("User name: ") password = raw_input("Password: ") if [username, password] in database: print 'Access granted' else: print 'Denied'
59053b0fb4f9973865e21b48583976a4b2a9415c
rmount96/Troll-Toll
/Troll-Toll/unit.py
2,489
3.59375
4
class Unit: def __init__(self, name, position, health =10, attack_power =2): self.name = name self.health = health self.attack_power = attack_power self.position = position #{"x":1, "y":1} [1,1] def get_hit(self, power): #print("The creature attacks you for %s HP" % power) self.health = self.health - power def attack(self, enemy): enemy.get_hit(self.attack_power) def move(self, dir): if dir == "up": self.position = [self.position[0], self.position[1]-1] elif dir == "down": self.position = [self.position[0], self.position[1]+1] elif dir == "left": self.position = [self.position[0]-1, self.position[1]] elif dir == "right": self.position = [self.position[0]+1, self.position[1]] class Player(Unit): def __init__(self, name, position, health =10, attack_power =2): super().__init__(name, position, 15, 5) self.inventory = [] def __str__(self): inv = "" for ivt in self.inventory: inv += " "+ivt.name return """ *************** Health: %s Position: %s Inventory: %s ***************""" % (self.health, self.position, inv) def get_hit(self, power): print("The creature attacks you for %s HP" % power) self.health = self.health - power def attack(self, enemy): print("You attack the %s for %s power" % (enemy.name, self.attack_power)) enemy.get_hit(self.attack_power) def pickup_item(self, item): self.inventory.append(item) item.get_picked_up(self) def troll_encounter(self, enemy): print("You are able to attack twice before he rises!") self.attack(enemy) self.attack(enemy) print("UH-OH! He looks angry!") class Troll(Unit): def __init__(self, name, position, health =10, attack_power =2): super().__init__("Troll", [6,3], 15, 7) def smash(self, enemy): print("I WILL CRUSH YOU!") super().attack(enemy) print("...and sends you flying back to the entrance") enemy.position = [5,5] #super().get_hit(enemy.attack_power) # def troll_encounter(self, enemy): # print("You are able to attack twice before he rises!") # player.attack(enemy) # player.attack(enemy) # super().attack(Player) # print("UH-OH!")
8cd30959172177ab8e8592367bc469167b8ccf74
SVMarshall/programming-challanges
/leetcode/add_digits.py
289
3.59375
4
# https://leetcode.com/problems/add-digits/ class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ num_str = str(num) while len(num_str) > 1: num_str = str(sum(map(int,num_str))) return int(num_str)
ed3314ecc1498462df5530ad8199f715b12472d3
jaideep99/NeuralNetsAI
/test.py
234
3.515625
4
import numpy as np p = np.array([[1,-1,3],[-1,5,-7]]) print(p) def sigmoid(x): return 1/(1+np.exp(-x)) def relu(x): return np.maximum(0,x) def relu_dev(x): x[x<=0]=0 x[x>0]=1 return x p = relu_dev(p) print(p)
b8dc6d0e019170c249277a4cfbe6b0b404105c93
PedroM85/Programacion-Orientada-a-Objecto-Lucas-
/Ejercicios-basicos-Python-master/src/Ejercicios basicos.py
8,557
4.15625
4
# Ejercicios sencillos de aprendizaje de python from math import pi # Funcion que retorne el mayor de dos numeros o 0 si son iguales def max_numeros(num1, num2): """ Devuelve el mayor de dos numeros x e y :param num1: float :param num2: float :return: float """ if num1 > num2: return num1 elif num2 > num1: return num2 else: return 0 # Funcion que determine si una persona es mayor de edad o no def es_mayor_edad(edad): """ Determina si una persona es mayor de edad a partir de su edad :param edad: int :return: bool """ return edad >= 18 # Programar una funcion que determine si una empresa es microempresa o no (retorno booleano True o False). # Se dice que es microempresa si tiene menos de 50 empleados, factura menos de 30 # millones de euros y tiene un balance igual o inferior a los 5 millones de euros. def es_microempresa(num_empleados, facturacion, balance): """ Determina si una empresa es microempresa o no :param num_empleados: int :param facturacion: int :param balance: int :return: bool """ return num_empleados < 50 and facturacion < 30 and balance <= 5 # Calcular el impuesto que debe pagar un contribuyente a partir de sus ingresos anuales # y el numero de hijos. El impuesto a pagar es un tercio del ingreso imponible, # siendo este ultimo igual a los ingresos totales menos una deduccion personal de 600 euros # y otra deduccion de 60 euros por hijo. def calcular_impuesto(): """ Calcula el impuesto que debe pagar un contribuyente en funcion se sus ingresos anuales y el numero de hijos. :return: float """ ingresos_anuales = input("Inserte sus ingresos anuales (en euros): ") tiene_hijos = raw_input("Tiene Ud. hijo/as? (S/N): ") if tiene_hijos == "S": num_hijos = input("Escriba cuantos hijo/as tiene: ") ingreso_imponible = ingresos_anuales - 600 - (60 * num_hijos) else: ingreso_imponible = ingresos_anuales - 600 return ingreso_imponible / 3.0 # Hacer los calculos que permiten saber si una empresa de 20 empleados, 18 millones de euros de # facturacion y 5 millones de euros de balance es una micro empresa y almacenar el # valor en una variable logica (booleana). # Solucion: llamar a la funcion, y escribir 20, 18 y 5 => True ejercicio_microempresa = es_microempresa(20, 18, 5) # La temperatura expresada en grados centigrados TC, se puede convertir a grados # Fahrenheit (TF) mediante la siguiente formula: TF = 9*TC/5 + 32. Programa una funcion # para hacer esta transformacion que reciba como argumento la temperatura en grados # centigrados y retorne su equivalente en Farenheit. def centigrados_to_fahrenheit(grados_centigrados): """ Transforma grados centigrados a fahrenheit :param grados_centigrados: float :return: float """ return 9*grados_centigrados/5.0 + 32 # Escribir una funcion Python que a partir de una cierta cantidad en euros y # del tipo de cambio del dia, retorne el equivalente en libras teniendo en cuenta que # la casa de cambio retiene una comision del 2% sobre el total de la operacion. def euros_to_libras(euros, tipo): """ Transforma euros a libras, con una comision del 2% :param euros: float :param tipo: float :return: float """ return (euros*tipo)*0.98 # Procedimiento que pinte una linea de asteriscos en pantalla def pintar_asteriscos(): """ Pinta una linea de asteriscos :return: void """ print("********************************") # Programe un modulo en Python que reutilizando la funcion anterior muestre nuestros datos # en pantalla con formato banner tal y como se representa abajo: # ************************************** # Autor: Miguel David Monzon # Email: miguel.monzon@uah.es # ************************************** def pintar_banner(autor, email): """ Pinta un banner con autor junto a su e-mail :param autor: string :param email: string :return: void """ pintar_asteriscos() print("Autor: "+autor) print("Email: "+email) pintar_asteriscos() # Programa modularizado que, utilizando funciones, calcule el perimetro y el area de # un circulo cuyo radio es proporcionado por el usuario def calcular_perimetro(radio): """ Calcula el perimetro de una circunferencia dado su radio :param radio: float :return: float """ return 2.0 * pi * radio def calcular_area(radio): """ Calcula el area de una circunferencia dado su radio :param radio: float :return: float """ return pi * (radio ** 2.0) def programa_calculo(): """ Calcula el perimetro y el area de una circunferencia dado su radio :return: void """ radio = input("Inserte el radio del circulo: ") print("Su perimetro es: " + str(calcular_perimetro(radio))) print("Su area es: " + str(calcular_area(radio))) # Escribir un programa para solicitar al usuario el numero de horas y el precio por hora # con vistas a calcular su salario bruto. Las horas que sobrepasen 40 se consideraran # extra y pagadas a 1,5 veces el precio de la hora regular. def calcular_salario_bruto(): """ Calcula salario bruto en funcion del numero de horas y el precio de la hora regular y extra :return: float """ num_horas = input("Inserte el numero de horas: ") precio_hora = input("Inserte el precio de la hora (regular): ") if num_horas > 40: horas_extra = num_horas - 40 precio_extra = horas_extra * 1.5 return 40 * precio_hora + precio_extra else: return num_horas * precio_hora # Programar una funcion que determine si un numero es par o impar. La funcion debe retornar # verdadero o falso haciendo uso de valores booleanos. def es_par(num): """ Devuelve si un numero es par o no :param num: int :return: bool """ return num % 2 == 0 # Programar una funcion que determine si una letra es vocal o no. def es_vocal(letra): """ Devuelve si una letra es vocal o no :param letra: char :return: bool """ return letra.upper() in ['A', 'E', 'I', 'O', 'U'] # Programar una funcion en Python que a partir de un numero entero entre 1 y 7 que recibe como # argumento retorne el dia de la semana que corresponda, y un mensaje de error si # el numero no esta entre 1 y 7. def dia_semana(num): """ Devuelve el dia de la semana correspondiente al numero pasado por parametro :param num: int :return: string """ if num == 1: return "Lunes" elif num == 2: return "Martes" elif num == 3: return "Miercoles" elif num == 4: return "Jueves" elif num == 5: return "Viernes" elif num == 6: return "Sabado" elif num == 7: return "Domingo" else: return "Error, el numero tiene que estar entre 1 y 7." def dia_semana_switch(num): """ Devuelve el dia de la semana correspondiente al numero pasado por parametro, usando switch :param num: int :return: string """ switcher = { 1: "Lunes", 2: "Martes", 3: "Miercoles", 4: "Jueves", 5: "Viernes", 6: "Sabado", 7: "Domingo", } return switcher.get(num, "Error, el numero tiene que estar entre 1 y 7.") # Funcion que recibe un numero y que muestre la tabla de multiplicar de ese numero (hasta 10) def tabla_multiplicar(num): """ Pinta la tabla de multiplicar de un numero :param num: float :return: void """ for i in range(0, 11): print (str(num) + " * " + str(i) + " = " + str(num*i)) # Funcion que suma todos los elementos del 1 al 200 que sean multiplos de 3 o de 5 def suma_multiplos(): """ Calcula la suma de los multiplos de 3 o 5 entre el 1 y el 200 y lo pinta en pantalla :return: void """ suma = 0 for i in range(1, 201): if i % 3 == 0 or i % 5 == 0: suma += i print ("La suma de los multiplos de 3 o de 5 es: " + str(suma)) # Funcion que devuelve la suma de los primeros 50 numeros que cumplen la condicion de ser # multiplo de 3 o de 5 def suma_multiplos2(): """ Calcula la suma de los 50 primeros multiplos de 3 o de 5 y lo pinta en pantalla :return: void """ num = 1 suma = 0 contador = 0 while contador < 50: if num % 3 == 0 or num % 5 == 0: suma += num contador += 1 num += 1 print ("La suma de los 50 primeros multiplos de 3 o 5 es: " + str(suma))
f7cd7aa1dd79780a5861626c3609ede11bdc96f9
imbaxl/-
/numpy_practice/np.array.py
425
4
4
import numpy as np ''' a = np.array([[1,2,3],[4,5,6]]) b = np.array([[2,2,3],[4,4,2]]) c = a*b print(c) ''' #matrix是array的分支, a = np.array([[1,2,3],[1/2,1/4,1/6],[1/3,1/6,1/9]]) b = np.array([[0,1,1],[1,0,-1],[1,1,1]]) #c = a.dot(b) c = np.dot(a, a) #matrix可以用*符号相乘,但array类型要用dot()方法相乘 print(c) #转置 https://www.runoob.com/numpy/numpy-matrix.html print('转置结果:',c.T)
436a2c4a6fa9bea3d047f03ec7f90fef95100a56
mickey0524/leetcode
/1027.Longest-Arithmetic-Sequence.py
791
3.5
4
# https://leetcode.com/problems/longest-arithmetic-sequence/ # Medium (41.35%) # Total Accepted: 2,953 # Total Submissions: 7,141 # beats 100.0% of python submissions class Solution(object): def longestArithSeqLength(self, A): """ :type A: List[int] :rtype: int """ length = len(A) if length < 3: return length dp = [{} for _ in xrange(length)] res = 2 for i in xrange(1, length): for j in xrange(i): diff = A[i] - A[j] tmp = 1 + dp[j][diff] if diff in dp[j] else 2 dp[i][diff] = tmp if diff not in dp[i] else max(dp[i][diff], tmp) res = max(res, dp[i][diff]) return res
e287aa18bd2068104acb76fbf75c8f819e5f2fef
NicholasDeLateur/DiplomacyAdjudicator
/diplomacy.py
3,573
3.515625
4
from collections import OrderedDict import testImport import diplomacyTests import diplomacyUtilities class Game: def __init__(self): self.name = '' self.powers = dict() #Perhaps could also be called/thought of as the players self.territories = dict() #All the territories in the game, the key is the name of the territory, value is actual object def __repr__(self): return 'String Rep of Game:' \ + self.name + '\n' \ + '\nTerritories:' + '\n' + diplomacyUtilities.makeSortedStringRepOfDict(self.territories) \ + '\n Powers: \n' + diplomacyUtilities.makeSortedStringRepOfDict(self.powers) \ def addPower(self, power_name): power = Power() power.name = power_name self.powers[power_name] = power def createTerritoriesFromList(self,territories_list): for next_territory in territories_list: new_territory = Territory() new_territory.name = next_territory[0] for next_neighbor in next_territory[1]: new_territory.neighbor_names.append(next_neighbor) self.territories[next_territory[0]] =new_territory def createPowersWithUnitsFromList(self,powers_and_units_list): for next_power in powers_and_units_list: new_power = Power() new_power.name = next_power[0] for next_territory in next_power[1]: new_power.territory_names.append(next_territory[0]) if(next_territory[1] != 'None'): new_unit = Unit() new_unit.territory_name = next_territory[0] new_unit.type = next_territory[1] new_power.units.append(new_unit) self.powers[new_power.name] = new_power class Power: def __init__(self): self.name = '' self.territory_names = [] #Just the names of territories currently owned by this power. Is key for looking up territory in game.territories self.units = [] #Units are always owned by a power def addUnit(self, type, territory): unit = Unit() unit.type = type unit.territory = territory def __repr__(self): return self.name + '\n\t' + '\n\t'.join(self.territory_names) +'\n\t' +'\n\t'.join(map(str,self.units)) class Territory: def __init__(self): self.name = '' self.neighbor_names = [] #Names of territories that are neighbors of this territory self.is_a_supply_center = False def __repr__(self): return self.name + '\n\t' + '\n\t'.join(self.neighbor_names) class Unit: def __init__(self): self.territory_name = None #Name of territory this unit is currently in self.order = None self.type = None #Army or fleet are the types def __repr__(self): return self.type + ' in ' + self.territory_name class Order: def _init_(self): self.order_type = None self.move_to = None #If type is move, this is name of territory moving to self.hold_support_target = None #If type is hold support, name of territory that is being supported self.move_support_who_supported = None #If type is move support, name of territory that supported unit is currently in self.move_support_target = None #If type is move support name of territory that supported unit is moving to def main (): testGame = diplomacyTests.createTestGame() print(testGame) testImport.printHello() if __name__ == "__main__": main ()
7c5b41422bec531966e1af2cc877f7f28fdb81b5
jorc-n/python_stack
/python/fundamentals/ciclo_for/main.py
1,827
3.765625
4
# EJERCICIO 1 def biggie_size(lista1): for x in range(len(lista1)): if lista1[x]>0: lista1[x]="big" return lista1 print(biggie_size([0,1,2,4,-4])) #EJERCICIO 2 def cuenta_positivos(lista2): sum=0 for x in range (len(lista2)): if lista2[x]>0: sum+=1 lista2[len(lista2)-1]=sum return lista2 print(cuenta_positivos([0,1,1,1,0])) # EJERCICIO 3 def suma_total(lista3): sum=0 for x in range(len(lista3)): sum=sum+lista3[x] return sum print(suma_total([1,1,1,1,1,1])) print(suma_total([6,3,-2])) # EJERCICIO 4 def promedio(lista4): sum=0 for x in range(len(lista4)): sum=sum+lista4[x] return sum/len(lista4) print(promedio([1,2,3,4])) # EJERCICIO 5 def longitud(lista5): return len(lista5) print(longitud([1,1,1,1,1])) # EJERCICIO 6 def minimo (lista6): if len(lista6)==0: return False min=lista6[0] for x in range(len(lista6)): if lista6[x]<min: min=lista6[x] return min print(min([1,1,0,1,1,1])) print(minimo([37,2,1, -9])) print(minimo([])) # EJERCICIO 7 def maximo (lista7): if len(lista7)==0: return False max=lista7[0] for x in range(len(lista7)): if lista7[x]>max: max=lista7[x] return max print(maximo([37,2,1, -9])) print(maximo([])) # EJERCICIO 8 def analisis_final(lista8): if len(lista8)==0: return False diccionario={} diccionario["sumatotal"]=suma_total(lista8) diccionario["promedio"]= promedio(lista8) diccionario["minimo"]=minimo(lista8) diccionario["maximo"]=maximo(lista8) diccionario["longitud"]=longitud(lista8) return diccionario print(analisis_final([37,2,1,-9])) # EJERCICIO 9 def inverso(lista9): return lista9[::-1] print(inverso([37,2,1,9]))
aac1996807583d2ab4e61897e2be5d6ca4a26931
sumedh151/python-programs
/duck-typing.py
854
3.796875
4
class A_06(): def __init__(self): super().__init__() print("Parent A") class B_06(): def __init__(self): print("Parent B") class C_06(A_06,B_06): def __init__(self): super().__init__() print("Child C") C_06() #duck typing class Class1_06(): def __init__(self,a,b): self.a=a self.b=b def add(self): return self.a+self.b class Class2_06(): def __init__(self,a,b): self.a=a self.b=b def add(self): self.a.append(self.b) return self.a def call(obj): print(obj.add()) x=Class1_06(int(input("Enter number 1 : ")),int(input("Enter number 2 : "))) y=Class1_06(list(input("Enter list 1 : ").split(" ")),list(input("Enter list 2 : ").split(" "))) call(x) call(y) print("\r")
c617bdc3889aaf744ceb329afbee78518c75ca52
SindyPin/Python_Exercises
/7.2_Counting_lines_X-DSPAM.py
967
4.28125
4
# 7.2 Write a program that prompts for a file name, then opens that file and reads through the file, # looking for lines of the form: X-DSPAM-Confidence: 0.8475 # Count these lines and extract the floating point values from each of the lines and compute the average of those values # and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution. # You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter # mbox-short.txt as the file name. Use the file name mbox-short.txt as the file name file_name = input('Enter the name of the file: ') text = open(file_name) data = [] for line in text: line = line.rstrip() if not line.startswith('X-DSPAM-Confidence:'): continue if line.startswith('X-DSPAM-Confidence:'): list1 = float(line[-1]) data.append(list1) average = sum(data)/len(data) print('Average spam confidence: ', average)
a88f2aebfe4644966d62f3e739e19faf9c3cadab
eduardopds/Programming-Lab1
/samu/samu.py
531
3.53125
4
# coding: utf-8 # Aluno: Eduardo Pereira # Matricula: 117210342 # Atividade: Atendimento no Samu soma_atendimentos = 0 lista_atendimentos = [] for m in range(12): n_atendimentos_mes = int(raw_input()) lista_atendimentos.append(n_atendimentos_mes) soma_atendimentos += n_atendimentos_mes media_mensal = soma_atendimentos / 12.0 print'Média mensal de atendimentos: %.2f' % media_mensal print'----' for d in range(len(lista_atendimentos)): if lista_atendimentos[d] > media_mensal: print 'Mês %d: %d' % (d+1,lista_atendimentos[d])
1f74e3c3ed0c3f0258c64528f74d1ef7070902fa
MCreese2/com404
/1-basics/3-decision/7-nested-decision/bot.py
546
4.09375
4
cover_type = input("What type of cover does the book have? ") print(cover_type) if (cover_type == "soft"): bound_type = input("Is the book perfect-bound? ") print(bound_type) if (bound_type == "yes"): print("Soft cover, perfect bound books are very popular!") elif (bound_type == "no"): print("Soft covers with coils or stitches are great for short books") else: print("I'm sorry, the question is yes or no.") elif (cover_type == "hard"): print("Books with hard covers can be more expensive!")
5f209b2b6a60d63de2a78acd2961949879ae81ac
laky/advent_of_code_2020
/advent_of_code_2020_01.py
776
3.5
4
def find_numbers_summing_to(sorted_input_array, number): start = 0 end = len(sorted_input_array)-1 while start < end: sum = sorted_input_array[start] + sorted_input_array[end] if sum == number: return (start, end) elif sum < number: start += 1 else: end -= 1 return None if __name__ == "__main__": with open("input.txt", "r") as f: input_array = [int(line) for line in f.readlines()] input_array.sort() print(len(input_array)) for i1 in range(len(input_array)): ans = find_numbers_summing_to(input_array, 2020-input_array[i1]) if ans != None: i2, i3 = ans print(i1, i2, i3) print(input_array[i1], input_array[i2], input_array[i3]) print(input_array[i1] * input_array[i2] * input_array[i3]) exit(0)
de03af2e7cf488c9ffc1f828e59ec4452ae16cf5
Bhagwati34/Python
/Car_Game.py
661
4.0625
4
cmd = "" start = False stop = False while True: cmd = input("> ").upper() if cmd.upper() == "HELP": print(""" start - to start the car stop - to stop the car quit - to exit """) elif cmd == "START": if start: print("car is already started!") else: start = True print("car started ..... Ready to go!") elif cmd == "STOP": if stop: print("car already stopped!") else: stop = True print("car stopped.") elif cmd == "QUIT": break else: print("I don't understand that ........")
01919716db091fa4a5d4baf98ea476ad32b5770b
kakamband/czech_language_sentiment_analyzer
/flask_webapp/database/conn_local_sqlite.py
719
3.78125
4
""" local sqlite db connection module """ import os import sqlite3 class Connect: """ connect sqlite3 class """ def __init__(self): """ create a database connection to the SQLite database specified by db_file :return: Connection object or sqlite3 error is raised """ self.db_file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'stats.db')) def __repr__(self): return str(self.db_file) def connect(self): """ connect method :return: """ try: conn = sqlite3.connect(self.db_file) except sqlite3.Error as general_err: raise general_err return conn
14a317a0c32c7ebc2e3d73529007f1f9b3352d84
Praveencode-kumar/Pythonlearning
/chapter 10/10.12.py
821
3.953125
4
#Exercise 10.12. import bisect def word_list(file): fin = open(file) li = [] for line in fin: word = line.strip() li.append(word) return li def in_bisect_cheat(word_list, word): """Checks whether a word is in a list using bisection search. Precondition: the words in the list are sorted word_list: list of strings word: string """ i = bisect.bisect_left(word_list, word) if i == len(word_list): return False return word_list[i] == word def reverse_pair(li): list_of_pairs = [] for word in li: if in_bisect_cheat(li, word[::-1]): pair = (word, word[::-1]) list_of_pairs.append(pair) return list_of_pairs li = word_list("words.txt") print(reverse_pair(li))
20d4cbd87b59ae6db733809d4b285142458b8a57
yenchungLin/study
/資料結構與演算法/week2/linked_list.py
3,464
3.984375
4
class Node: def __init__(self, element): self.element = element self.next = None class LinkedList: def __init__(self): self.__head = None self.__tail = None self.__size = 0 #回傳linked_list頭的值 def getHead(self): return self.__head #回傳linked_list尾的值 def getTail(self): return self.__tail #找linked_list頭 def getFirst(self): if self.__size == 0: return None else: return self.__head.element #找linked_list頭 def getLast(self): if self.__size == 0: return None else: return self.__tail.element #加節點在頭 def addFirst(self, e): newNode = Node(e) newNode.next = self.__head self.__head = newNode self.__size += 1 #如果一開始直有頭時 if self.__tail == None: self.__tail = self.__head #加節點在尾 def addLast(self, e): newNode = Node(e) #若尾不存在,頭下一個是新結點 if self.__tail == None: self.__head = self.__tail = newNode #若尾存在,尾的下一個是新節點 else: self.__tail.next = newNode self.__tail = self.__tail.next #size要加1 self.__size += 1 #加節點在中間 def insert(self, index, e): #加在頭 if index == 0: self.addFirst(e) #加在尾 elif index >= self.__size: self.addLast(e) #加在中間 else: current = self.__head for i in range(1, index): current = current.next temp = current.next current.next = Node(e) (current.next).next = temp self.__size += 1 #移除節點在頭 def removeFirst(self): #節點不存在 if self.__size == 0: return None #節點存在 else: temp = self.__head self.__head = self.__head.next self.__size -= 1 if self.__head == None: self.__tail = None return temp.element #移除節點在尾 def removeLast(self): #節點不存在 if self.__size == 0: return None #若只有一個節點 elif self.__size == 1: temp = self.__head self.__head = self.__tail = None self.__size = 0 return temp.element #若很多節點 else: current = self.__head for i in range(self.__size - 2): current = current.next temp = self.__tail self.__tail = current self.__tail.next = None self.__size -= 1 return temp.element def removeAt(self, index): if index < 0 or index >= self.__size: return None # Out of range elif index == 0: return self.removeFirst() # Remove first elif index == self.__size - 1: return self.removeLast() # Remove last else: previous = self.__head for i in range(1, index): previous = previous.next current = previous.next previous.next = current.next self.__size -= 1 return current.element
9affc41c01385ccb52696d1235748fa2b1d3506e
amymareerobinson/cp1404practicals
/prac_09/cleanup_files.py
1,278
3.71875
4
""" CP1404 2020 - Practical 9 Student Name: Amy Robinson Program - Cleanup Files """ import os def main(): """Process all subdirectories using os.walk().""" os.chdir('Lyrics') for directory_name, subdirectories, filenames in os.walk('.'): print("Directory:", directory_name) print("\tcontains subdirectories:", subdirectories) print("\tand files:", filenames) print("(Current working directory is: {})".format(os.getcwd())) for filename in filenames: new_name = get_fixed_filename(filename) print(f"Renaming {filename} to {new_name}") original_name = os.path.join(directory_name, filename) new_name = os.path.join(directory_name, get_fixed_filename(filename)) os.rename(original_name, new_name) def get_fixed_filename(filename): """Return a 'fixed' version of filename.""" empty_string = ' ' filename.replace(" ", "_").replace(".TXT", ".txt") if "_" not in filename: new_name = "_".join(''.join(empty_string + char if char.isupper() else char for char in filename).strip(empty_string).split(empty_string)) else: new_name = "_".join(filename.split("_")).title() return new_name main()
8e9508277eab0857a3d7565a747e989cb12884ea
applepie405/Marcel-s-Python-GUI-Window
/hello-worldj84.py
681
3.9375
4
from tkinter import * root = Tk() root.title("Goal Tracker") # Create and set the message text variable message_text = StringVar() message_text.set("Welcome! You can deposit or withdraw money and see your progress towards your goals.") # Create the message label and add it to the window using pack() message_label = Label(root, textvariable=message_text, wraplength=250) message_label.pack() #Create a PhotoImage() neutral_image = PhotoImage(file="/images/python/neutral.png") #Create a new Label using the PhotoImage and pack it into the GUI image_label = Label(root, image=neutral_image) image_label.pack() # Run the main window loop root.mainloop()
9427e2f4e2020f12328fde324012ceeb109cd2bb
qalp34/100DaysOfCode
/week05/Day32-33.py
329
3.953125
4
for A in range(3, 17): print(A) for B in range(2, 16): print(B) A = [3, 5, 7, 9, 11, 13, 15, 17] B = [2, 4, 6, 8, 10, 12, 14, 16] for x in A: for y in B: print(x, y) A = [3, 5, 7, 9, 11, 13, 15, 17] B = [2, 4, 6, 8, 10, 12, 14, 16] for x in range(3, 18, 2): for y in range(2, 17, 2): print(x, y)
6605e8450fb8fe63276a734157a01ae22c4ed8a8
yughurt1984/Python
/小甲鱼课堂/033/032课后练习0.py
237
3.765625
4
#!usr/bin/env python # -*- coding:utf-8 -*- try: for i in range(3): for j in range(3): if i == 2: raise KeyboardInterrupt print(i, j) except KeyboardInterrupt: print('退出啦')
b739823acc61c7ce847ddf38090230fa6c0b12af
piotrlewandowski/plus_uno
/plus_uno_solver.py
4,339
3.578125
4
import Queue class Plus_uno(): def __init__(self, goal): self.goal = goal def get_start_state(self): return (0,) + (1,) * 8 def is_goal_state(self, state): return state == (self.goal,) * 9 def get_successors(self, state): state = list(state) values = list(set(state)) values.sort() successors = [] for val in values: for val2 in values: new_suc = self.gen_successor(state, (val, val2)) if new_suc: successors.append(new_suc) new_suc = self.gen_successor(state, (val2, val)) if new_suc: successors.append(new_suc) return successors # helper method def gen_successor(self, tiles, move): if sum(move) > self.goal: return new_state = tiles[:] try: new_state.remove(move[0]) new_state.remove(move[1]) new_val = move[0] + 1 new_val2 = move[0] + move[1] new_state.append(new_val) new_state.append(new_val2) new_state.sort() return tuple(new_state), [move] except: return def get_cost_of_actions(self, actions): return len(actions) class Plus_uno2(): def __init__(self, goal): self.goal = goal def get_start_state(self): return (0,) + (1,) * 4 def is_goal_state(self, state): return state == (self.goal-1,) * 4 + (self.goal,) def get_successors(self, state): state = list(state) values = list(set(state)) values.sort() successors = [] for val in values: for val2 in values: new_suc = self.gen_successor(state, (val, val2)) if new_suc: successors.append(new_suc) new_suc = self.gen_successor(state, (val2, val)) if new_suc: successors.append(new_suc) return successors # helper method def gen_successor(self, tiles, move): if sum(move) > self.goal: return new_state = tiles[:] try: new_state.remove(move[0]) new_state.remove(move[1]) new_val = move[0] + 1 new_val2 = move[0] + move[1] new_state.append(new_val) new_state.append(new_val2) new_state.sort() return tuple(new_state), [move] except: return def get_cost_of_actions(self, actions): return len(actions) def null_heuristic(state, problem=None): return 0 # number of things not satisfying goal state / 2 def f_heuristic(state, problem): not_matching = len(filter(lambda x: x != problem.goal, state)) return not_matching / 2 # stuff returned in (state, path) pairs def aStarSearch(problem, heuristic=null_heuristic): closed = set([problem.get_start_state()]) fringe = Queue.PriorityQueue() for successor in problem.get_successors(problem.get_start_state()): state, path = successor cost = problem.get_cost_of_actions(path) + heuristic(state, problem) to_put = (cost, (state, path)) fringe.put(to_put) while not fringe.empty(): _, (state, path) = fringe.get() if problem.is_goal_state(state): print 'states checked: {}'.format(len(closed)) return path if state not in closed: closed.add(state) for successor in problem.get_successors(state): new_state, new_path = successor if new_state in closed: continue new_path = path + new_path cost = problem.get_cost_of_actions(new_path) + heuristic(new_state, problem) to_put = (cost, (new_state, new_path)) fringe.put(to_put) raise Exception('Error: path not found') def main(): for i in range(2,21): print '-' * 40 print 'goal: {}'.format(i) problem = Plus_uno2(i) path = aStarSearch(problem, heuristic=f_heuristic) # add the last 4 moves to the solution path += [(i-1, 1)] * 4 print 'path: {}'.format(path) if __name__ == '__main__': main()
a46677800342014319777cb6dd88ea0ec153380d
qtvspa/offer
/Stack/min.py
1,011
4.15625
4
# -*- coding:utf-8 -*- """ 定义栈的数据结构,请在类型中实现一个能够得到栈最小元素的min函数。""" """ 思路 定义一个辅助栈min用于存放最小元素 """ class Stack(object): def __init__(self): self.data = [] self.min = [] def push(self, num): if not self.data and not self.min: self.data.append(num) self.min.append(num) else: self.data.append(num) if num < self.min_num(): self.min.pop() self.min.append(num) def pop(self): return self.data.pop() def min_num(self): if self.min: return self.min[0] else: return 0 if __name__ == '__main__': obj = Stack() obj.push(3) obj.push(4) obj.push(1) obj.push(5) obj.push(2) print(obj.min_num()) # print(obj.pop()) # print(obj.pop()) # print(obj.pop()) # print(obj.pop()) # print(obj.pop())
6757cbaa08785a966b11a06bc88d5e26159761b3
xpessoles/Informatique_PSI
/01_Recursivite/Cours/programmes/recursivite.py
536
4.15625
4
def fonction_recursive(): return fonction_recursive() #fonction_recursive() def P2_iterative(n): """ Entrée : n(int) Sorite : 2^n """ res = 1 if n==0: return res else : while n>0: res=2*res n=n-1 return res print(P2_iterative(0)) print(P2_iterative(1)) print(P2_iterative(2)) def P2_rapide(n): if n == 0: return 1 if n%2 == 0 : tmp = P2_rapide(n/2) return tmp*tmp else : return (2*P2_rapide(n-1))
786f12ff7854390ef55691e752290d01c4bd35d4
weber81/DailyProgrammerSolutions
/gameOfThrees.py
744
3.734375
4
#E239 def gameOfThrees1(num): while num != 1: print(num, [0, -1, 1][num%3]) num = (num + [0, -1, 1][num%3])//3 print(1) #I239 def gameOfThrees2(num): def gameOfThreesHelper(num, total): #End Case if num < 3: if total%3 == 0: return [(1, "")] else: return None for i in [(0,), (-1, 2), (-2, 1)][num%3]: result = gameOfThreesHelper((num+i)//3, total+i) if result != None: return result + [(num, i)] result = gameOfThreesHelper(num, 0) if result != None: for i in result[::-1]: print(*i) else: print("IMPOSSIBLE") return result
d1a3ac86cb1ac032c49ec43b183cb9c22b61d157
mcoram/var_arguments
/var_arguments.py
8,196
3.515625
4
debug=False # Optionally turn on debug print statements ## To test, use "nosetests -v var_arguments.py" """ """ def recon_dict(dictToImitate,dictWithValues): """ recon_dict is for the case when you have one dictionary that holds old values for all the keys that you're interested in, and another dictionary that holds the new values for all those keys (as well as possibly others that you don't want) """ return dict( (k,dictWithValues[k]) for k in dictToImitate.keys() ) def test_recon_dict_1(): xyab=dict(x=1,y=2,a=3,b=4) assert recon_dict(dict(a=8,b=9),xyab)==dict(a=3,b=4) def test_recon_dict_2(): old_d=dict(a=8,b=9) # I want these keys, but they're old values xyab=dict(x=1,y=2,a=3,b=4) # These are the new values, but I don't want all of them new_d=recon_dict(old_d,xyab) assert new_d==dict(a=3,b=4) def ddict(varstr,yourlocals,sep=','): """ Select the subset of a dictionary corresponding to the keys named in a string example: ddict('a,c',dict(a=1,b=2,c=3))==dict(a=1,c=3) note: interesting when applied to a dictionary of the callers local variables example: def foo(c): a=c-2;b=2 return ddict('a,c',locals()) assert foo(3) == dict(a=1,c=3) """ return dict( (k,yourlocals[k]) for k in varstr.split(sep) ) def test_ddict_1(): assert ddict('a,c',dict(a=1,b=2,c=3))==dict(a=1,c=3) def test_ddict_2(): def foo(c): a=c-2;b=2 return ddict('a,c',locals()) assert foo(3) == dict(a=1,c=3) def dcall(f,varstr,yourlocals): """ Let's you change: f(x=x,y=y) into: dcall(f,'x,y',locals()) """ return f(**ddict(varstr,yourlocals)) def test_dcall_1(): def f(a=None,b=None,c=None): assert a==1 and c==3 and b==None a=1;b=2;c=3 dcall(f,'a,c',locals()) def lddict(varstr,dictlist,sep=','): """ Suppose you have dicts xy=dict(x=1,y=2) and ab=dict(a=3,b=4). And that what you would normally write is: dict(x=xy['x'],b=ab['b']) in order to get dict(x=1,b=4), in this case. Now you can write: lddict('x,b',[xy,ab]), to get the same result """ varl=varstr.split(sep) revdlist=dictlist[:] revdlist.reverse() result={} for k in varl: found=False for d1 in revdlist: if d1.has_key(k): result[k]=d1[k] found=True break if not found: raise KeyError(k) return result def test_lddict_1(): xy=dict(x=1,y=2) ab=dict(a=3,b=4) answer=dict(x=xy['x'],b=ab['b']) assert answer==dict(x=1,b=4) assert answer==lddict('x,b',[xy,ab]) x=5 assert lddict('x,b',[xy,ab,locals()]) == dict(x=5,b=4) try: lddict('z,b',[xy,ab]) except KeyError, e: None # Expected; there's no z else: assert False def ldcall(f,varstr,dictlist): """ Suppose you have a dictionary xy with keys x and y and local variables a and b, then we can change: f(x=xy['x'],y=xy['y'],a=a,b=b) into: ldcall(f,'x,y,a,b',[locals(),xy]) (If keys are defined in multiple dictionaries, the behavior will be that the later dictionaries override the former; make sure that's what you want.) """ return f(**lddict(varstr,dictlist)) def test_ldcall(): def f(x,y,a,b): assert x==1 and y==2 and a==3 and b==4 xy=dict(x=1,y=2) x=None # should be overridden a=3;b=4 f(x=xy['x'],y=xy['y'],a=a,b=b) ldcall(f,'x,y,a,b',[locals(),xy]) ldcall(f,'x,a,y,b',[locals(),xy]) def use_dargs(f): """ Decorator that allows a function to accept arguments via an optional dargs keyword argument that, if present, must be a list of dictionaries. The key value pairs in those dictionaries will appear as regular arguments to the decorated function. If you want this trick to work when you pass, e.g. dargs=[locals()], or, generally, if the dictionaries in the dargs list have extra keys that are not arguments of f, write f to accept **kwargs as an argument. """ def f_new(*pargs,**kwargs): dargs=kwargs.get('dargs',None) if dargs!=None: nargs={} if debug: print 'dargs==%r'%dargs for d in dargs: nargs.update(d) del kwargs['dargs'] nargs.update(kwargs) # let keyword arguments override even the dargs dictionaries return f(*pargs,**nargs) else: return f(*pargs,**kwargs) return f_new def test_use_dargs_1(): def fA(x,y,a,b): assert x==1 and y==2 and a==3 and b==4 return x+a def fB(x,y,a,b,**kwargs): assert x==1 and y==2 and a==3 and b==4 return x+a assert use_dargs(fA)(1,2,3,4) == 4 #1A assert use_dargs(fB)(1,2,3,4) == 4 #1B xy=dict(x=1,y=2) ab=dict(a=3,b=4) assert use_dargs(fA)(dargs=[xy,ab]) == 4 #2A assert use_dargs(fB)(dargs=[xy,ab]) == 4 #2B y=2 bd={'b':4} try: assert use_dargs(fA)(1,a=3,dargs=[locals(),bd]) == 4 #3A except TypeError: None ## A TypeError that complains "got an unexpected keyword argument 'bd'" is expected else: assert False assert use_dargs(fB)(1,a=3,dargs=[locals(),bd]) == 4 #3B #for 1 and 2, it suffices that f has dargs as a keyword argument. #for 3, f will receive the other locals too, like bd, so in order that it ignore # such extra arguments, it's necessary that f accept general **kwargs. # To test precedence overriding, let the locals and ab have extraneous values for a # the intended result is that the "a=3" in the call takes precedence ab['a']=7 a=8 yd={'y':2} assert use_dargs(fA)(1,a=3,dargs=[yd,ab])==4 assert use_dargs(fB)(1,a=3,dargs=[locals(),ab])==4 # Here we're testing that the value for a should come from ab ab['a']=3 assert use_dargs(fB)(1,dargs=[yd,ab])==4 assert use_dargs(fB)(1,dargs=[locals(),ab])==4 def dict_return(f): """ Decorator that composes the function with a call to lddict. """ def f_new(*pargs,**kwargs): varstr,yourdicts=f(*pargs,**kwargs) return lddict(varstr,yourdicts) return f_new def test_decorators(): def myfunc_mundane(x,y,a,b): y=x+a return dict(x=x,y=y,a=a,b=b) answer=myfunc_mundane(1,2,3,4) assert answer==dict(x=1,y=4,a=3,b=4) @dict_return @use_dargs def myfunc(x,y,a,b): y=x+a return 'x,y,a,b',[locals()] ab={'a':3,'b':4} xy={'x':1,'y':2} assert myfunc(1,2,3,4) == answer assert myfunc(1,2,dargs=[ab]) == answer assert myfunc(dargs=[ab,xy]) == answer assert myfunc(dargs=[xy,ab]) == answer justb={'b':4} assert myfunc(a=3,dargs=[xy,justb]) == answer def test_stack_overflow_solution(): def f_mundane(d1,d2): x,y,a,b = d1['x'],d1['y'],d2['a'],d2['b'] y=x+a return {'x':x,'y':y}, {'a':a,'b':b} def f(d1,d2): r=f2(dargs=[d1,d2]) return recon_dict(d1,r), recon_dict(d2,r) @use_dargs def f2(x,y,a,b): y=x+a return locals() xy=dict(x=1,y=2) ab=dict(a=3,b=4) answer_xy, answer_ab=f_mundane(xy,ab) assert answer_xy==dict(x=1,y=4) assert answer_ab==dict(a=3,b=4) res_xy, res_ab = f(xy,ab) assert res_xy==answer_xy assert res_ab==answer_ab answer=dict(x=1,y=4,a=3,b=4) assert f2(1,2,3,4)==answer assert f2(1,a=3,dargs=[dict(y=2,b=4)])==answer assert f2(dargs=[dict(x=1,y=2),dict(a=3,b=4)])==answer def experimental_idiom(f): return dict_return(use_dargs(f)) def test_experimental_idiom(): @experimental_idiom def f1(u): z=u+5 x=z+5 y=z+6 xz=ddict('x,z',locals()) return 'x,y,xz',[locals()] @experimental_idiom def f2(a,u,y,**kwargs): a=(u-1)*y return 'a,y',[locals()] d1=dict(u=0) d2=f1(dargs=[d1]) d3=f2(a=7,dargs=[d1,d2]) __all__=["recon_dict", "ddict", "lddict", "dcall", "ldcall", "use_dargs", "dict_return","experimental_idiom"]
9b5dd06ee8399a575ccf54d1b3c9503c99e83320
isaacmartin1/Texas_Financial_Derivatives
/Week_3_Cirriculum.py
802
3.5625
4
#!/usr/bin/env python # coding: utf-8 # In[4]: #import library import numpy as np #set assumptions #counter i = 0 #standard deviation each day sigma = .00302 #list prices will be stored in l = [] #list #stock price p = 112 while i < 100: p = np.random.normal(1, sigma) * p l.append(p) i += 1 print(l) # In[17]: #import library import numpy as np import matplotlib.pyplot as plt #set assumptions #counter i = 0 #standard deviation each day sigma = .00302 #list prices will be stored in l = [] #time will be stored in #needed to set up x axis for graphing t = [] #stock price p = 112 while i < 100: p = np.random.normal(1, sigma) * p l.append(p) i += 1 t.append(i) plt.plot(t, l) plt.show() print(l) # In[ ]: # In[ ]:
56e516243aaf85e49f08890c2ebf20cde9157c97
A01377230/Mision-03
/RendimientoDeUnAuto.py
1,158
3.9375
4
#Jesús Roberto Herrera Vieyra // A01377230 #Programa para calcular el rendimiento de un auto #función para calcular el rendimiento del coche def calcularrendimiento(kilometros,litros): rendimiento= kilometros/litros return rendimiento #función para convertir a millas/galones def convertirUnidades(kilometros,litros): millas = kilometros/1.6093 galones = litros*0.264 rendimiento = millas/galones return rendimiento #Procedimiento principal def main(): kilometros= int(input("Teclea el número de km recorridos: ")) litros= int(input("Teclea el número de litros de gasolina usados: ")) rendimiento = calcularrendimiento(kilometros,litros) conversion = convertirUnidades(kilometros,litros) print("Si recorres %d km con %d litros de gasolina, el rendimiento es: " %(kilometros,litros)) print("{0:.2f}".format(rendimiento),"km/l") print("{0:.2f}".format(conversion),"mi/gal") distancia = int(input("¿Cuántos kilómetros vas a recorrer? ")) litrosNecesarios = distancia/rendimiento print("Para recorrer ",distancia," km. Necesitas ","{0:.2f}".format(litrosNecesarios)," litros de gasolina") main()
eb1f4366a9e8c26643834183758243d7da67fd0b
dlingerfelt/DSC-510-Fall2019
/Steen_DSC510/Assignment 9.1 - Jonathan Steen.py
3,371
4.4375
4
# File: Assignment 9.1 - Jonathan Steen.py # Name: Jonathan Steen # Date: 2/7/2020 # Course: DSC510 - Introduction to Programing # Desc: Program will open a file, calculate the total words, # the total occurrences of each word and print to screen and file # Usage: The program will count total words and occurrences of each word. import string def processLine(line, fileDictionary): #function to process each line of file line = line.translate(line.maketrans('', '', string.punctuation)) #strip punctuation line = line.lower() #convert to lower words = line.split() #split out words addWord(words, fileDictionary) #call addWord function def addWord(words, fileDictionary): #function to add words for word in words: #for statement to get the count if word in fileDictionary: fileDictionary[word] += 1 else: fileDictionary[word] = 1 def prettyPrint(fileDictionary): #function to format and display output print('Length of the dictionary: ', len(fileDictionary)) cols = ['Word', 'Count'] #colum headers print("{:>0}\t{:>15}".format(*cols)) print('------------------------') for key, value in sorted(fileDictionary.items(), key=lambda kv: kv[1], reverse=True): #sort by frequency print("{:15}\t{:6}".format(key, fileDictionary[key])) def process_file(newFile, fileDictionary): total = 0 for word in fileDictionary: total += 1 # open and write to file output=open(newFile,'a') output.write('Length of the dictionary:\n\n' + str(len(fileDictionary)) + '\n') cols = ['\nWord', 'Count\n'] #colum headers output.write("{:>0}\t{:>15}".format(*cols)) output.write('------------------------') for key, value in sorted(fileDictionary.items(), key=lambda kv: kv[1], reverse=True): #sort by frequency output.write("\n{:15}\t{:6}".format(key, fileDictionary[key])) print("\n\nText file has been created.") output.close() # close file def main(): try: try: gba_file = open('gettysburg.txt', 'r') fileDictionary = dict() try: # get input from user and check for illegal characters and incorrect extension fileName = input('Please input a filename. \n') fileName = fileName.lower() fileExtentsion = fileName[-4:] correctExtentsion = '.txt' illegalCharacters = '<>:"/\|?*' if fileExtentsion not in correctExtentsion: raise Exception() elif illegalCharacters in fileName: raise Exception() elif fileName[+4] in {''} == True: raise Exception() newFile = open(fileName, 'w') for line in gba_file: processLine(line, fileDictionary) prettyPrint(fileDictionary) process_file(fileName, fileDictionary) except: print('Invalid filename. \nPlease enter "filename".txt.\nDo not include illegal charcters, "<>:"/\|?*"\n') except: print('Error opening file.') except: print('Something went wrong.') if __name__ == '__main__': main()
64810bb844c3bbfc48a731e0ddddfe9c2e7b5c79
power3lectronics/orgDesc
/ordenaCresc.py
740
4.0625
4
def crescSort(list1,list2): print ("Num original: "+str(list1)) print ("Letter original: "+str(list2)) print('\n') flag = True while (flag): flag = False for i in range(len(list1)-1): if (list1[i] > list1[i+1]): aux1 = list1[i+1] list1[i+1] = list1[i] list1[i] = aux1 aux2 =list2[i+1] list2[i+1] = list2[i] list2[i] = aux2 flag = True print ("Nums sorted: "+str(list1)) print ("Letters sorted: "+str(list2)) list11=[1245,456033,7,1,345,15,20,0] list22=['a','b','c','d','e','f','g','h'] crescSort(list11,list22)
53d1066f69815df7038dba8ea6b3ac05e88e10bb
pisskidney/leetcode
/algorithms/nqueens.py
841
3.703125
4
#!/usr/bin/python ''' Print all the ways you can fit n queens onto a nxn chess board ''' c = 0 def nqueens(n): solve([], n) def solve(sol, n): if len(sol) == n: global c c += 1 show(sol) return for i in xrange(n): if noattacks(sol + [i]): sol.append(i) solve(sol, n) sol.pop() def noattacks(board): if len(set(board)) < len(board): return False for i in xrange(len(board)): for j in xrange(i + 1, len(board)): if abs(i-j) == abs(board[i]-board[j]): return False return True def show(sol): row = ['.' for _ in xrange(len(sol))] for i in xrange(len(sol)): row[sol[i]] = 'Q' print ''.join(row) row[sol[i]] = '.' print '-' * 20 nqueens(8) print c
cbc3360a3702179319a26d7b6298d707d6dfb1b6
Stl36/python-base-gb
/lesson_8/task1.py
1,910
3.71875
4
""" Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год». В рамках класса реализовать два метода. Первый, с декоратором @classmethod. Он должен извлекать число, месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, должен проводить валидацию числа, месяца и года (например, месяц — от 1 до 12). Проверить работу полученной структуры на реальных данных. """ class MyDate: def __init__(self, date): self.date = date @staticmethod def chek_date(param): if "2021" >= param[6:10] >= "1900": mouth = param[3:5] if ((mouth[:1] == "1") and ("12" >= mouth >= "10")) or ((mouth[:1] == "0") and ("9" >= mouth[1:] >= "1")): day = param[:2] if (("1" <= day[:1] <= "9") and (day[:1] == "0")) or (("1" <= day[:1] <= "3") and ("10" <= day <= "31")): return True return False @classmethod def int_date(cls, param): if MyDate.chek_date(param): return int(param[:2]), int(param[3:5]), int(param[6:]) else: raise ValueError("Неверный формат даты. Формат должен быть день-месяц-год, например 01-02-1990") hb_vasya = MyDate("28-03-1992") hb_petya = "13-08-1992" hb_vi = "10-33-2021" print(hb_vasya.date) print(MyDate.chek_date(hb_vasya.date)) print(MyDate.chek_date(hb_vi)) print(MyDate.int_date(hb_vasya.date)) print(MyDate.int_date(hb_petya)) print(MyDate.int_date(hb_vi))
89e43df0751f153e5d24acd6b2aa90fbeb0354cb
TaniaBladier/nlp-project-similar-lyrics
/code/lyrics_sentiment.py
6,905
3.84375
4
"""This module analyses a song's sentiment and based on that finds similar songs. Functions: The following function can be used without an XML tree: song_polarity(string) -> float The following functions can only be used with an XML tree: query_sentiment(string, string, xml.etree.ElementTree.Element) -> string pos_minimum_difference(xml.etree.ElementTree.Element, float, xml.etree.ElementTree.Element) -> xml.etree.ElementTree.Element neg_minimum_difference(xml.etree.ElementTree.Element, float, xml.etree.ElementTree.Element) -> xml.etree.ElementTree.Element similar_sentiment(xml.etree.ElementTree.Element, xml.etree.ElementTree.Element) -> string query_get_song_recommendation(string, string, xml.etree.ElementTree.Element) -> string """ from textblob import TextBlob import song_information def song_polarity(lyrics): """Calculates the polarity of the lyrics. Args: lyrics: A string containing the lyrics of a song. Returns: A float representing the polarity value of the lyrics. """ lines = lyrics.split('\n') polarity_analysis = 0 count = 0 for line in lines: polarity_analysis += TextBlob(line).polarity count += 1 result = polarity_analysis/count return result def query_sentiment(songtitle, artist, root): """Evaluates the requested songs sentiment. Args: songtitle: A string containing a song name. artist: A string containing the artist of the song. root: The root of the ElementTree. Returns: A string message including whether the requested song has a negative, positive or neutral sentiment. """ for child in root: if (song_information.get_songtitle(child) == songtitle and song_information.get_artist(child) == artist): song = child lyrics = song_information.get_lyrics(song) polarity = song_polarity(lyrics) songtitle = song_information.get_songtitle(root, lyrics) artist = song_information.get_artist(root, lyrics) if polarity < 0: result = ("The sentiment of '" + songtitle + "' by " + artist + " is negative") elif polarity > 0: result = ("The sentiment of '" + songtitle + "' by " + artist + " is positive") else: result = ("The sentiment of '" + songtitle + "' by " + artist + " is neutral") return result def pos_minimum_difference(song, polarity, root): """Calculates which song has the most similar polarity to the passed polarity. Args: song: A child of an ElementTree. polarity: A positive float which represents the polarity of the song to which the song with the most similar polarity is wanted. root: The root of the ElementTree which has the child song. Returns: The child of the XML tree in which the song with the most similar polarity to the passed polarity is stored. """ minimum = 10.0 # A number which is higher than the polarity values for child in root: if child != song: lyrics_child = song_information.get_lyrics(child) polarity_child = song_polarity(lyrics_child) if polarity_child > 0: difference = polarity - polarity_child if abs(difference) < minimum: minimum = abs(difference) minimum_song = child return minimum_song def neg_minimum_difference(song, polarity, root): """Calculates which song has the most similar polarity to the passed polarity. Args: song: A child of an ElementTree. polarity: A negative float which represents the polarity of the song to which the song with the most similar polarity is wanted. root: The root of the ElementTree which has the child song. Returns: The child of the XML tree in which the song with the most similar polarity to the passed polarity is stored. """ minimum = 10.0 # A number which is higher than the polarity values for child in root: if child != song: lyrics_child = song_information.get_lyrics(child) polarity_child = song_polarity(lyrics_child) if polarity_child < 0: difference = abs(polarity - polarity_child) if abs(difference) < minimum: minimum = abs(difference) minimum_song = child return minimum_song def similar_sentiment(song, root): """Finds the song with the most similar polarity to the requested song from all songs stored in an XML corpus. Args: song: A child of an ElementTree. root: The root of the ElementTree which has the child song. Returns: A string containing the song with the most similar polarity to the passed song. """ lyrics = song_information.get_lyrics(song) polarity = song_polarity(lyrics) if polarity > 0: similar_song = pos_minimum_difference(song, polarity, root) result = ("'" + song_information.get_songtitle(similar_song) + "' by " + song_information.get_artist(similar_song)) elif polarity < 0: similar_song = neg_minimum_difference(song, polarity, root) result = ("'" + song_information.get_songtitle(similar_song) + "' by " + song_information.get_artist(similar_song)) return result def query_get_song_recommendation(songtitle, artist, root): """Recommends the song with the most similar sentiment to the requested song. Args: songtitle: A string containing a song name. artist: A string containing the artist of the song. root: The root of the ElementTree. Returns: A string message including which song has a similar mood to the requested song. """ for child in root: if (song_information.get_songtitle(child) == songtitle and song_information.get_artist(child) == artist): song = child lyrics = song_information.get_lyrics(song) polarity = song_polarity(lyrics) if polarity > 0: similar_song = pos_minimum_difference(song, polarity, root) result = ("'" + song_information.get_songtitle(similar_song) + "' by " + song_information.get_artist(similar_song) + " has a similiar mood to '" + songtitle + "' by " + artist) elif polarity < 0: similar_song = neg_minimum_difference(song, polarity, root) result = ("'" + song_information.get_songtitle(similar_song) + "' by " + song_information.get_artist(similar_song) + " has a similiar mood to '" + songtitle + "' by " + artist) return result
fd842c98cc73ea79f0538ab7a40de7ce1df46558
Andmontc/holbertonschool-higher_level_programming
/0x0B-python-input_output/13-student.py
715
3.59375
4
#!/usr/bin/python3 """ Class Student """ class Student: """ Class Student init """ def __init__(self, first_name, last_name, age): """ init of the class """ self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """ dictionary from Student""" data = {} obj = self.__dict__ if attrs is not None: for x in attrs: if x in obj: data[x] = obj[x] return data else: return obj def reload_from_json(self, json): """ Reload attributes""" for key in json: setattr(self, key, json[key])
a5550ed41b540a72dde2a119d2c8256482cfbe47
DongjiY/Kattis
/src/tripletexting.py
228
3.9375
4
phrase = input() interval = int(len(phrase)/3) one = phrase[0: interval] mid = phrase[interval:-interval] end = phrase[-interval:] if one == end or one == mid: correctword = one else: correctword = mid print(correctword)
3a81d673c80348823e6c5d7502ff84ecbde36974
skhlivnenko/Python
/rename_files.py
211
3.78125
4
def rename_files(): #1 get file names from the folder file_list = os.listdir("/Users/Sergii/Documents/Python_Udacity/prank") print (file_list) #2 for each file, rename the file rename_files()
ff6a2ad8851cb7e72fb6ff359beade6106bad12d
hanxinxue/python1-0120
/venv/learn1.py
1,078
4.09375
4
# -*- coding: utf-8 -*- # Quick python script explanation for programmers import os #导入模块 def main(): #函式名 print ("Hello world") #python最好也最个性的语法:使用缩进代替语句块声明 print ("这是Alice\'的问候.") print ('这是Bob\'的问候') foo(5,10) print ('=' * 10) print ('这将直接执行'+os.getcwd()) counter = 0 counter += 1 food = ['apple','banana','pear','mengo'] for i in food: print ('I realy like integer:'+i) print ('count to 10') for i in range(10): print (i) def foo(param1, secondParam): res = param1+secondParam print ('%s plus %s equals to %s'%(param1, secondParam, res)) if res < 50: print ('this one') elif (res>=50)and((param1==42)or(secondParam==24)): print ('that one') else: print ('en...') return res '''多行注释的内容不用遵守当前缩进格式,只要开始的三撇缩进格式正确即可''' if _name_=='_main_': main()
c190d94f520498a5c42c7e73a7856086063a1b50
MapRantala/Blog
/python/python/20100516_MeasureDistanceFromPointToLine/dist_point_to_line.py
1,314
3.78125
4
# A python implementation of Paul Bourke's algorythm for calculating the distance from a point to a # line. # # Originally posted at http://www.maprantala.com def lineMagnitude (x1, y1, x2, y2): lineMagnitude = math.sqrt(math.pow((x2 - x1), 2)+ math.pow((y2 - y1), 2)) return lineMagnitude #Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline). def DistancePointLine (px, py, x1, y1, x2, y2): #http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba LineMag = lineMagnitude(x1, y1, x2, y2) if LineMag < 0.00000001: DistancePointLine = 9999 return DistancePointLine u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1))) u = u1 / (LineMag * LineMag) if (u < 0.00001) or (u > 1): #// closest point does not fall within the line segment, take the shorter distance #// to an endpoint ix = lineMagnitude(px, py, x1, y1) iy = lineMagnitude(px, py, x2, y2) if ix > iy: DistancePointLine = iy else: DistancePointLine = ix else: # Intersecting point is on the line, use the formula ix = x1 + u * (x2 - x1) iy = y1 + u * (y2 - y1) DistancePointLine = lineMagnitude(px, py, ix, iy) return DistancePointLine
482d34b840b62edc493f39ea604f2e195e6c2d0b
panchoSalsa/ScannerAndParser
/parser.py
5,476
3.71875
4
import sys class Parser: def __init__(self, scanner): self.scanner = scanner def error(nonterminal): print("self.error: not a valid " + "<" + nonterminal + ">") sys.exit() def printAll(self): self.scanner.getNextToken() while self.scanner.moreTokens(): print(self.scanner.getToken()) self.scanner.getNextToken() def program(self): print("Program") while self.statement(): continue def statement(self): print("Statement") if self.set(): return True elif self.jump(): return True elif self.jumpt(): return True elif self.halt(): return False else: self.error("Statement") def jump(self): if self.scanner.getToken() == "jump": print("Jump") self.scanner.getNextToken() return self.expression() else: return False def jumpt(self): if (self.scanner.getToken() == "jumpt"): print("Jumpt") self.scanner.getNextToken() if not self.expression(): self.error("Jumpt") if (self.scanner.getToken() == ","): self.scanner.getNextToken() if not self.expression(): self.error("Jumpt") if self.equalitiesCheck(): self.scanner.getNextToken() if not self.expression(): self.error("Jumpt") else: self.error("Jumpt") else: self.error("Jumpt") return True else: return False def equalitiesCheck(self): token = self.scanner.getToken() if token == "<" or token == "<=" or token == ">" or token == ">=": return True elif token == "==" or token == "!=": return True else: return False def expression(self): print("Expr") truth = self.term() while self.termCheck(): truth = self.term() continue return truth def termCheck(self): if self.scanner.getToken() == "+" or self.scanner.getToken() == "-": self.scanner.getNextToken() return True else: return False def term(self): print("Term") truth = self.factor() while self.factorCheck(): truth = self.factor() continue return truth def factorCheck(self): if self.scanner.getToken() == '*' or self.scanner.getToken() == '/' or self.scanner.getToken() == '%': self.scanner.getNextToken() return True else: return False def factor(self): print("Factor") # the problem is here with the 5 followed by the comma, # sets if number to false if self.number(): print("Number") return True elif self.scanner.getToken() == 'D': temp = self.scanner.peekNextToken() if temp == '[': # the token matches so consume the char '[' self.scanner.getNextToken() # call getNextToken one more time to advance to digit between '0..9' self.scanner.getNextToken() if not self.expression(): self.error("Factor") if self.scanner.getToken() == ']': # we have matched with D[<Expr>] self.scanner.getNextToken() return True else: self.error("Factor") else: self.error("Factor") return True elif self.scanner.getToken() == '(': self.scanner.getNextToken() self.expression() if self.scanner.getToken() == ')': # we have matched with (<Expr>) self.scanner.getNextToken() return True else: self.error("Factor") else: return False def number(self): if self.scanner.getToken().isdigit(): if self.scanner.getToken() == '0': self.scanner.getNextToken() else: self.scanner.getNextToken() self.pullAllNumbers() return True else: return False def pullAllNumbers(self): while self.scanner.getToken().isdigit(): self.scanner.getNextToken() def set(self): if self.scanner.getToken() == "set": print("Set") self.scanner.getNextToken() if self.scanner.getToken() == "write": self.scanner.getNextToken() else: if not self.expression(): self.error("Set") if self.scanner.getToken() == ",": self.scanner.getNextToken() if self.scanner.getToken() == "read": self.scanner.getNextToken() else: if not self.expression(): self.error("Set") else: self.error("Set") return True else: False def halt(self): return self.scanner.getToken() == "halt"
a8fd9d4864c94cdb6f9a191d37f4304c29702073
erikfsk/matin1105
/rec_test.py
86
3.5625
4
def f(x): if x <= 0: return 1 return x*f(x-1) for i in range(10): print(i,f(i))
6a4c676cc5677aa5f88e7028c8501f6af8b400f1
chrisjd20/python_powershell_aes_encrypt_decrypt
/aes.py
1,183
3.859375
4
from Crypto import Random from Crypto.Cipher import AES import hashlib class cryptor: """ Encrypt and Decrypt Data/Strings via AES in Python Example Usage: from aes import cryptor cipher = cryptor('Really Strong Key') encrypted = cipher.encrypt('Hello World!') decrypted = cipher.decrypt(encrypted) print encrypted print decrypted """ def __init__( self, key ): H = hashlib.sha1(); H.update(key) self.pad = lambda self, s: s + (self.BS - len(s) % self.BS) * "\x00" self.unpad = lambda self, s : s.rstrip('\x00') self.toHex = lambda self, x:"".join([hex(ord(c))[2:].zfill(2) for c in x]) self.BS = 16 self.key = H.hexdigest()[:32] def encrypt( self, raw ): raw = self.pad(self, raw) iv = Random.new().read( AES.block_size ) cipher = AES.new( self.key, AES.MODE_CBC, iv ) return self.toHex(self, iv + cipher.encrypt( raw ) ) def decrypt( self, enc ): enc = (enc).decode("hex_codec") iv = enc[:16] cipher = AES.new(self.key, AES.MODE_CBC, iv ) return self.unpad(self, cipher.decrypt( enc[16:] ))
68542d414c48f190a05c4d7bbcf443bb62a24285
Gorjachka/Learning
/My_pygame.py
1,011
3.640625
4
import pygame WHITE = (255, 255, 255) ORANGE = (255, 150, 100) PURPLE = (128, 0, 128) BLUE = (0, 0, 255) pygame.init() gameDisplay = pygame.display.set_mode((800, 600)) pygame.display.set_caption("My first game") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # -------- Main Program Loop ----------- while not done: # --- Main event loop for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop # --- Game logic should go here # --- Drawing code should go here # First, clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. gameDisplay.fill(BLUE) # --- Go ahead and update the screen with what we've drawn. pygame.display.update() # --- Limit to 60 frames per second clock.tick(60)
346b2f42fe80cd9d1dd4c69475de9ea48bd68cdc
JohnCDunn/Course-Work-TTA
/Python/PythonInADay2/CSV-Files-Drill/37of79-8.py
738
3.578125
4
import os, csv # The path to the script currentPath = os.path.dirname( os.path.abspath("__file__")) print currentPath # Make the spreadsheet path outputCsv = currentPath + '/spreadsheet.csv' print outputCsv # Open the file csvFile = open(outputCsv, "wb") # Create writer object writer = csv.writer(csvFile, delimiter=',') # data to go into csv row_1 = [1, "Row 1", 123] row_2 = [2, "Row 2", 456] row_3 = [3, "Row 3", 789] rows = [row_1, row_2, row_3] # loop through rows and write them for row in rows: writer.writerow(row) # Result from above # C:\Users\Student\Documents\All My Essays\Python # C:\Users\Student\Documents\All My Essays\Python/spreadsheet.csv # on spreadsheet #1 Row_1 123 #2 Row_2 456 #3 Row_3 789
54f247d1fcd3856002b06ecc181cb506e02d58bd
AyoungYa/Leetcode_in_python
/leetcode/pascal_trangle_ii.py
637
4.03125
4
#! -*- encoding: utf-8 -*- """ Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? """ class Solution: def getRow(self, rowIndex): ans = [1] if not rowIndex: return ans elif rowIndex == 1: return [1, 1] else: ans = [1] for i in xrange(1, rowIndex): ans.append(ans[i-1] * (rowIndex-i+1)/i) ans.append(1) return ans if __name__ == "__main__": s = Solution() print s.getRow(3)
2d7960bccfeec8165641e0687a4423274aca69c6
owenxu10/LeetCode
/old/17.py
999
3.53125
4
class Solution(object): phone = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } def LetterCombination(self, num): result = [] new_result = [] for i in range(0, len(num)): if int(num[i]) > 1: if len(result) > 0: for j in range(0, len(result)): prefix = result.pop() curValue = self.phone[num[i]] for k in range(0, len(curValue)): new_result.append(prefix + curValue[k]) result = new_result new_result = [] else: curValue = self.phone[num[i]] for j in range(0, len(curValue)): result.append(curValue[j]) return result s = Solution() print(s.LetterCombination('12302'))
b57076c1a2d822fb1d3ad9925df1eb9048aacbe0
c4rl0sFr3it4s/Python_Basico_Avancado
/script_python/media_duas_notas_aluno_040.py
618
3.640625
4
'''entre com duas notas de um aluno calcule a media e mostre no final de acordo com a média abaixo de 5.0 reprovado, entre 5.0 e 6.9 recuperacao, 7.0 ou superior aprovado''' nota_01 = float(input('Digite a nota 01: ')) nota_02 = float(input('Digite a nota 02: ')) media = (nota_01 + nota_02 ) / 2 print(f'Com a média \033[1;34m{media:.1f}\033[m seu status é, ', end='') #\033[m cor, :.1f com 1 casa depois da vírgula if media < 5.0: print('\033[1;31mReprovado.\033[m ') elif 5.0 >= media <= 6.9: print('\033[1;33mRecuperação.\033[m ') else: print('\033[1;34mAprovado.\033[m ') print('{:-^40}'.format('FIM'))
d88b798bc14a702f2f31bf94355b9461c18fa5e8
KosmKos/CLRS.jupyter
/Chapter_02_Getting_Started/2.3-2.py
1,002
3.640625
4
import random import unittest def merge_sort_sub(arr, lt, rt): if lt >= rt: return mid = (lt + rt) // 2 merge_sort_sub(arr, lt, mid) merge_sort_sub(arr, mid + 1, rt) arr_l = [arr[i] for i in range(lt, mid + 1)] arr_r = [arr[j] for j in range(mid + 1, rt + 1)] i, j = 0, 0 for k in range(lt, rt + 1): if j == len(arr_r) or (i != len(arr_l) and arr_l[i] <= arr_r[j]): arr[k] = arr_l[i] i += 1 else: arr[k] = arr_r[j] j += 1 def merge_sort(arr): merge_sort_sub(arr, 0, len(arr) - 1) class MergeSortTestCase(unittest.TestCase): def random_array(self): return [random.randint(0, 100) for _ in range(random.randint(1, 100))] def test_random(self): for _ in range(10000): arr = self.random_array() sorted_arr = sorted(arr) merge_sort(arr) self.assertEqual(arr, sorted_arr) if __name__ == '__main__': unittest.main()
4c3cf07af628832fd64abd84621307c12ff88705
duxuhao/Chinese_University_Entrance_Ranking_GD
/UniversityclusterLabel.py
2,334
3.59375
4
# -*- coding: utf-8 -*- #combine the university score of different year to the original dataset import pandas as pd from sklearn import cluster import matplotlib.pyplot as plt import numpy as np df1 = pd.read_csv("Produce_Data/UniversityData.csv") df1['Average_Ranking'] = pd.Series(np.zeros(len(df1)),index=df1.index) df1['Last_Ranking'] = pd.Series(np.zeros(len(df1)),index=df1.index) df1.Topic[df1.Topic == "理科"] = 1 df1.Topic[df1.Topic == "文科"] = 0 UniNoList = df1.UniversityNo.unique() #obtain the university number # obtain the average ranking in previous year and the last year for No in UniNoList: # loop university number for Y in range(2011,2016): # loop year for t in range(2): #loop topic ave = np.mean(df1[(df1.Topic == t) &( df1.UniversityNo == No) & (df1.Year < Y)].Lowest_Ranking) df1.loc[(df1.Topic == t) &( df1.UniversityNo == No) & (df1.Year == Y),'Average_Ranking'] = ave last = df1[(df1.Topic == t) &( df1.UniversityNo == No) & (df1.Year == Y-1)].Lowest_Ranking try: df1.loc[(df1.Topic == t) &( df1.UniversityNo == No) & (df1.Year == Y),'Last_Ranking'] = last.values except: pass df2 = pd.read_csv("Original_Data/UniversityMarksFull.csv") #the score of different years of universities df2.columns = ["University_Name_Location","Year","Lowest","Highest","ave","Plan","NO","Topic"] df2.Year += 1 #set to predict the next year # in some university, no lowest score data provided, so we use the ave andhighest to present df2.Lowest[np.isnan(df2.Lowest)] = df2.Lowest[np.isnan(df2.ave)] df2.Lowest[np.isnan(df2.Lowest)] = df2.Lowest[np.isnan(df2.Highest)] df2.Topic[df2.Topic == "理科"] = 1 df2.Topic[df2.Topic == "文科"] = 0 df = df1.merge(df2[["University_Name_Location","Year","Lowest","Topic"]],on=['University_Name_Location','Year','Topic']) #merge some content of df2 to df1 #select some columns to produce the useful data selected_column = ["UniversityNo",'Year','Topic',"Lowest","GDP","Population","GDP_Per_Person","Plan_Number","Ranking_Scores","Media_Impact","Distance","Last_Ranking","Average_Ranking"] df = df[selected_column] df = df[~np.isnan(df.Last_Ranking)] df = df[~np.isnan(df.Average_Ranking)] df = df[~(df.Average_Ranking == 0)] #average ranking in 2010 is zero df.to_csv("Produce_Data/University_data_cluster.csv") #the data pass for label training
d67b6cf357278ebd16954f6a0405ffd40d4e65f2
jchen49gsu/coding_practice
/700. Search in a Binary Search Tree.py
460
3.78125
4
class TreeNode(object): def __init__(self,x): self.val = x self.left = None self.right = None class Solution(object): def searchBST(self,root,val): if root is None: return root if root.val == val: return root elif root.val > val: return self.searchBST(root.left,val) else: return self.searchBST(root.right,val) root = TreeNode(2) root.left = TreeNode(1) root.right = TreeNode(3) val = 1 s = Solution() print s.searchBST(root,val)