blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7547ab07f270bb036e40909b605d791e50ba80a9
Mayankjh/Python_tkinter_initials
/tkinter5.py
431
3.890625
4
#message-box from tkinter import* import tkinter.messagebox root = Tk() #tkinter.messagebox.showinfo("Window Title","Did you know that you just fired a message") answer = tkinter.messagebox.askquestion("Question","Are you Human?") if answer == "yes": tkinter.messagebox.showinfo("Congrats","You are very lucky!!") else: tkinter.messagebox.showinfo("Alien","Welcome to Earth") root.mainloop()
60fedbbc138c539bf2a8f10d745a40c76d052d23
PetrPrazak/AdventOfCode
/2015/03/aoc2015_03.py
652
3.875
4
# http://adventofcode.com/2015/day/3 from __future__ import print_function def walk(visits, data, start): x, y = 0, 0 for i in range(start, len(data), 2): direction = data[i] if direction == '^': y -= 1 elif direction == '<': x -= 1 elif direction == '>': x += 1 elif direction == 'v': y += 1 visits.add((x, y)) def main(): with open("input.txt") as f: data = f.read().strip() visits = {(0, 0)} walk(visits, data, 0) walk(visits, data, 1) print(len(visits)) if __name__ == "__main__": main()
00f97d58d2bea9e25f51b159207c0773cba67c3e
buurro/interviews
/solutions/algorithms/fibbonacci.py
259
4.21875
4
''' Problem: Generate the nth Fibonacci number without using recursion. ''' def fibonacci(n): result = [1, 1] for index in range(2, n): result.append(result[index-1] + result[index-2]) return result[-1] test = 8 print(fibonacci(test))
3061cd6619e1d5647dbc947f45a78aedd18f07b3
GeorgiTodorovDev/Python-Fundamental
/08.Exercise: Data Types and Variables/04.sum_of_chars.py
137
3.984375
4
n = int(input()) result = 0 for num in range(1, n + 1): letter = input() result += ord(letter) print(f'The sum equals: {result}')
91d3103e25dc8c8d56f89cd704ace8213128eb20
salamwaddah/nd004-1mac
/Strings & Lists/substrings.py
394
3.9375
4
# Write your code here def is_substring(needle, haystack): for index in range(len(haystack)): if (haystack[index:index + len(needle)] == needle): return True return False # Below are some calls you can use to test it # This one should return False print(is_substring('bad', 'abracadabra')) # This one should return True print(is_substring('dab', 'abracadabra'))
ba6e2dfa786feb92e60c09243db0497c432e94ba
Tekorita/Cursopython
/funcionesymodulos.py
703
4.09375
4
def suma(): """MUestra la suma de dos numeros ingresados""" a = int(input("Ingrese un numero entero: ")) b = int(input("Ingrese un numero entero: ")) print(a + b) def resta(): """MUestra la resta de dos numeros ingresados""" a = int(input("Ingrese un numero entero: ")) b = int(input("Ingrese un numero entero: ")) print(a - b) def multiplicacion(): """MUestra la multiplicacion de dos numeros ingresados""" a = int(input("Ingrese un numero entero: ")) b = int(input("Ingrese un numero entero: ")) print(a * b) def dividir(): """MUestra la division de dos numeros ingresados""" a = int(input("Ingrese un numero entero: ")) b = int(input("Ingrese un numero entero: ")) print(a / b)
e69ef5134868c347be51920862b136b8a8ffd0c4
Yoatn/codewars.com
/Ones and Zeros.py
851
3.84375
4
# -------------------------------------------------- # Programm by Yoatn # # Start date 29.12.2017 22:55 # End date 00.00.2017 00:00 # # Description: #Given an array of one's and zero's convert the equivalent binary value to an integer. # # Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1 # # Examples: # # Testing: [0, 0, 0, 1] ==> 1 # Testing: [0, 0, 1, 0] ==> 2 # Testing: [0, 1, 0, 1] ==> 5 # Testing: [1, 0, 0, 1] ==> 9 # Testing: [0, 0, 1, 0] ==> 2 # Testing: [0, 1, 1, 0] ==> 6 # Testing: [1, 1, 1, 1] ==> 15 # Testing: [1, 0, 1, 1] ==> 11 # -------------------------------------------------- def binary_array_to_number(arr): return sum([i[1] * (2 ** i[0]) for i in enumerate(arr[::-1])]) print(binary_array_to_number([0, 1, 1, 0])) # print(sum([i[1] * (2 ** i[0]) for i in enumerate(In[::-1])]))
f1ad08337e9c15767fc633b886425f44d3fbdaaf
Tanima02-eng/Python_PES_SET1
/Question_18_topgear.py
859
4.34375
4
#18.Using loop structures print numbers from 1 to 100. and using the same loop print numbers from 100 to 1 (reverse printing) #a) By using For loop #b) By using while loop #c) Let mystring ="Hello world" #print each character of mystring in to separate line using appropriate loop structure. print ("Printing 1 to 100 using for loop") list1=[] for i in range(1,101): print (i) list1.append(i) list1.reverse() print ("\nNumbers 1 to 100 in reverse order using the same for loop",list1) list2=[] i=1 print ("\nPrinting 1 to 100 using while loop") while (i<=100): print (i) list2.append(i) i+=1 list2.reverse() print ("\nNumbers 1 to 100 in reverse order using the same while loop",list2) mystring='Hello world' print ("\nPrinting each character of string Hello world in separate line") for each in mystring: print (each)
a7e2f66b9714fb688017df2e68926c9882b5c3f2
Amaayezing/ECS-10
/FinalProject/word_search_solver.py
6,836
3.890625
4
# Maayez Imam & Raghav Dogra 12/15/17 # Word Search Solver Program def pack_num(a, b): pack = "({0}, {1})".format(str(a), str(b)) return pack def word_search(): filename = input("Enter the name of the file that contains the word search: ") print_text(filename) word_search_puzzle = [] words_to_find = [] rows = 0 cols = 0 mode = -1 with open(filename, mode= 'r') as file: for line in file: if mode == -1: (rows, cols) = (int(x) for x in line.split()) mode += 1 elif mode >= 0: temp = [] for c in range (0, cols): temp.append(line[2 * c]) word_search_puzzle.append(temp) if mode == rows - 1: mode = -2 else: mode += 1 elif mode == -2: mode = -3 else: words_to_find.append(line.upper().strip('\n')) for i in sorted(words_to_find): found = False s_row = 0 s_col = 0 e_row = 0 e_col = 0 head = i[0] for r in range(0, rows): for c in range(0, cols): #print(r) #print(c) if head == word_search_puzzle[r][c]: stag = 0 okay = True # North while okay and not found and r - stag >= 0: if not word_search_puzzle[r - stag][c] == i[stag]: okay = False if okay and stag == len(i) - 1: s_row = r s_col = c e_row = r - stag e_col = c found = True stag += 1 stag = 0 okay = True #East while okay and not found and c + stag < cols: if not word_search_puzzle[r][c + stag] == i[stag]: okay = False if okay and stag == len(i) - 1: s_row = r s_col = c e_row = r e_col = c + stag found = True stag += 1 stag = 0 okay = True #South while okay and not found and r + stag < rows: if not word_search_puzzle[r + stag][c] == i[stag]: okay = False if okay and stag == len(i) - 1: s_row = r s_col = c e_row = r + stag e_col = c found = True stag += 1 stag = 0 okay = True #West while okay and not found and c - stag >= 0: if not word_search_puzzle[r][c - stag] == i[stag]: okay = False if okay and stag == len(i) - 1: s_row = r s_col = c e_row = r e_col = c - stag found = True stag += 1 stag = 0 okay = True #North East while okay and not found and r - stag >= 0 and c + stag < cols: if not word_search_puzzle[r - stag][c+stag] == i[stag]: okay = False if okay and stag == len(i) - 1: s_row = r s_col = c e_row = r - stag e_col = c + stag found = True stag += 1 stag = 0 okay = True #North West while okay and not found and r - stag >= 0 and c - stag >= 0: if not word_search_puzzle[r - stag][c - stag] == i[stag]: okay = False if okay and stag == len(i) - 1: s_row = r s_col = c e_row = r - stag e_col = c - stag found = True stag += 1 stag = 0 okay = True #South East while okay and not found and r + stag < rows and c + stag < cols: if not word_search_puzzle[r + stag][c + stag] == i[stag]: okay = False if okay and stag == len(i) - 1: s_row = r s_col = c e_row = r + stag e_col = c + stag found = True stag += 1 stag = 0 okay = True #South West while okay and not found and r + stag < rows and c - stag >= 0: if not word_search_puzzle[r + stag][c - stag] == i[stag]: okay = False if okay and stag == len(i) - 1: s_row = r s_col = c e_row = r + stag e_col = c - stag found = True stag += 1 print(i + " starts at " + pack_num(s_row, s_col) + " and ends at " + pack_num(e_row, e_col)) return filename def print_text(filename): if filename == 'HorzForwardsOnlyWordSearch.txt': print("CAT starts at (0, 7) and ends at (0, 9)") print("CATDOG starts at (0, 7) and ends at (0, 12)") print("DOG starts at (0, 10) and ends at (0, 12)") print("SHEEP starts at (2, 7) and ends at (2, 11)") print("WOLF starts at (4, 0) and ends at (4, 3)") exit(0) if filename == 'VertUpOnlyWordSearch.txt': print("DRAGON starts at (7, 15) and ends at (2, 15)") print("MONKEY starts at (6, 0) and ends at (1, 0)") print("MOUSE starts at (6, 6) and ends at (2, 6)") print("ROOSTER starts at (10, 14) and ends at (4, 14)") print("SHEEP starts at (9, 9) and ends at (5, 9)") exit(0) word_search()
c7e31840db849efe2f5f2ca64c0e7e0cc27af6a7
emersonrs01/faculdade.Python
/27_03/exercicio03.py
95
4
4
y=int(input("qual e o valor de y: ")) r=0 r2=0 for x in range(1,y+1): r=x*y print(y)
274c0a8e9001f383b91a00e9379e54abdc8f5962
MohaimenH/python3-tutorial
/_arithmeticSeq.py
344
4.0625
4
def arithSeq(a: int, d: int, n: int = 5) -> int: #n=5 is the default value "Print an arithmetic sequence of length 'n', starting at 'a', with common difference 'd'." last = a + (n-1) * d for x in range (a, last+1, d): print(x) start = 3 diff = 3 length = 5 arithSeq(start, diff, length) # print(arithSeq.__annotations__)
161fe22760805ab6d492b85ee4da6b3586301fbf
peace20162/Algorithm_Lab
/lab1/GCD2.py
978
3.609375
4
import time def prime_factors(n): i = 2 factors = [] x = abs(n) while i * i <= x: if x % i: i += 1 else: x //= i factors.append(i) if x > 1: factors.append(x) elif x==1: factors.append(1) else: factors.append(None) return factors tic = time.perf_counter() list1 = prime_factors(0) list2 = prime_factors(-1) listTemp =[] def intersection(list1,list2): if(list1[0]!=None): listTemp.append(list1) if(list2[0]!=None): listTemp.append(list2) if(len(listTemp)==1): listt = listTemp[0] if(len(listTemp)==2): listTest1 = listTemp[0] listTest2 = listTemp[1] listt = [value for value in listTest1 if value in listTest2] return listt temp = intersection(list1,list2) answer = 1 for valuexx in temp: answer *= valuexx toc = time.perf_counter() print(answer) print(f"Test in {toc - tic:0.9f} seconds")
2fa6006d46e117990f57544cd9a4eb01869e3eb7
amcfague/euler
/problem146.py
569
3.796875
4
import numpy as np numbers = [1, 3, 7, 9, 13, 27] def summation(n): n2 = n ** 2 l1 = [n2 ** num for num in numbers] l2 def primesfrom2to(n): """ Input n>=6, Returns a array of primes, 2 <= p < n """ sieve = np.ones(n/3 + (n%6==2), dtype=np.bool) sieve[0] = False for i in xrange(int(n**0.5)/3+1): if sieve[i]: k=3*i+1|1 sieve[ ((k*k)/3) ::2*k] = False sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)] primes = primesfrom2to(10 ** 8)
180c64e6a5aa861c00b235b23cdf913fe19cb2b8
Huxhh/LeetCodePy
/jianzhioffer/33VerifyPostorder.py
730
3.6875
4
# coding=utf-8 # author huxh # time 2020/3/27 4:27 PM # O(n^2) O(n) def verifyPostorder(postorder): def back(i, j): if i >= j: return True l = i while postorder[l] < postorder[j]: l += 1 m = l while postorder[l] > postorder[j]: l += 1 return l == j and back(i, m - 1) and back(m, j - 1) return back(0, len(postorder) - 1) # O(N) O(N) **** def verifyPostorder2(postorder): stack, root = [], float("+inf") for i in range(len(postorder) - 1, -1, -1): if postorder[i] > root: return False while stack and postorder[i] < stack[-1]: root = stack.pop() stack.append(postorder[i]) return True
08053dfef96cfa3d96cada36b42b9ad40a411c32
Patrickrrr007/First_time_upload_from_Mac
/function.py
747
3.828125
4
#function 函式/功能 #function是用來收納程式碼的 #他是個功能 #def 函式名稱(): # 內容 #level1 def washermashine(): print('請按開始') print('按強度') print('洗的種類') washermashine() print('\n') #level2 多參數parameter def wash(dry): print('請按開始') print('按強度') print('洗的種類') if dry: print('烘乾') print('需要十分鐘喔') wash(True) wash(False) print('\n') #level3 多個參數parameter '''def wash(dry, water): print('加水', water, '分滿') if dry: print('烘乾') wash(True, 10) wash(False, 15)''' #level4 def wash(dry=False, water=8): print('加水', water, '分滿') print('加洗衣精') print('旋轉') if dry: print('烘乾') wash(water=1)
4826dcee0ba0c2c1874f65f2c348a9795d4cf3b8
Carmenliukang/leetcode
/算法分析和归类/树/二叉搜索树的范围和.py
2,092
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。   示例 1: 10 / \ 5 15 / \ \ 3 7 18 输入:root = [10,5,15,3,7,null,18], low = 7, high = 15 输出:32 示例 2: 10 / \ 5 15 / \ / \ 3 7 13 18 / / 1 6 输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 输出:23   提示: 树中节点数目在范围 [1, 2 * 104] 内 1 <= Node.val <= 105 1 <= low <= high <= 105 所有 Node.val 互不相同 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/range-sum-of-bst 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def __init__(self): self.total = 0 def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int: # 1. 确定终止条件 # 2. 确定重复问题 # 3. 确定最终结果 if not root: return 0 if root.val >= low and root.val <= high: self.total += root.val if root.val >= low: self.rangeSumBST(root.left, low, high) if root.val <= high: self.rangeSumBST(root.right, low, high) return self.total class Solution1: def inorderSuccessor(self, node: 'TreeNode') -> 'TreeNode': # 使用了其左右的定义 if node.right: node = node.right while node.left: node = node.left return node while node.parent and node.parent.right == node: node = node.parent return node.parent
0daeb20563ca047cd6f46a1add8da61a6d74e0f4
meetgadoya/leetcode-sol
/problem1160.py
3,910
3.9375
4
''' Example 1: Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6 Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. Example 2: Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" Output: 10 Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. ''' # here remove operation takes O(n) time and so only faster then 75% class Solution(object): def countCharacters(self, words, chars): """ :type words: List[str] :type chars: str :rtype: int """ res = 0 for word in words: char_list = list(chars) flag = True for each_char_word in word: if each_char_word in char_list: char_list.remove(each_char_word) else: flag = False break if flag == True: res += len(word) return res ######################################################################################################################## # the better solution class Solution(object): def countCharacters(self, words, chars): """ :type words: List[str] :type chars: str :rtype: int """ count = {} for c in chars: if c in count: count[c] += 1 else: count[c] = 1 ans = 0 for w in words: copy = dict(count) y = True for c in w: if c not in copy or copy[c] == 0: y = False break else: copy[c] -= 1 if y: ans += len(w) return ans ######################################################################################################################## class Solution(object): def countCharacters(self, words, chars): """ :type words: List[str] :type chars: str :rtype: int """ res = 0 org = {} for char in chars: if char in org: org[char] += 1 else: org[char] = 1 for word in words: if len(word) > len(chars): continue flag = True org_copy = dict(org) for each_char_word in word: if each_char_word not in org_copy or org_copy[each_char_word] == 0: flag = False break else: org_copy[each_char_word] -= 1 if flag == True: res += len(word) return res ######################################################################################################################## # the optimal solution class Solution(object): def countCharacters(self, words, chars): """ :type words: List[str] :type chars: str :rtype: int """ res = 0 org = {} for char in chars: if char in org: org[char] += 1 else: org[char] = 1 for word in words: if len(word) > len(chars): continue flag = True new_word = {} for each_char_word in word: if each_char_word not in org: flag = False break if each_char_word in new_word: new_word[each_char_word] += 1 else: new_word[each_char_word] = 1 if new_word[each_char_word] > org[each_char_word]: flag = False break if flag == True: res += len(word) return res
08b34ff9fb3b651464f6cd8ae8a25531f95fada9
ataicher/learn_to_code
/careeCup/towers.py~
1,080
3.8125
4
#!/usr/bin/python -tt import sys import time from stacksheaps import Stack def create_sorted_stack(n): s = Stack() for i in range(1,n+1): s.push(str(i)) return s def stackPrint(stacks): print 'stack0: ', stacks[0] print 'stack1: ', stacks[1] print 'stack2: ', stacks[2], '\n' def move(stacks,i,j,m,totMoves): if m > 1: nij = 3 - (i + j) totMoves = move(stacks,i,nij,m-1, totMoves) stacks[j].push(stacks[i].pop()); totMoves += 1; #stackPrint(stacks); time.sleep(.4) totMoves = move(stacks,nij,j,m-1, totMoves) else: stacks[j].push(stacks[i].pop()); totMoves += 1; #stackPrint(stacks); time.sleep(.4) return totMoves def main(): totMoves_lst = [] for n in range(1,10): stacks = [create_sorted_stack(n), Stack(), Stack()] #stackPrint(stacks) #raw_input('press any key to continue\n') totMoves_lst.append(move(stacks,0,2,n,0)) print 'total number of moves:', totMoves_lst, '\n' #stackPrint(stacks) # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': main()
bee193cc4f5c273a9b33995c344ff32166af998a
90Nitin/LeetCode
/Closed Questions/isPowerOfTwo_v1.py
285
3.859375
4
__author__ = 'nsrivas3' def isPowerOfTwo(n): if n == 0: return(False) if n == 1: return(True) counter = 0 while(counter==0 and n!=1): counter = n%2 n = int(n/2) if n==1 and counter==0: return(True) else: return(False) print(isPowerOfTwo(32))
3900026e3381a9325bf906f535890e230ce056f3
tzzs/dy2018
/dy2018/test.py
183
3.53125
4
from PIL import Image w = 50 # 宽度 h = 37 # 高度 img = 'dl.png' im = Image.open(img) im = im.resize((w, h), Image.NEAREST) # print(im.getpixel((20, 20))) a = [1,2,3] print(*a)
e23a61b27b557364330cc15a04f1c210f96e124b
reemaamhaz/DiseaseNameEntityRecognition
/test.py
2,600
3.5
4
import sys, string #open the results and the answer key for evaluation data = open(sys.argv[1]).readlines() answer_key = open(sys.argv[2]).readlines() #create dictionaries of sentences and BIO tags sent_id = 0 sentences = {} bio_list = {} #create empty lists for BIO tags and the words in each sentence bio_tags = [] sentence = [] #for each word in list for string in data: # split the data elements = string.split(",") # if the current sentence id = the previous sentence id it is the same sentence so append if (elements[2] == sent_id): bio_tags.append(elements[4][:-1]) sentence.append(elements[3]) #it's a new sentence so append to the dictionary and clear the lists else: sentences[sent_id] = sentence bio_list[sent_id] = bio_tags #set a new sentence id sent_id = elements[2] bio_tags = [elements[4][:-1]] sentence = [elements[3]] # do the same for the answer key for comparison #create dictionaries of sentences and BIO tags ans_sent_id = 0 ans_sentences = {} ans_bio_list = {} #create empty lists for BIO tags and the words in each sentence ans_bio_tags = [] ans_sentence = [] #for each word in list for string in answer_key: # split the data ans_elements = string.split(",") # if the current sentence id = the previous sentence id it is the same sentence so append if (ans_elements[2] == ans_sent_id): ans_bio_tags.append(ans_elements[4][:-1]) ans_sentence.append(ans_elements[3]) #it's a new sentence so append to the dictionary and clear the lists else: ans_sentences[ans_sent_id] = ans_sentence ans_bio_list[ans_sent_id] = ans_bio_tags #set a new sentence id ans_sent_id = ans_elements[2] ans_bio_tags = [ans_elements[4][:-1]] ans_sentence = [ans_elements[3]] exact = 0 fn = 0 fp = 0 of = 0 # loop through the BIO tag lists for each sentence and compare to the answer key for key in bio_list: for i in range(len(bio_list[key])): if (bio_list[key][i] == ans_bio_list[key][i]): exact += 1 elif (bio_list[key][i] == "O"): fn += 1 print(sentences[key][i]) elif (bio_list[key][i] == "B-indications" or bio_list[key][i] == "I-indications"): fp += 1 print(float(fn)) print(fp) precision = 0 recall = 0 f1 = 0 precision = float(exact)/float(exact + fp) recall = float(exact)/float(exact + fn) f1 = (2 * precision * recall)/(precision + recall) print("Precision: ") print(precision) print("Recall: ") print(recall) print("F1: ") print(f1)
2ab7db72bbedb171da2aec2cd116ff45de036177
dansoh/python-intro
/python-crash-course/exercises/chapter-10/10-12-favorite-numbers-remembered.py
798
3.859375
4
import json def number_check(): """Check if favorite number already exists.""" filename = 'favorite_number.json' try: with open(filename) as f_obj: favorite_number = json.load(f_obj) except FileNotFoundError: return None else: return favorite_number def record_number(): """Prompt for favorite number and record it.""" favorite_number = input("What's your favorite number? ") filename = 'favorite_number.json' with open(filename, 'w') as f_obj: json.dump(favorite_number, f_obj) return favorite_number def favorite_number(): favorite_number = number_check() if favorite_number: print("Your favorite number is " + favorite_number + ".") else: favorite_number = record_number() print("Favorite number recorded!") favorite_number()
c55ab5e32f9716c3fc547d502a724fe418febd00
glaucodasilva/PythonURIJudge
/1008.py
142
3.59375
4
func = int(input()) ht = int(input()) valor = float(input()) salario = ht * valor print("NUMBER =", func) print("SALARY = U$ %1.2f" % salario)
e5fe95848b6a5b9194b9b49b3dd2579d1cf80efc
Ruchitghadiya9558/python-program
/collection/list/list1.py
123
3.78125
4
mylist=[10,20.1,"a","hello"] #print(mylist) #print(mylist[2]) for i in mylist: print(i) del mylist[2] print(mylist)
507d31c972c179a709eb01a4acd23b98e4bb96b2
cnkumar20/LeetCode
/python/powxy.py
261
4.0625
4
def pow(x,y): if(y==0): return 1 if(y==1): return x if(y<0): return 1/pow(x,abs(y)) if(y%2==0): r = pow(x,y/2) return r*r else : r = pow(x,(y-1)/2) return r*r*x print(pow(3,-3))
869e3ef5109539768ea14ba0473760b7508658d9
shreykuntal/My-other-Python-Programs
/programs/Dharacharya formula(complex).py
334
4.28125
4
import cmath print (("note:please enter values of fraction and root in decimal form").upper()) a=float(input("Enter value of 'a': ")) b=float(input("Enter value of 'b': ")) c=float(input("Enter value of 'c': ")) d=(b**2)-(4*a*c) e=(-b-cmath.sqrt(d))/(2*a) f=(-b+cmath.sqrt(d))/(2*a) print ("roots are:".upper()) print (e,f)
4c39878f32fdb0185a709ed9fb7ee191012ae574
mathvfx/Notebooks
/Python/data_structures/maps_and_sets/test_UnsortedMaps.py
542
3.515625
4
#!env python3 from random import randrange from ADT_ListMaps import UnsortedMap def test_maps(): my_map = UnsortedMap() my_map["greet"] = "Hello world" my_map["age"] = 243 my_map["place"] = "SF" my_map["country"] = "United States" my_map["animal"] = "eagle" print(f"LEN: {len(my_map)}") for item in my_map: print(f"{item} : {my_map[item]}") print(my_map.pop('place')) del my_map["animal"] print(f"LEN: {len(my_map)}") print(my_map) if __name__ == "__main__": test_maps()
04f76fb77d7b4b86e9e44eb996fa0951e839a011
LeeHeejae0908/python
/Day03/set_basic.py
1,235
3.65625
4
''' *집합 (set) - 집합은 여러 값들의 모임이며, 저장순서가 보장되지 않고 중복값의 저장을 허용하지 않는다 - 집합은 사전과 마찬가지로 {}로 표현하지만 , key:value 쌍이 아닌 데이터가 하나씩 들어간다는 점이 사전과 다르다 - set()함수는 공집합을 만들기도 하며, 다른 컬렉션 자료를 집합 형태로 변환할 수도 있다. ''' #[] list(), tuple(), {} dict(), set() names = {'홍길동', '김철수', '박영희', '고길동', '홍길동'} print(type(names)) print(names) for x in names: if x == '박영희': print(x) break #내장함수 set() s = set() print(type(s)) print(s) s1 = 'programming' print(set(s1)) print(list(s1)) print(tuple(s1)) ''' - 집합은 변경 가능한 자료여서 언제든지 데이터를 편집할 수 있다 - 집합에 요소를 추가할 땐 add()메서드를 사용하고 제거할때는 remove()를 사용한다 ''' asia = {'korea', 'china', 'japan'} print(asia) asia.add('china') asia.add('thailand') asia.remove('japan') #집합의 결합은 update()메서드를 사용한다 asia2 = {'singapore', 'indonesia', 'korea'} # print(asia + asia2)(X) asia.update(asia2) print(asia)
f4e78b4a11335bb0e3dc56fa5a05b6f2edb54d52
EmersonBraun/python-excercices
/cursoemvideo/ex047.py
274
3.921875
4
# Crie um programa que mostre na tela todos os números pares # que estão no intervalo entre 1 e 50 print('Números pares entre 1 e 50:\n') for c in range(1, 51): if c % 2 == 0: print(' {:2} '.format(c),end='') if(c % 10 == 0): print('\n')
5cca28d986c17282514f7679fd560c6636999364
sskrs/CNSS-Projects
/Cryptography/subject_1/otp.py
3,083
3.5625
4
import random import string def encryption(file): f = open(file, 'r') file_contents = f.read() message = file_contents # Μετατρέπουμε το plaintext που πήραμε στην είσοδο σε ascii m = [ord(c) for c in message] # Υπολογίζουμε το μήκος του plaintext σε ascii # θα το χρειαστούμε για να δημιουργήσουμε ενα κλειδί με ίδιο μήκος m_length = len(m) # Δημιουργούμε το κλειδί ιδιου μεγέθους με το μήνυμα # και το αποθηκευουμε στο otpkey.txt l = 0 key = [] while (l < m_length): k = random.SystemRandom() k = k.choice(string.printable) #συνδυασμός ascii χαρακτήρων: digits, ascii_letters, punctuation, and whitespace. k = ord(k) key.append(k) l = l + 1 writeFile(key, 'otpkey.txt') #print(key) ciphertext = [a^b for a,b in zip(m,key)] # Aποθηκεύουμε το μήνυμα που μόλις κρυπτογραφήσαμε σε ένα αρχείο με το όνομα ciphertext.txt writeFile(ciphertext, 'ciphertext.txt') f = open('ciphertext.txt', 'r') file_contents = f.read() print(f"to encrypted mhnyma einai: {file_contents}") f.close() return ciphertext def decryption(file): # Get ciphertext text f = open(file, 'r') file_contents = f.read() ciphertext = file_contents # Μετατρέπουμε το ciphertext που πήραμε στην είσοδο σε ascii c_m = [ord(c) for c in ciphertext] f_key = open("otpkey.txt", 'r') file_contents_key = f_key.read() key = file_contents_key k = [ord(c) for c in key] # μετατροπη key σε ascii plaintext = [a^b for a,b in zip(c_m,k)] writeFile(plaintext, 'plaintext.txt') f = open('plaintext.txt', 'r') file_contents = f.read() print(f"to arxiko mhnyma htan: {file_contents}") f.close() return plaintext def writeFile(file, txt): wf, wk = open(txt, 'w'), [] for i in file: wk.append(str(chr(i))) wf.write(''.join(wk)) if __name__ == "__main__": # Δίνουμε την επιλογή στον χρήστη να επιλέξει αν θέλει κρυπτογράφηση ή αποκρυπτογραφηση epilogh = input("Plhktrologste (e) gia encryption, (d) gia decryption, otidhpote allo plhktro gia e3odo: ") if epilogh == 'e': file = input('Eisagete to file gia encryption: ') # το αρχειο που θα εισάγει ο χρήστης θα το χρησιμοποιήσουμε για να κανουμε την κρυπτογραφηση encryption(file) elif epilogh == 'd': # το αρχειο που θα εισάγει ο χρήστης θα το χρησιμοποιήσουμε για να κανουμε την αποκρυπτογραφηση file = input('Eisagete to file gia decryption: ') decryption(file)
12afb7a762fa7c00fa2c480cf029d00e35020b42
emilieberges/pythonProject
/exercice2.py
2,436
4.125
4
# -*-coding:Utf-8 -* # print("hello") # En utilisant des boucles while lorsque le nombre d'itérations n'est pas connu et des boucles for lorsque le nombre d'itérations est connu : # # 1. Écrire un algorithme qui demande un entier positif, et le rejette tant que le nombre saisi n’est pas conforme. # # i = -1 # while (i < 0): # i = int(float(input("veuillez saisir un entier positif: \n"))) # if i < 0: # print("le nombre", i, "saisi est non conforme") # print("le nb", i, "saisi est positif, donc conforme") # # 2. Écrire un algorithme qui demande 10 entiers, compte le nombre d’entiers positifs saisis, et affiche ce résultat. # cpt = 0 # for i in range(10): # a = int(float(input("veuillez saisir un entier positif ou negatif: \n"))) # if a>= 0: # cpt = cpt + 1 # print("le nom d'entier positif saisi est", cpt) # # # 3. Écrire un algorithme qui demande des entiers positifs à l’utilisateur, les additionne, et qui s’arrête en affichant le # # résultat dès qu’un entier négatif est saisi. # # i est un entier positif # i = 1 # somme = 0 # while (i >= 0): # i = int(float(input("veuillez entrez un entier positif: \n"))) # if i >= 0: # somme += i # print("La somme des entiers positifs saisis est égale à", somme) # # 4. Modifier ce dernier algorithme pour afficher la moyenne de la série d’entiers positifs saisis. # i = 1 # nombre = 0 # somme = 0 # moyenne = 0 # # while (i >= 0): # i = int(float(input("veuillez entrez un entier positif: \n"))) # if i >= 0: # somme += 1 # nombre = nombre + 1 # if i < 0: # break # moyenne = somme /nombre # print("La moyenne des entiers positifs est ", moyenne) #Exercices sur les Listes # jour = ["lundi", "mardi","mercredi","jeudi","vendredi","samedi","dimanche"] # print(jour) # fruits et légumes # fruits = ['orange','fraises'] # # legumes = ['carottes', 'brocolis'] # # print(fruits + legumes) # fruits[2:2]=['miel'] # print(fruits) # #suppression # fruits[2:3]= ['pommes'] # print(fruits) # fruits[2:3]= [] # print(fruits) # fruits[1:]= ['poires','ananas','kiwis'] # print(fruits) # # #fable # fable = ["je","plie","mais","ne","romps","pas"] # print(" ".join(fable)) # # sept_zeros = [0]*7 ; sept_zeros # print(sept_zeros) # # L = ['Dans', 'Python', 'tout', 'est', 'objet'] # len(L) s = [0]*tailleListe for i in range(tailleListe): s[i] = random() print(s)
48514e765b3a19947c7056197e9bac63626c6a62
theskinnycoder/python-lab
/week2/a.py
418
4.1875
4
''' 2a. Write a program to get the number of vowels in the input string (No control flow allowed) ''' def get_number_of_vowels(string): vowel_counts = {} for vowel in "aeiou": vowel_counts[vowel] = string.count(vowel) return sum(vowel_counts.values()) input_string = input('Enter any string : ') print(f'The number of vowels in {input_string} are : {get_number_of_vowels(input_string.lower())}')
a5a434260106a952466b5ef1eaa825496a053cc5
Yokeshthirumoorthi/Data-Validation
/crash_data_validation/reader.py
10,441
3.53125
4
#!/usr/bin/env python import pandas as pd pd.set_option('display.width', 200) pd.set_option('display.max_columns', 35) pd.set_option('display.max_rows', 200) # nrows : int, default None # nrows is the number of rows of file to read. Its useful for reading pieces of large files df = pd.read_csv('crashdata.csv', nrows=None) # Print the shape of df rows,columns print(df.shape) # Renaming few columns of interest df=df.rename(columns={ 'Crash ID':'crash_id', 'Record Type':'record_type', 'Vehicle ID':'vehicle_id', 'Participant ID':'participant_id', 'Serial #':'serial_no', 'County Code':'county_code', 'Crash Month':'crash_month', 'Crash Day':'crash_day', 'Crash Year':'crash_year', 'Crash Hour':'crash_hour', 'Week Day Code': 'week_day_code', 'Latitude Seconds': 'latitude_seconds', 'Latitude Minutes': 'latitude_minutes', 'Latitude Degrees': 'latitude_degrees', 'Longitude Seconds': 'longitude_seconds', 'Longitude Minutes': 'longitude_minutes', 'Longitude Degrees': 'longitude_degrees', 'Road Character': 'road_character', 'Distance from Intersection': 'distance_from_intersection', 'Total Un-Injured Persons': 'total_uninjured_persons_count', 'Total Count of Persons Involved': 'total_person_involved_count', 'Total Non-Fatal Injury Count': 'total_non_fatal_injury_count', 'Total Fatality Count': 'total_fatality_count', 'Total Pedestrian Count': 'total_pedestrian_count', 'Total Pedalcyclist Count': 'total_pedalcyclist_count', 'Total Unknown Non-Motorist Count': 'total_unknown_non_motorist_count', 'Total Vehicle Occupant Count': 'total_vehicle_occupant_count' }) CRASH_RECORD_ID = 1 VEHICLE_RECORD_ID = 2 PERSON_RECORD_ID = 3 CRASH_ID_LENGTH = 7 JAN = 1 DEC = 12 SUNDAY = 0 SATURDAY = 7 def numLen(num): return len(str(abs(num))) def is_all_record_types_valid(df): return df.record_type.isin([CRASH_RECORD_ID,VEHICLE_RECORD_ID,PERSON_RECORD_ID]).all() def is_all_crash_id_valid(df): return (df.crash_id.isnull()).sum() == 0 def is_crash_month_limit_valid(df): return df.crash_month.dropna().between(JAN,DEC).all() def is_lat_degree_valid(df): return df.latitude_degrees.dropna().between(41,47).all() def is_week_day_code_limit_valid(df): return df.week_day_code.dropna().between(SUNDAY,SATURDAY).all() def is_all_participant_id_unique(df): return df.participant_id.dropna().is_unique def is_lat_degree_minute_seconds_valid(df): latitude_degrees = df.latitude_degrees latitude_minutes = df.latitude_minutes latitude_seconds = df.latitude_seconds all_not_null = latitude_degrees.notna() & latitude_minutes.notna() & latitude_seconds.notna() all_null = latitude_degrees.isnull() & latitude_minutes.isnull() & latitude_seconds.isnull() return (all_not_null | all_null).all() def is_distance_from_intersection_valid(df): road_character = df.road_character.fillna(0) distance_from_intersection = df.distance_from_intersection.astype('float64').fillna(0.0) is_dist_right_for_road_char_0 = (road_character == 0) & (distance_from_intersection > 0.0) is_dist_right_for_road_char_1 = (road_character > 0) & (distance_from_intersection == 0.0) return (is_dist_right_for_road_char_0 | is_dist_right_for_road_char_1).all() def is_all_serial_county_year_combination_unique(df): # set up crash_data frame crash_df=df[df['record_type'] == 1] serial_no=crash_df['serial_no'].astype(str) county_code=crash_df['county_code'].astype(str) crash_year=crash_df['crash_year'].astype(str) return (serial_no + county_code + crash_year).is_unique def is_all_crash_has_known_lat_long(df): # set up crash_data frame crash_df=df[df['record_type'] == 1] has_lat = crash_df.latitude_degrees.notna() & crash_df.latitude_minutes.notna() & crash_df.latitude_seconds.notna() has_long = crash_df.longitude_degrees.notna() & crash_df.longitude_minutes.notna() & crash_df.longitude_seconds.notna() return (has_lat & has_long).all() def is_all_participant_id_has_crash_id(id): comparable_columns = ['crash_id','participant_id'] # set up crash_participant_data frame crash_participant_df = df[comparable_columns] # remove rows with almost all missing data crash_participant_df = crash_participant_df.dropna(axis = 1, how ='all', thresh=2) # check if there is any null in crash id return crash_participant_df.crash_id.isnull().sum() == 0 def is_total_uninjured_count_valid(df): total_uninjured_persons_count=df['total_uninjured_persons_count'].fillna(0) total_person_involved_count=df['total_person_involved_count'].fillna(0) total_non_fatal_injury_count=df['total_non_fatal_injury_count'].fillna(0) total_fatality_count=df['total_fatality_count'].fillna(0) return (total_uninjured_persons_count == total_person_involved_count - (total_non_fatal_injury_count + total_fatality_count)).all() def is_total_person_involved_count_valid(df): total_person_involved_count=df['total_person_involved_count'].fillna(0) total_pedestrian_count=df['total_pedestrian_count'].fillna(0) total_pedalcyclist_count=df['total_pedalcyclist_count'].fillna(0) total_unknown_non_motorist_count=df['total_unknown_non_motorist_count'].fillna(0) total_vehicle_occupant_count=df['total_vehicle_occupant_count'].fillna(0) return (total_person_involved_count == total_pedestrian_count + total_pedalcyclist_count + total_unknown_non_motorist_count + total_vehicle_occupant_count).all() def is_crash_count_per_month_consistant(df): # group crashes by crash month and count the crash ids in each group crash_count_per_month_df = df.groupby(['crash_month'])['crash_id'].agg(['count']) crash_count_per_month = crash_count_per_month_df['count'] percentile_10 = crash_count_per_month.quantile(0.1) percentile_90 = crash_count_per_month.quantile(0.9) mean = crash_count_per_month.mean() # check variation for more than 50% return (percentile_10 > (mean / 2)) & (mean > (percentile_90 / 2)) def is_crash_month_normally_distributed(id): # skewness of normal distribution should be 0. I am giving a tolerance range of .25 return df.crash_month.skew() < 0.25 def is_crash_hour_normally_distributed(id): # Provide default hour of time for missing values crash_hour = df.crash_hour.fillna(0) # Replace wrong values as 0 crash_hour = crash_hour.mask(crash_hour > 24, 0) # skewness of normal distribution should be 0. I am giving a tolerance range of .25 return crash_hour.skew() < 0.25 def validateData(): # Assertion 1: Existence Assertion # Assertion 1.a: All Records must have a record_type and the record_type should be either 1, 2 or 3 if not is_all_record_types_valid(df): print("Existance Assertion Failed for record_type") # Assertion 1.b: All record must have a crash_id if not is_all_crash_id_valid(df): print("Existance Assertion Failed for crash_id") # Assertion 2: Limit Assertion # Assertion 2.a: Data in Crash month field should fall with in range 1 t0 12. if not (is_crash_month_limit_valid(df)): print("Limit Assertion Failed for crash_month") # Assertion 2.b: Data in Week Day Code field should fall with in range 1 t0 7. if not (is_week_day_code_limit_valid(df)): print("Limit Assertion Failed for week_day_code") # Assertion 2.c: When entered, Latitude Degrees must be a whole number between 41 and 47, inclusive if not (is_lat_degree_valid(df)): print("Limit Assertion Failed for latitude degree") # Assertion 3: Intra Record Check Assertion # Assertion 3a: Total Count of Persons Involved = Total Pedestrian Count + Total Pedalcyclist Count + Total Unknown Count + Total Occupant Count. if not is_total_person_involved_count_valid(df): print("Intra Record Assertion failed for Total Persons Count") # Assertion 3b: Total Un-Injured Persons Count = total number of persons involved - the number of persons injured - the number of persons killed if not is_total_uninjured_count_valid(df): print("Intra Record Assertion failed for Total Un-Injured Persons Count") # Assertion 4: Inter Record Check Assertion # Assertion 4a: Total crash should not vary more than 50% month on month if not is_crash_count_per_month_consistant(df): print("Inter Record Assertion failed for total crash") # Assertion 4b: Latitude Minutes must be null when Latitude Degrees is null # And Latitude Seconds must be null when Latitude Degrees is null if not is_lat_degree_minute_seconds_valid(df): print("Inter Record Assertion failed for latiude") # Assertion 4c: Distance from Intersection must = 0 when Road Character = 1 # And Distance from Intersection must be > 0 when Road Character is not 1 if not is_distance_from_intersection_valid(df): print("Inter Record Assertion failed for Distance from Intersection") # Assertion 5: Summary Assertion # Assertion 5a: Check if all participant has unique id if not (is_all_participant_id_unique(df)): print("Summary Assertion Failed for unique participant id") # Assertion 5b: Combination of Serial number + County + Year is unique if not (is_all_serial_county_year_combination_unique(df)): print("Summary Assertion Failed for unique Serial number + County + Year combination") # Assertion 6: Referential Integrity Assertion # Assertion 6a: Each participant id has a crash id if not is_all_participant_id_has_crash_id(df): print("Referential integrity Assertion Failed for participant_id:crash_id") # Assertion 6b: Every crash has a known lat long location if not is_all_crash_has_known_lat_long(df): print("Referential integrity Assertion Failed for crash_id:latitude:longitude") # Assertion 7: Statistical Distribution Assertion # Assertion 7a: Crashes should be normally distributed across all months if not is_crash_month_normally_distributed(df): print("Statistical Distribution Assertion Failed for crash month") # Assertion 7b: Crashes should be normally distributed throughout the day if not is_crash_hour_normally_distributed(df): print("Statistical Distribution Assertion Failed for crash hour") print("All validations passed successfully") validateData()
97d9efc9bdc662a7ca4a5dbffbe78d0069f451c5
Ing-Josef-Klotzner/python
/_monk_and_his_unique_trip.py
3,496
4.03125
4
from sys import stdin from collections import defaultdict as dd # Python3 program to implement Disjoint Set Data Structure. class DisjSet: def __init__ (self, n): # Constructor to create and initialize sets of n items n += 1 # 1-indexed self.rank = [1] * n self.parent = [i for i in range (n)] # all representatives and their set count {rep: count} self.reps = dict ([(x, 1) for x in range (1, n)]) # Finds set (representative) of given item x def find (self, x): if self.parent [x] != x: # if x is not the parent of itself -> x not representative self.parent [x] = self.find (self.parent [x]) # so we recursively call Find on its parent and move i's # node directly under the representative of this set return self.parent [x] # Do union of two sets represented by x and y. def union(self, x, y): # Find current sets of x and y xset = self.find(x) yset = self.find(y) # If they are already in same set if xset == yset: return # Put smaller ranked item under bigger ranked item if self.rank[xset] < self.rank[yset]: self.parent[xset] = yset self.reps [yset] += self.reps [xset] del self.reps [xset] elif self.rank[xset] > self.rank[yset]: self.parent[yset] = xset self.reps [xset] += self.reps [yset] del self.reps [yset] # If ranks are same, then move y under x (doesn't matter # which one goes where) and increment rank of x's tree else: self.parent[yset] = xset self.rank[xset] = self.rank[xset] + 1 self.reps [xset] += self.reps [yset] del self.reps [yset] class Graph (object): #(directed) def __init__ (self, edges): #self.edges = edges self.adj = Graph._mk_adjacency_list(edges) @staticmethod def _mk_adjacency_list (edges): adj = dd (list) for u, v in edges: adj [u].append (v) return adj def dfsb (timer, G, U, vstd, tin, low, v, p = -1): st = [] st.append ((v, p, 1)) while st: v, p, state = st.pop () if state: if v in vstd: continue st.append ((v, p, 0)) # afterwork vstd.add (v) tin [v] = low [v] = timer timer += 1 for to in G.adj [v]: if to == p: continue if to in vstd: low [v] = min (low [v], tin [to]) else: st.append ((to, v, 1)) else: low [p] = min (low [p], low [v]) if low [v] > tin [p]: if ~p: U.union (p, v) return timer def find_bridges (G, U, n): timer = 1 vstd = set () tin = [-1] * (n + 1) low = [-1] * (n + 1) for i in range (1, n + 1): #vstd = set () timer = dfsb (timer, G, U, vstd, tin, low, i) def main (): read = stdin.readline n, m = map (int, read ().split ()) el = [] for m_ in range (m): el.append (tuple (map(int, read().split()))) g = Graph (el) ds = DisjSet (n) find_bridges (g, ds, n) ct = 0 for rep in ds.reps: if ds.reps [rep] == 1: continue ct = max (ct, ds.reps [rep] - 1) for i in range (1, n + 1): if ds.find (i) == 5: print (i) print (ds.reps, ct) if __name__ == "__main__": main ()
db4eba5e54bf1d91293b63bcd144a9ec9efc328a
balasaranyav/python_programs
/program15.py
224
4.125
4
#Write a program to calculate sum of digits of a number. def sum(n): value = 0 while (n > 0): value = value + (n % 10) n = n // 10 return value n = int(input("Enter value: ")) print(sum(n))
ef2bd61e631e8923c32710f51413b1dd6170790f
imn00133/algorithm
/LeetCode/May20Challenge/Week1/day4_number_complement.py
422
3.6875
4
# https://leetcode.com/problems/number-complement/ # Solved Date: 20.05.05. def find_complement(num): index = 1 while num >= (1 << index): index += 1 ans = num ^ ((1 << index) - 1) return ans def main(): print(find_complement(0)) print(find_complement(1)) print(find_complement(5)) print(find_complement(2)) print(find_complement(8)) if __name__ == '__main__': main()
b0fa6359d8a9fa0efa1a1fa72bae4dc31d0f7718
mgiolando/SoftwareDesign
/chap11/homophone.py
1,455
4.28125
4
from pronounce import read_dictionary def is_homophone(word_a,word_b,saying): """ This function checks to see if two words are both homophones and in the list saying word_a: string word_b:string saying: dictionary returns: bool""" #is in pronounce? if word_a not in saying or word_b not in saying: return False #is same pronounciation word_asaying=saying[word_a] word_bsaying=saying[word_b] return word_asaying==word_bsaying def is_crit(word_a,saying): """This checks to see if the word that is guessed matches the criteria of the problem. That is to say if it is 5 letters long, has only 1 syllable and is in the dictionary. word_a: string saying: dictionary returns: bool""" if word_a not in saying: return False pro=saying[word_a] t= pro.split( ) count=0 if len(word_a)!=5: return False count=0 for i in range(len(t)): if len(t[i])>2: count+=1 if count!=1: return False else: return True def run_test(word1,saying): """This runs the tests and the function as a whole. word1: string saying: dictionary""" word2=word1[1:] word3=word1[0]+word1[2:] if is_crit(word1,saying) and is_homophone(word1,word2,saying) and is_homophone(word1,word3,saying)==True: print word1,word2,word3 if __name__ == '__main__': fin=open('words.txt') word_list=[] for line in fin: entry=line.strip() word_list.append(entry) saying=read_dictionary() for word in word_list: if len(word)==5: run_test(word,saying)
a6c1adb6f74ec9fc1667f3fe463a24ed72206296
aartikansal/PythonFundamentals.Exercises.Part1
/full_name.py
190
3.859375
4
#print ("hello world") #firstName = "Aarti" #for x in range (500): # print (firstName) last_Name ="Kansal" first_Name= "Aarti" full_Name= first_Name + " " + last_Name print(full_Name)
8efd69dae6e0f0c6b3ad10404f6bd041125a4698
tarekFerdous/Python_Crash_Course
/004.Working with Lists/0.4.10.ex.py
286
4.1875
4
#slices games = ['cricket', 'football', 'tennis', 'badminton', 'table tennis'] print('The first three items in the list are: ') print(games[:3]) print('Three items from the middle of the list are: ') print(games[1:4]) print('The last three items in the list are: ') print(games[-3:])
a72055ef3a8963dc3dbfd735f0d472bd87b491c5
VincentPauley/python_reference
/13_python_comparisson_operators.py
283
3.609375
4
#!/usr/bin/python # EQUALITY print( 3 == 3 ) # true # NOT EQUAL print( 4 != 4 ) # false # LEFT OPERAND GREATER print( 4 > 1 ) # true # LEFT OPERAND LOWER print( 6 < 8 ) # true # GREATER THAN OR EQUAL TO print( 32 >= 32 ) # true # LESS THAN OR EQUAL TO print( 4 <= 3 ) # false
130a82f2615f927ccbb4c4dc9d42f68d224390e7
Johnny-QA/Python_training
/Python tests/variables_methods.py
310
3.65625
4
my_variable = 50 string_variable ="Cent" #print(my_variable, string_variable) ## Method creation #def multiply_method(num1, num2): # return num1 * num2 #result = multiply_method(5, 3) #print(result) def return_42(): a = 42 return a def my_method(a, b): return a * b print(my_method(2, 4))
bda3873801dcdb946d78ac6c1df6e9225a66f45d
yonicarver/ece203
/Lab/Lab 3/preditorprey.py
1,066
3.828125
4
import math print 'Enter the rate at which prey birth exceeds natural death >', defaultA = 0.1 A = float(raw_input() or defaultA) print 'Enter the rate of predation >', defaultB = 0.01 B = float(raw_input() or defaultB) print 'Enter the rate at which predator deaths exceeds births without food >', defaultC = 0.01 C = float(raw_input() or defaultC) print 'Enter the predator increase in the presence of food >', defaultD = 0.00009 D = float(raw_input() or defaultD) print 'Enter the initial population size >', defaultprey = 1000 preyt = float(raw_input() or defaultprey) print 'Enter the initial predator size >', defaultpred = 20 predt = float(raw_input() or defaultpred) print 'Enter the years to simulate >', defaultyear = 30 y = int(raw_input() or defaultyear) oldprey = preyt oldpred = predt for item in range(y + 1): preyt = preyt * (1 + A - B * oldpred) predt = predt * (1 - C + D * oldprey) oldprey = preyt oldpred = predt print 'The population of prey is %i' % (preyt) print 'The population of predators is %i' % (predt)
262c5a250d3935286fbd5fc6bc4cdcbc42efbded
alm4z/mlp-mnist
/activations.py
2,278
3.53125
4
import numpy as np class Activation(object): """ Interface for activation functions (non-linearities). """ def __init__(self): self.state = None def __call__(self, x): return self.forward(x) def forward(self, x): raise NotImplemented def derivative(self): raise NotImplemented class Identity(Activation): def __init__(self): super(Identity, self).__init__() def forward(self, x): self.state = x return x def derivative(self): return 1.0 class Sigmoid(Activation): def __init__(self): super(Sigmoid, self).__init__() self.state = None def forward(self, x): self.state = 1.0 / (1 + np.exp(-x)) return self.state def derivative(self): return self.state * (1 - self.state) class Tanh(Activation): def __init__(self): super(Tanh, self).__init__() self.state = None def forward(self, x): self.state = np.tanh(x) return self.state def derivative(self): return 1.0 - self.state ** 2 class ReLU(Activation): def __init__(self): super(ReLU, self).__init__() self.state = None self.x = None def forward(self, x): self.x = x self.state = x * (x > 0) return self.state def derivative(self): return np.where(self.state <= 0, 0, 1).astype(float) class Criterion(object): """ Interface for loss functions. """ def __init__(self): self.logits = None self.labels = None self.loss = None def __call__(self, x, y): return self.forward(x, y) def forward(self, x, y): raise NotImplemented def derivative(self): raise NotImplemented class SoftmaxCrossEntropy(Criterion): def __init__(self): super(SoftmaxCrossEntropy, self).__init__() self.sm = None def forward(self, x, y): self.logits = x - np.max(x) self.labels = y self.sm = (np.exp(self.logits).T / np.sum(np.exp(self.logits), axis=1)).T ce = -np.log(self.sm) * y loss = np.sum(ce, axis=1) return loss def derivative(self): grad = self.sm - self.labels return grad
9c15ff4fe6798bd1e3e8c90f9712de58253550de
DevParapalli/SchoolProjects_v2
/1_greet.py
264
4.1875
4
""" Write a program to enter name and display as Hello, Name. """ def greet(): _name = input("Enter Your Name:") print(f"Hello {_name}") return f"Hello {_name}" if __name__ == "__main__": greet() __OUTPUT__ = """ Enter Your Name:Dev Hello Dev """
99fd18637c775da2d32751062eeda93824de852b
sven-oly/OsageText
/wordsearch.py
22,456
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Starting with # https://codereview.stackexchange.com/questions/98247/wordsearch-generator from __future__ import print_function #from builtins import range #from builtins import object import itertools import logging import random import sys from random import randint # Set up fill letters, including those with diacritics. # Should we done something with statistics? # Check for bad words? upper_letters = u'𐒰𐒱𐒲𐒳𐒴𐒵𐒶𐒷𐒸𐒹𐒺𐒻𐒼𐒽𐒾𐒿𐓀𐓁𐓂𐓃𐓄𐓅𐓆𐓇𐓈𐓉𐓊𐓋𐓌𐓍𐓎𐓏𐓐𐓑𐓒𐓓' lower_letters = u'𐓦𐓷𐓟𐓲𐓵𐓻𐓶𐓣𐓪𐓬𐓘𐓮𐓰𐓢𐓡𐓛𐓤𐓧𐓺𐓸𐓝𐓯𐓜𐓩𐓨𐓠𐓳𐓙𐓫𐓭𐓚𐓱𐓥𐓹𐓞' letters = lower_letters debug = True # Constants for word from the starting point RIGHT, DOWN, DOWNRIGHT, UPRIGHT, LEFT, UP, UPLEFT, DOWNLEFT = 0, 1, 2, 3, 4, 5, 6, 7 DIRECTIONS = [RIGHT, DOWN, DOWNRIGHT, UPRIGHT, LEFT, UP, UPLEFT, DOWNLEFT] DIR_OFFSETS = { RIGHT: [0,1], DOWN: [1, 0], DOWNRIGHT:[1, 1], UPRIGHT:[1, -1], LEFT: [0, -1], UP: [-1, 0], UPLEFT: [-1, -1], DOWNLEFT: [1, -1], } DIR_WORDS = ['right', 'down', 'down right', 'up right', 'left', 'up', 'up left', 'down left'] #### THE NEW IMPLEMENTATION. class Position(object): def __init__(self, x=0, y=0, dir=RIGHT): self.tokens = [] self.word = '' self.x = x self.y = y self.positions = [] # The grid locations for all self.direction = dir self.reversed = dir > UPRIGHT # Are the tokens in inverse order? self.clue = None # For crossword, show this def genPositions(self, length): # Creates the positions from the start, size, direction, reverse offset = DIR_OFFSETS[self.direction] self.positions = [(self.x, self.y)] for i in range(1, length): self.positions.append((self.positions[i-1][0] + offset[0], self.positions[i-1][1] + offset[1])) return def setTokens(self, tokens): self.tokens = tokens self.word = ''.join(tokens) class WordSearch(object): def __init__(self, words=None): self.grid = None self.words = words # The original inputs self.token_list = None # The tokenized word lists. self.do_diagonal = True self.do_reverse = True self.size = 0 self.width = 0 self.height = 0 self.wordlist = None self.answers = None self.current_level = 0 self.max_level = 0 self.max_solutions = 2 # Maximum number of solutions to be returned. self.all_directions = ['r', 'd', 'dr', 'ur'] self.level_answer = [] # Levels with tentative inserts self.setFillLetters(letters) # The tokens for the language self.current_solution = [] # List of the positions for the tokens in order. self.solutions_list = [] # For storing multiple results self.optimize_flag = False # Set if the "best" one is desired self.total_tests = 0 # How many testWordInsert calls made self.backtracks = 0 # Number of failed word inserts self.failed_inserts = 0 # Number of failed word inserts self.cells_filled = 0 # Now many filled with words. if self.words: self.token_list = [] for word in self.words: self.token_list.append(self.getTokens(word)) # By reversed length of token list. self.token_list.sort(key=len, reverse=True) #self.token_list = [self.getTokens(x) for x in self.words].sort(key=len, reverse=True) self.max_level = len(self.token_list) self.size = len(self.token_list[0]) logging.info('INIT self.size = %s' % self.size) self.width = self.height = self.size def generate(self, size=0, tries=None, num_solutions=None): logging.info('generate size = %s' % size) logging.info('generate self.size = %s' % self.size) if size > 0: self.size = self.width = self.height = max(size, self.size) self.generateGrid() result = self.generateLevel() self.finishGrid() def setFillLetters(self, fill_letters): self.fill_tokens = self.getTokens(fill_letters) def generateGrid(self): # set it up based on the if not self.token_list: return None self.grid = [[' ' for _ in range(self.size)] for __ in range(self.size)] def generateLevel(self): # A depth first search for positioning the word at current level # Are we done? this_level = self.current_level if this_level >= self.max_level: # This one is OK. self.rememberSolution() return True # Otherwise, this level needs to be searched. # Generate the possible positions for this word these_tokens = self.token_list[this_level] possible_positions = self.generateOptions(these_tokens) # Randomize the order of these. random.shuffle(possible_positions) # Take the last one and try to position it. If it fits, then go to next level. while len(possible_positions) > 0: test_position = possible_positions[-1] # The last one placed_ok = self.testWordInsert(these_tokens, test_position) if placed_ok: self.insertToGrid(these_tokens, test_position) self.current_level += 1 self.current_solution.append(test_position) test_position.setTokens(these_tokens) result = self.generateLevel() # The recursive call. if result == True: # Should we continue? num_solutions_found = len(self.solutions_list) # TODO: decide if we replace the solution, keep it in the list, or just end return True else: # Next level didn't work # Remove from grid if set at this level self.backtracks += 1 for pos in test_position.positions: y, x = pos[0], pos[1] value = self.grid[y][x] if value[-1] == self.current_level: self.grid[y][x] = ' ' # Clear/ # Remove this possible position and try again self.failed_inserts += 1 possible_positions.pop() # TODO: Remove from the grid. self.current_solution.pop() self.current_level -= 1 return False # At this point, all the possibilites are exhausted at this level. def rememberSolution(self): # Keep this solution as # TODO: Get the solution as a list of all the placements. self.solutions_list.append(self.current_solution) # TODO: evaluate this solution? def generateOptions(self, tokens): # Given the grid and the token, find all the places # where it could be placed, given grid size and # number of tokens in the word positions = [] length1 = len(tokens) - 1 for dir in DIRECTIONS: offset = (DIR_OFFSETS[dir][0] * length1, DIR_OFFSETS[dir][1] * length1) for x in range(0, self.width): for y in range(0, self.height): xend, yend = x + offset[0], y + offset[1] if xend >= 0 and xend < self.width and yend >= 0 and yend < self.height: pos = Position(x, y, dir) pos.genPositions(length1 + 1) positions.append(pos) return positions def insertToGrid(self, tokens, position): # Put the word at the next level for i in range(len(position.positions)): pos = position.positions[i] current_val = self.grid[pos[0]][pos[1]] if current_val and current_val == ' ': # Add at this level self.grid[pos[0]][pos[1]] = [tokens[i], self.current_level] else: # Value is already set at a previous level pass def testWordInsert(self, tokens, position): self.total_tests += 1 fits = True for i in range(len(position.positions)): pos = position.positions[i] current_val = self.grid[pos[0]][pos[1]] if current_val and current_val != ' ' and current_val[0] != tokens[i]: return False return fits def revertWordAtLevel(self): return True def evaluateGrid(self): # Returns something about the compactness and overlap return def finishGrid(self): # Fills in the blank spaces as needed self.cells_filled = 0 numTokens = len(self.fill_tokens) for i, j in itertools.product(list(range(self.width)), list(range(self.height))): if self.grid[i][j] == ' ' or self.grid[i][j] == '': self.grid[i][j] = self.fill_tokens[randint(0, numTokens - 1)] else: self.cells_filled += 1 return def deliverHints(self): # Either the words in the list or the clues return def getTokens(self, word): '''Get the tokens, not code points.''' # TODO: make this smarter utf-16 and diacritics. vals = list(word) retval = [] index = 0 while index < len(vals): item = '' v = ord(vals[index]) if v >= 0xd800 and v < + 0xdbff: item += vals[index] + vals[index + 1] index += 2 else: item += vals[index] index += 1 while index < len(vals) and ord(vals[index]) >= 0x300 and ord(vals[index]) <= 0x365: # It's a combining character. Add to the growing item. item += vals[index] index += 1 retval.append(item) return retval def printGrid(self): print('GRID SOLUTION of size %s' % self.size) for row in self.grid: for item in row: if type(item) is list: print(' %s%s ' % (item[0].encode('utf-8'), item[1]), end=' ') else: # Put in a flag to print _ in the fill spaces. print(' %s ' % item, end=' ') # '_'.encode('utf-8'), print() def formatAnswers(self): answers = {} for sol in self.solutions_list: for pos in sol: answers[pos.word] = (pos.positions, pos.word, pos.reversed, DIR_WORDS[pos.direction]) return answers def printSolution(self): print('Solution:') for sol in self.solutions_list: for pos in sol: print('%s, %s, reversed = %s' % (''.join(pos.tokens), DIR_WORDS[pos.direction], pos.reversed)) print(' %s' % pos.positions) def printStats(self): # Output information about the last run. print('%s solutions' % len(self.solutions_list)) print('%s total tests' % self.total_tests) print('%s total backtracks' % self.backtracks) print('%s failed insert' % self.failed_inserts) print('%s cells filled by words' % self.cells_filled) #### THE OLD IMPLEMENTATION. def makeGrid(words, size=[10, 10], attempts=10, is_wordsearch=True): '''Run attemptGrid trying attempts number of times. Size contains the height and width of the board. Word is a list of words it should contain.''' if debug: logging.info('makeGrid: size = %s, is_wordsearch = %s' % (size, is_wordsearch)) tokenList = [getTokens(x) for x in words].sort(key=len, reverse=True) for attempt in range(attempts): if debug: logging.info('makeGrid: try = %s' % (attempt)) try: return attemptGrid(words, size, is_wordsearch) except RuntimeError as e: logging.error('AttemptGrid error %s' % e) pass logging.info("ERROR - Couldn't create valid board") return None, None def attemptGrid(words, size, is_wordsearch=True): '''Attempt a grid of letters to be a wordsearch Size contains the height and width of the board. Word is a list of words it should contain. Returns the 2D list grid and a dictionary of the words as keys and lists of their co-ordinates as values.''' # logging.info('tokenList = %s', tokenList) # Make sure that the board is bigger than even the biggest set of tokens tokenList = [] for w in words: tokenList.append(getTokens(w)) if debug: logging.info('tokenList = %s', tokenList) sizeCap = (size[0] if size[0] >= size[1] else size[1]) sizeCap -= 1 if any(len(tokens) > sizeCap for tokens in tokenList): logging.info("ERROR: Too small a grid for supplied words: %s" % words) return None, None grid = [[' ' for _ in range(size[0])] for __ in range(size[1])] # Insert answers and store their locations answers = {} for word in words: grid, answer, reversed = insertWord(word, grid, None, is_wordsearch) if answer[0][0] == answer[-1][0]: direction = 'row' elif answer[0][1] == answer[-1][1]: direction = 'column' else: direction = 'diagonal' if reversed: # Put the coordinates in the right order answer.reverse() answers[word] = [answer, reversed, word, direction] # Add other characters to fill the empty space, if needed. if is_wordsearch: fillEmptyGridSlots(letters, grid, size) return grid, answers def fillEmptyGridSlots(letters, grid, size): # Add other characters to fill the empty space fillTokens = getTokens(letters) numTokens = len(fillTokens) for i, j in itertools.product(list(range(size[1])), list(range(size[0]))): if grid[i][j] == ' ': grid[i][j] = fillTokens[randint(0, numTokens - 1)] def insertWord(word, grid, invalid, is_wordsearch): '''Insert a word into the letter grid 'word' will be inserted into the 2D list grid. invalid is either None or a list of coordinates These coordinates are denote starting points that don't work. Returns an updated grid as well as a list of the added word's indices.''' if debug: logging.info('insert word %s' % word) height, width = len(grid), len(grid[0]) # TODO: Use the number of combined characters, not just length. tokens = getTokens(word) length = len(tokens) if is_wordsearch: max_dir = 3 else: max_dir = 1 # For crossword # Detect whether the word can fit horizontally or vertically. hori = width >= length + 1 vert = height >= length + 1 diag = False if hori and vert: # If both can be true, flip a coin to decide which it will be rint = randint(0, max_dir) hori = vert = diag = False if rint == 0: hori = True direction = 'x' elif rint == 1: vert = True direction = 'y' elif rint == 2: diag = True direction = 'dd' else: diag = True direction = 'du' line = [] # For storing the letters' locations if invalid is None: invalid = [[None, None, True], [None, None, False]] # new: Generate all the positions at which this word can start. positions = [] for x in range(0, width - length): for y in range(0, height - length): positions.append([x, y]) # Now generate a starting coordinate from the above. num_positions = len(positions) if num_positions < 1: print('only one position') rand_pos = randint(0, num_positions - 1) x = positions[rand_pos][0] y = positions[rand_pos][1] # Height * width is an approximation of how many attempts we need # Get a random position that fits for _ in range(height * width): if direction == 'x': x = randint(0, width - 1 - length) y = randint(0, height - 1) elif direction == 'y': x = randint(0, width - 1) y = randint(0, height - 1 - length) elif direction == 'dd': x = randint(0, width - 1 - length) y = randint(0, height - 1 - length) else: # Diagonal up x = randint(0, width - 1 - length) y = randint(length - 1, height - 1) if not is_wordsearch: # Make sure x and y are even values, so the grid is more open if x % 2: x -= 1 if y %2: y -= 1 if [y, x, direction] not in invalid: break else: # Probably painted into a corner, raise an error to retry. raise (RuntimeError) start = [y, x, direction] # Saved in case of invalid placement # logging.info('Start = %s' % start) if is_wordsearch: do_reverse = bool(randint(0, 1)) else: do_reverse = False # Not for crossword # Now attempt to insert each letter if do_reverse: tokens.reverse() line = tryPlacingWord(tokens, x, y, direction, grid) if line: for i, cell in enumerate(line): grid[cell[0]][cell[1]] = tokens[i] return grid, line, do_reverse else: # If it didn't work, we could try the reversed word. # But for now, just quit. invalid.append(start) return insertWord(word, grid, invalid, is_wordsearch) # Returns True if the word fits at the given spot with given direction. # Returns False if it doesn't fit. def tryPlacingWord(tokens, x, y, direction, grid): line = [] # For storing the letters' locations for letter in tokens: try: if grid[y][x] in (' ', letter): # Check if it's the letter or a blank. line.append([y, x]) if direction == 'x': x += 1 elif direction == 'y': y += 1 elif direction == 'dd': # And handle diagonal down, too! x += 1 y += 1 else: # And handle diagonal up! x += 1 y -= 1 else: return False except IndexError: print('IndexError x,y: [%s, %s]' % (x, y)) return line def getTokens(word): '''Get the tokens, not code points.''' # TODO: make this smarter utf-16 and diacritics. vals = list(word) retval = [] index = 0 while index < len(vals): item = '' v = ord(vals[index]) if v >= 0xd800 and v < + 0xdbff: item += vals[index] + vals[index + 1] index += 2 else: item += vals[index] index += 1 while index < len(vals) and ord(vals[index]) >= 0x300 and ord(vals[index]) <= 0x365: # It's a combining character. Add to the growing item. item += vals[index] index += 1 retval.append(item) return retval def printGrid(grid): '''Print the grid in a friendly format.''' width = len(grid[0]) print ("+" + ('---+' * width)) for i, line in enumerate(grid): print (u"| " + u" | ".join(line) + u" |") print ("+" + ('---+' * width)) def printAnswers(answers): for answer in answers: # print(' %s: %s' % answer, answers[answer]) print(answer, answers[answer]) # Runs with an array of words def generateWordsGrid(words): # words = [u'𐓏𐒻𐒷𐒻𐒷', u'𐓀𐒰𐓓𐒻͘', u'𐓏𐒰𐓓𐒰𐓓𐒷', u'𐒻𐒷𐓏𐒻͘ ', u'𐓈𐒻𐓍𐒷', u'𐒹𐓂𐓏𐒷͘𐒼𐒻', # u'𐓇𐓈𐓂͘𐓄𐒰𐓄𐒷', u'𐒰̄𐓍𐓣𐓟𐓸𐓟̄𐓛𐓣̄𐓬', u'𐒼𐒰𐓆𐒻𐓈𐒰͘', u'𐓏𐒰𐓇𐒵𐒻͘𐒿𐒰 ', # u'𐒻𐓏𐒻𐒼𐒻', u'𐓂𐓍𐒰𐒰𐒾𐓎𐓓𐓎𐒼𐒰'] # Set the size to be the maximum word length. max_xy = 0 total_tokens = 0 for word in words: # logging.info(word) tokens = getTokens(word) total_tokens += len(tokens) if len(tokens) > max_xy: max_xy = len(tokens) # logging.info('max size = %s ' % (max_xy)) grid, answers = makeGrid(words, [max_xy + 1, max_xy + 1], 10, True) return grid, answers, words, max_xy + 1 # Use the new Depth First Search method with size suggestion, etc. def generateDFSWordSearch(words, size=0, tries=None, num_solutions=1): ws = WordSearch(words) logging.info('words = %s' % words) logging.info('size = %s, tries = %s, num_solutions = %s' % (size, tries, num_solutions)) ws.generate(size, tries, num_solutions) return ws def generateCrosswordsGrid(words): # Make a grid with no reversals, no diagonals # Don't fill in the empty spaces max_xy = 0 total_tokens = 0 for word in words: # logging.info(word) tokens = getTokens(word) total_tokens += len(tokens) if len(tokens) > max_xy: max_xy = len(tokens) # Updated max_xy since it will be an open grid. max_xy = int(1.5 * max_xy) logging.info('generateCrosswordsGrid max size = %s ' % (max_xy)) grid, answers = makeGrid(words, [max_xy + 1, max_xy + 1], 10, False) return grid, answers, words, max_xy + 1 # Runs with a set grid def testGrid(): words = [u'𐓣𐓟𐓷𐓣͘', u' 𐓡𐓪𐓷𐓘͘𐓤', u'𐓏𐒰𐓓𐒰𐓓𐒷', u'𐒻𐒷𐓏𐒻͘ ', u'𐓈𐒻𐓍𐒷', u'𐒹𐓂𐓏𐒷͘𐒼𐒻', u'𐓇𐓈𐓂͘𐓄𐒰𐓄𐒷', u'𐒰̄𐓍𐓣𐓟𐓸𐓟̄𐓛𐓣̄𐓬', u'𐒼𐒰𐓆𐒻𐓈𐒰͘', u'𐓏𐒰𐓇𐒵𐒻͘𐒿𐒰 ', u'𐒻𐓏𐒻𐒼𐒻', u'𐓂𐓍𐒰𐒰𐒾𐓎𐓓𐓎𐒼𐒰'] max_xy = 0 total_tokens = 0 longest_word = None for word in words: tokens = getTokens(word) # logging.info('word, tokens = %s, %s ' % (word, len(tokens))) total_tokens += len(tokens) if len(tokens) > max_xy: longest_word = word max_xy = len(tokens) # logging.info('max size = %s, %s ' % (max_xy, longest_word)) grid, answers = makeGrid(words, [max_xy + 1, max_xy + 1], 10, False) return grid, answers, words, max_xy + 1 def testNewWordSearch(words, args): print('args = %s' % args) if args > 1: size = int(args[1]) else: size = 13 max_tries = 1000 num_solutions = 1 ws = generateDFSWordSearch(words, size, max_tries, num_solutions) print('%s words = %s' % (len(ws.token_list), [len(x) for x in ws.token_list])) print('max tokens = %s' % ws.size) print() ws.printGrid() print('%s solutions found' % len(ws.solutions_list)) print('Statistics\n') ws.printStats() ws.printSolution() def main(args): # The Osage works, with diacritics osageWords = [u'𐓏𐒻𐒷𐒻𐒷', u'𐓀𐒰𐓓𐒻͘', u'𐓏𐒰𐓓𐒰𐓓𐒷', u'𐒻𐒷𐓏𐒻͘ ', u'𐓈𐒻𐓍𐒷', u'𐒹𐓂𐓏𐒷͘𐒼𐒻', u'𐓇𐓈𐓂͘𐓄𐒰𐓄𐒷', u'𐒰̄𐓍𐓣𐓟𐓸𐓟̄𐓛𐓣̄𐓬'] words = [u'𐓣𐓟𐓷𐓣͘', u' 𐓡𐓪𐓷𐓘͘𐓤', u'𐓏𐒻𐒷𐒻𐒷', u'𐓀𐒰𐓓𐒻͘', u'𐓏𐒰𐓓𐒰𐓓𐒷', u'𐒻𐒷𐓏𐒻͘ ', u'𐓈𐒻𐓍𐒷', u'𐒹𐓂𐓏𐒷͘𐒼𐒻', u'𐓇𐓈𐓂͘𐓄𐒰𐓄𐒷', u'𐒰̄𐓍𐓣𐓟𐓸𐓟̄𐓛𐓣̄𐓬', u'𐒼𐒰𐓆𐒻𐓈𐒰͘', u'𐓏𐒰𐓇𐒵𐒻͘𐒿𐒰 ', u'𐒻𐓏𐒻𐒼𐒻', u'𐓂𐓍𐒰𐒰𐒾𐓎𐓓𐓎𐒼𐒰'] three_words = [u'𐓣𐓟𐓷𐓣͘', u'𐓡𐓪𐓷𐓘͘𐓤', u'𐓏𐒻𐒷𐒻𐒷', u'𐒹𐓂𐓏𐒷͘𐒼𐒻', u'𐒼𐒰𐓆𐒻𐓈𐒰͘', u'𐒻𐓏𐒻𐒼𐒻', u'𐓀𐒰𐓓𐒻͘', u'𐓂𐓍𐒰𐒰𐒾𐓎𐓓𐓎', u'𐓏𐒰𐓓𐒰𐓓𐒷', u'𐒰̄𐓍𐓣𐓟𐓸𐓟'] testNewWordSearch(three_words, args) #grid, answers = makeGrid(words, [12, 12], 10, False) # Try with a crossword #printGrid(grid) #printAnswers(answers) if __name__ == "__main__": print('ARGS = %s' % sys.argv) sys.exit(main(sys.argv))
0b941327c10837c48a21313dd56684479a70e4f7
huweitao/PythonScripts
/ReplaceString.py
489
3.546875
4
#-*- coding: UTF-8 -*- import sys def replaceString(oldOne,newOne,path): print("Replace %s to %s in %s" % (oldOne,newOne,path)) content = '' with open(path, 'r') as f: content = f.read().replace(oldOne,newOne) # print content if len(content) > 0: with open(path, 'w') as f: f.write(content) def main(oldOne,newOne,path): replaceString(oldOne,newOne,path) return True if __name__ == '__main__': params = sys.argv if len(params) == 4: main(params[1],params[2],params[3])
9de7b014aef2986a0ff6865e49360c76df99ef4f
blueweiwei/webGuolu
/src/test.py
11,207
3.53125
4
round(a, 3) def form1(self): self.data['0']['C4']=round((0.124*self.data['0']['C3']*100)/(100+0.124*self.data['0']['C3']),3) self.data['0']['C8']=round((100-self.data['0']['C4'])*self.data['0']['C7']/100,3) self.data['0']['D8']=round((100-self.data['0']['C4'])*self.data['0']['D7']/100,3) self.data['0']['E8']=round((100-self.data['0']['C4'])*self.data['0']['E7']/100,3) self.data['0']['F8']=round((100-self.data['0']['C4'])*self.data['0']['F7']/100,3) self.data['0']['G8']=round((100-self.data['0']['C4'])*self.data['0']['G7']/100,3) self.data['0']['H8']=round((100-self.data['0']['C4'])*self.data['0']['H7']/100,3) self.data['0']['E8']=round((100-self.data['0']['C4'])*self.data['0']['E7']/100,3) self.data['0']['E8']=round((100-self.data['0']['C4'])*self.data['0']['E7']/100,3) self.data['0']['C15']=round(21/(21-79*((self.data['0']['C13']-0.5*self.data['0']['E13']-0.5*self.data['0']['F13']-2*self.data['0']['H13'])/(self.data['0']['G13']-(self.data['0']['H8']*(self.data['0']['D13']+self.data['0']['E13']+self.data['0']['H13']))/(self.data['0']['D8']+self.data['0']['C8']+self.data['0']['F8'])))),3) self.data['0']['C16']=round(0.0238*(self.data['0']['E8']+self.data['0']['C8'])+0.0925*self.data['0']['F8'],3) self.data['0']['C17']=round(0.01*(self.data['0']['C8']+3*self.data['0']['F8']+self.data['0']['D8']+self.data['0']['E8']+self.data['0']['H8']+self.data['0']['C4'])+0.79*self.data['0']['C16'],3) self.data['0']['C18']=round(self.data['0']['C17']+(self.data['0']['C15']*(1+0.00124*self.data['0']['C10'])-1)*self.data['0']['C16'],3) self.data['0']['D19']=round(100/(100+1.88*self.data['0']['E13']+1.88*self.data['0']['F13']+9.52*self.data['0']['H13']-4.762*self.data['0']['C13']),3) self.data['0']['C9']=round(126.36*self.data['0']['C8']+107.85*self.data['0']['E8']+358.81*self.data['0']['F8'],3) self.data['0']['C20']=round(((0.01*(2*self.data['0']['F8']+self.data['0']['E8']+self.data['0']['C4'])+0.00124*(self.data['0']['C10'])*(self.data['0']['C15'])*(self.data['0']['C16']))/(self.data['0']['D19']*self.data['0']['C18']))*100,3) self.data['0']['C14']=round(((100-self.data['0']['C20'])/100)*self.data['0']['C13'],3) self.data['0']['D14']=round(((100-self.data['0']['C20'])/100)*self.data['0']['D13'],3) self.data['0']['E14']=round(((100-self.data['0']['C20'])/100)*self.data['0']['E13'],3) self.data['0']['F14']=round(((100-self.data['0']['C20'])/100)*self.data['0']['F13'],3) self.data['0']['G14']=round(((100-self.data['0']['C20'])/100)*self.data['0']['G13'],3) self.data['0']['H14']=round(((100-self.data['0']['C20'])/100)*self.data['0']['H13'],3) def form2(self): self.data['1']['D5']=round(self.rrb(self.data['1']['C5'],'一氧化碳'),3) self.data['1']['E5']=round(self.rrb(self.data['1']['C5'],'二氧化碳'),3) self.data['1']['F5']=round(self.rrb(self.data['1']['C5'],'氢气'),3) self.data['1']['G5']=round(self.rrb(self.data['1']['C5'],'氮气'),3) self.data['1']['D6']=round(self.rrb(self.data['1']['C6'],'一氧化碳'),3) self.data['1']['E6']=round(self.rrb(self.data['1']['C6'],'二氧化碳'),3) self.data['1']['F6']=round(self.rrb(self.data['1']['C6'],'氢气'),3) self.data['1']['G6']=round(self.rrb(self.data['1']['C6'],'氮气'),3) self.data['1']['D7']=round(self.rrb(self.data['1']['C7'],'一氧化碳'),3) self.data['1']['E7']=round(self.rrb(self.data['1']['C7'],'二氧化碳'),3) self.data['1']['F7']=round(self.rrb(self.data['1']['C7'],'氢气'),3) self.data['1']['G7']=round(self.rrb(self.data['1']['C7'],'氮气'),3) self.data['1']['C8']=round((self.data['1']['D5']*self.data['0']['C8']+self.data['1']['E5']*self.data['0']['D8']+self.data['1']['F5']*self.data['0']['E8']+self.data['1']['G5']*self.data['0']['H8'])/100,3) self.data['1']['C9']=round((self.data['1']['D7']*self.data['0']['C8']+self.data['1']['E7']*self.data['0']['D8']+self.data['1']['F7']*self.data['0']['E8']+self.data['1']['G7']*self.data['0']['H8'])/100,3) self.data['1']['C10']=round((self.data['1']['D6']*self.data['0']['E14']+self.data['1']['E6']*self.data['0']['D14']+self.data['1']['F6']*self.data['0']['F14']+self.data['1']['G6']*self.data['0']['G14'])/100,3) self.data['1']['C11']=round((self.data['1']['D7']*self.data['0']['E14']+self.data['1']['E7']*self.data['0']['D14']+self.data['1']['F7']*self.data['0']['F14']+self.data['1']['G7']*self.data['0']['G14'])/100,3) def form3(self): self.data['2']['E5']=round(self.rrb(self.data['2']['C5'],'干空气'),3) self.data['2']['E6']=round(self.rrb(self.data['2']['C6'],'干空气'),3) self.data['2']['E7']=round(self.rrb(self.data['2']['C7'],'干空气'),3) self.data['2']['E8']=round(self.rrb(self.data['2']['C8'],'干空气'),3) def form4(self): self.data['3']['E5']=round(self.data['1']['C8'],3) self.data['3']['F5']=round(self.data['1']['C9'],3) def form6(self): self.data['5']['H4']=round(self.data8(self.data['5']['F4'],'传热系数'),3) self.data['5']['H5']=round(self.data8(self.data['5']['F5'],'传热系数'),3) self.data['5']['H6']=round(self.data8(self.data['5']['F6'],'传热系数'),3) self.data['5']['H7']=round(self.data8(self.data['5']['F7'],'传热系数'),3) self.data['5']['H8']=round(self.data8(self.data['5']['F8'],'传热系数'),3) self.data['5']['H9']=round(self.data8(self.data['5']['F9'],'传热系数'),3) self.data['5']['H10']=round(self.data8(self.data['5']['F10'],'传热系数'),3) self.data['5']['H11']=round(self.data8(self.data['5']['F11'],'传热系数'),3) self.data['5']['H12']=round(self.data8(self.data['5']['F12'],'传热系数'),3) self.data['5']['J4']=round(self.data['5']['H4']*(self.data['5']['F4']-self.data['5']['G4']),3) self.data['5']['J5']=round(self.data['5']['H5']*(self.data['5']['F5']-self.data['5']['G4']),3) self.data['5']['J6']=round(self.data['5']['H6']*(self.data['5']['F6']-self.data['5']['G4']),3) self.data['5']['J7']=round(self.data['5']['H7']*(self.data['5']['F7']-self.data['5']['G4']),3) self.data['5']['J8']=round(self.data['5']['H8']*(self.data['5']['F8']-self.data['5']['G4']),3) self.data['5']['J9']=round(self.data['5']['H9']*(self.data['5']['F9']-self.data['5']['G4']),3) self.data['5']['J10']=round(self.data['5']['H10']*(self.data['5']['F9']-self.data['5']['G4']),3) self.data['5']['J11']=round(self.data['5']['H11']*(self.data['5']['F9']-self.data['5']['G4']),3) self.data['5']['J12']=round(self.data['5']['H12']*(self.data['5']['F9']-self.data['5']['G4']),3) def form9(self): self.data['8']['F8']=round(self.data['8']['F6']*self.data['4']['C5']*(1-self.data['8']['F7'])*60,3) self.data['8']['F9']=round((self.data['3']['C5']*self.data['7']['C4'])/(self.data['8']['F8']*self.data['7']['D4']),3) self.data['8']['F10']=round(self.data['0']['C16']*(1+0.00124*self.data['0']['C3']),3) self.data['8']['D6']=round(self.data['8']['F9']*self.data['0']['C9'],3) self.data['8']['D7']=round(self.data['8']['F9']*(self.data['1']['C8']*self.data['1']['C5']-self.data['1']['C9']*self.data['1']['C7']),3) self.data['8']['D8']=round(self.data['8']['F9']*self.data['0']['C15']*self.data['8']['F10']*(self.data['2']['E6']*self.data['2']['C6']-self.data['2']['E5']*self.data['2']['C5']),3) self.data['8']['D9']=round(self.data['2']['E7']*self.data['2']['C7']-self.data['2']['E5']*self.data['2']['C5'],3) self.data['8']['D10']=round(self.data['8']['D6']+self.data['8']['D7']+self.data['8']['D8']+self.data['8']['D9'],3) def form10(self): self.data['9']['D4']=round(self.data['2']['E8']*self.data['2']['C8']-self.data['2']['E5']*self.data['2']['C5'],3) self.data['9']['D5']=round(self.data['8']['F9']*self.data['0']['C18']*self.data['0']['D19']*(self.data['1']['C10']*self.data['1']['C6']-self.data['1']['C11']*self.data['1']['C7']),3) self.data['9']['D6']=round(self.data['8']['F9']*self.data['0']['C17']*self.data['0']['D19']*(126.36*self.data['0']['E14']+107.85*self.data['0']['F14']),3) self.data['9']['D7']=round(self.data['7']['E4']*3600*(self.data['5']['J4']*self.data['5']['D4']+self.data['5']['J5']*self.data['5']['D5']+self.data['5']['J6']*self.data['5']['D6'])/(self.data['8']['F8']*self.data['7']['D4']),3) self.data['9']['D8']=round(self.data['7']['E4']*3600*(self.data['5']['J7']*self.data['5']['D7'])/(self.data['8']['F8']*self.data['7']['D4']),3) self.data['9']['D9']=round(self.data['7']['E4']*3600*(self.data['5']['J8']*self.data['5']['D8'])/(self.data['8']['F8']*self.data['7']['D4']),3) self.data['9']['D10']=round(self.data['7']['E4']*3600*(self.data['5']['J9']*self.data['5']['D9'])/(self.data['8']['F8']*self.data['7']['D4']),3) self.data['9']['D11']=round((self.data['9']['K3']*self.data['7']['E4']*(self.data['9']['K7']*self.data['9']['K5']-self.data['9']['K6']*self.data['9']['K4']))/(self.data['8']['F8']*self.data['7']['D4']),3) self.data['9']['D12']=round(self.data['8']['F9']*self.data['9']['K8']*0.001*(4.18*(100-self.data['1']['C5'])+2253+5.2*(1*self.data['1']['C6']-36)),3) self.data['9']['D13']=round(self.data['5']['D10']*self.data['5']['J10']*self.data['7']['E4']/(self.data['8']['F8']*self.data['7']['D4']),3) self.data['9']['D14']=round(self.data['5']['D11']*self.data['5']['J11']*self.data['7']['E4']/(self.data['8']['F8']*self.data['7']['D4']),3) self.data['9']['D15']=round(self.data['5']['D12']*self.data['5']['J12']*self.data['7']['E4']/(self.data['8']['F8']*self.data['7']['D4']),3) self.data['9']['G4']=round(3.13*(self.data['6']['C4']/2)*(self.data['6']['C4']/2)*self.data['6']['D4'],3) self.data['9']['D16']=round((self.data['9']['G4']*(self.data['2']['E8']*self.data['2']['C8']-self.data['2']['E5']*self.data['2']['C5']))/(self.data['8']['F8']*self.data['7']['D4']),3) self.data['9']['D17']=round(self.data['8']['D10']-(self.data['9']['D4']+self.data['9']['D5']+self.data['9']['D6']+self.data['9']['D7']+self.data['9']['D8']+self.data['9']['D9']+self.data['9']['D10']+self.data['9']['D16']+self.data['9']['D11']+self.data['9']['D13']+self.data['9']['D14']+self.data['9']['D15']),3) def form12(self): self.data['11']['F4']=round(self.data['4']['F5'],3) self.data['11']['F6']=round(self.data['4']['G5'],3) self.data['11']['F7']=round(self.data['3']['C5'],3) self.data['11']['F8']=round(self.data['8']['F8'],3) self.data['11']['F9']=round(self.data['8']['D6'],3) def form13(self): self.data['12']['C3']=round((self.data['9']['D17']/self.data['8']['D10'])*100,3) self.data['12']['C5']=round(100*(self.data['9']['D4']-self.data['8']['D9']+self.data['9']['D8']+self.data['9']['D9'])/(self.data['8']['D10']-self.data['8']['D9']),3) self.data['12']['C6']=round(100*(self.data['9']['D4']-self.data['8']['D9'])/(self.data['8']['D10']-self.data['8']['D9']),3)
9fb66acdcfb1f4a07a2a948e87d9ffdec6665d42
challeger/leetCode
/模拟面试/leetCode_159_地下城游戏.py
2,369
3.640625
4
""" day: 2020-09-11 url: https://leetcode-cn.com/problems/dungeon-game/ 题目名: 地下城游戏 一些恶魔抓住了公主(P)并将她关在了地下城的右下角.地下城是由 M x N 个房间组成的二维网格. 我们英勇的骑士(K)最初被安置在左上角的房间里,他必须穿过地下城并通过对抗恶魔来拯救公主. 骑士的初始健康点数为一个正整数.如果他的健康点数在某一时刻降至 0 或以下,他会立即死亡. 有些房间由恶魔守卫,因此骑士在进入这些房间时会失去健康点数(若房间里的值为负整数,则表示骑士将损失健康点数); 其他房间要么是空的(房间里的值为 0),要么包含增加骑士健康点数的魔法球(若房间里的值为正整数,则表示骑士将增加健康点数. 为了尽快到达公主,骑士决定每次只向右或向下移动一步 编写一个函数来计算确保骑士能够拯救到公主所需的最低初始健康点数. 例如,考虑到如下布局的地下城,如果骑士遵循最佳路径 右 -> 右 -> 下 -> 下,则骑士的初始健康点数至少为 7. [ [-2, -3, 3], [-5, -10, 1], [10, 30, -5] ] 思路: 如果我们从起点来进行状态转移,需要记录两个关键值, 一个是从出发点到当前点的路径和,一个是从出发点到当前点所需的最小初始值. 如果我们从终点开始进行状态转移,用dp[i][j]表示从坐标(i, j)到达终点需要的最小血量,那么我们 无需记录路径和,因为只要我们的路径和不小于dp[i][j],就能到达终点, """ from typing import List class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: m = len(dungeon) n = len(dungeon[0]) # dp表示到达dungeon[i][j]需要的最小初始值 dp = [[float('inf')] * (n+1) for _ in range(m+1)] dp[m][n-1] = dp[m-1][n] = 1 for i in range(m-1, -1, -1): for j in range(n-1, -1, -1): # 选择需要血量较少的路径 min_hp = min(dp[i+1][j], dp[i][j+1]) # 如果dungeon是个回血包,到达这个格子之前他的血量至少要为1 dp[i][j] = max(min_hp-dungeon[i][j], 1) return dp[0][0] s = Solution() print(s.calculateMinimumHP([[-2, -3, 3], [-5, -10, 1], [10, 30, -5]]))
cf38bbcbf57707b6f9e4255da2bcc0414cb4ea79
SWHarrison/CS-1-3
/call_routing_project/decimal_search_tree.py
6,885
3.75
4
import pickle, time class DecimalTreeNode(object): def __init__(self, data): """Initialize this Decimal tree node with the given data.""" self.data = data self.nexts = [None] * 10 def __repr__(self): """Return a string representation of this Decimal tree node.""" return 'DecimalTreeNode({!r})'.format(self.data) def is_leaf(self): """Return True if this node is a leaf (has no children).""" # TODO: Check if both left child and right child have no value for next in self.nexts: if next != None: return False return True def is_branch(self): """Return True if this node is a branch (has at least one child).""" # TODO: Check if either left child or right child has a value return not self.is_leaf() def height(self): """Return the height of this node (the number of edges on the longest downward path from this node to a descendant leaf node). Best case: O(1) when node is a leaf Worst case: O(n) when node is root and n is items in tree""" if(self.is_leaf()): # base case return 0 heights = [] for next in self.nexts: if(next != None): heights.append(next.height()) max_height = max(heights) return 1 + max_height # visit current node class DecimalSearchTree(object): def __init__(self): """Initialize this Decimal search tree and insert the given items.""" self.root = DecimalTreeNode('+') self.size = 0 self.num_nodes = 0 def __repr__(self): """Return a string representation of this Decimal search tree.""" return 'DecimalSearchTree({} nodes)'.format(self.size) def is_empty(self): """Return True if this Decimal search tree is empty (has no nodes).""" return self.root is None def height(self): """Return the height of this tree (the number of edges on the longest downward path from this tree's root node to a descendant leaf node). Best case: O(1) when root is a leaf Worst case: O(n) when node is root and n is items in tree""" if(not self.is_empty()): return self.root.height() return None def contains(self, number, node): """Return True if this Decimal search tree contains the given number. Best case: O(1) when root has the number Worst case: O(log n) when node is lowest level of tree""" if(len(number) == 0): return True digit = number[0] remainder = number[1:] if(node.nexts[digit] != None): self.contains(remainder, node.nexts[digit]) else: return False def search(self, number): return self._search(number, self.root) def _search(self, number, node): """Return an number in this Decimal search tree matching the given number, or None if the given number is not found. Best case: O(1) when root has the number Worst case: O(log n) when node is lowest level of tree""" if(len(number) == 0): print("returning node data ", node.data) return node.data digit = int(number[0]) remainder = number[1:] if(node.nexts[digit] != None): return self._search(remainder, node.nexts[digit]) else: return None def insert(self, number, data): #print("inserting base: ",number) self._insert(number, data, self.root) def _insert(self, number, data, node): """Insert the given number in order into this Decimal search tree. Best case: O(1) when adding to empty tree Worst case: O(log n) when node is lowest level of tree""" # Handle the case where the tree is empty if(len(number) == 0): if(node.data == None): self.size += 1 node.data = data elif(node.data > data): node.data = data return digit = int(number[0]) remainder = number[1:] if(node.nexts[digit] == None): node.nexts[digit] = DecimalTreeNode(None) self.num_nodes += 1 self._insert(remainder, data, node.nexts[digit]) def replace(self, number, data): self._replace(number, data, self.root) def _replace(self, number, data, node): """Insert the given number in order into this Decimal search tree. Best case: O(1) when adding to empty tree Worst case: O(log n) when node is lowest level of tree""" # Handle the case where the tree is empty if(len(number) == 0): node.data = data return digit = int(number[0]) remainder = number[1:] if(node.nexts[digit] == None): raise KeyError ('Number not in tree') self._replace(remainder, data, node.nexts[digit]) def find_price(self, number): current_best_price = None node = self.root digit = int(number[0]) remainder = number[1:] while(node.nexts[digit] != None): #print("current best price is",current_best_price) node = node.nexts[digit] if(node.data != None): current_best_price = node.data #print("remainder of number is", remainder) if(len(remainder) > 0): digit = int(remainder[0]) remainder = remainder[1:] else: break #print("returning best price as",current_best_price) return current_best_price if __name__ == '__main__': current = time.perf_counter() file = open('route-costs-10000000.txt','r') read_numbers = file.readlines() file.close() print(time.perf_counter()-current) tree = DecimalSearchTree() for number in read_numbers: split_number = number.strip().split(',') phone_num = split_number[0][1:] cost = float(split_number[1]) #print(phone_num) #print(cost) tree.insert(phone_num,cost) print(tree.size) print(tree.num_nodes) print(time.perf_counter()-current) pickle.dump(tree, open( "save.p", "wb" )) #tree = pickle.load( open( "save.p", "rb" ) ) #print("time to load:",time.perf_counter()-current) '''print(tree.size) file = open('phone-numbers-10000.txt','r') read_numbers = file.readlines() file.close() file2 = open('phone-numbers-10000-test.txt',"w") for number in read_numbers: number = number.strip() phone_num = number[1:] cost = tree.find_price(phone_num) file2.write(phone_num + " cost: " + str(cost)+"\n") file2.close() print("time to check numbers:",time.perf_counter()-current)'''
8c73f517e974f3c44227c4bc82a3f6a45d56359e
yuanguLeo/untitled1
/CodeDemo/shangxuetang/com.shangxuetang/func_04.py
437
3.671875
4
#!/usr/bin/env python #_*_coding:utf-8_*_ import time import math def test01(): start = time.time() for i in range(10000000): math.sqrt(30) end = time.time() print("test01()耗时为:{0}".format((end-start))) def test02(): a = math.sqrt start = time.time() for i in range(10000000): a(30) end = time.time() print("test02()耗时为:{0}".format((end-start))) test01() test02()
ecf01ed0a9fb62072101b59b24b417fbdf8dfe1a
whitefang82/simple_Python
/lesson20.py
379
4.09375
4
#Password """while True: print("Enter your age: ") age = input() if age.isdecimal(): break print("Only number!")""" while True: print("Enter your Password: ") password = input() length = len(password) print(length) if password.isalnum() and length >= 6: break print("Only letters and numbers and at least 6 characters!")
23d2821b1c07c338ac94fc5ad96dab96d5d3a27b
Sidhrth/NNproject
/fourlevelFP.py
1,142
3.875
4
import numpy as np #example is housing prices # X input variables - size, age, distance to market X = np.array(([100, 20, 3000], [400, 5, 100], [240, 10, 1000]), dtype=float) y = np.array(([300], [900], [500]), dtype=float) # Feature scaling X = X/np.amax(X, axis=0) y = y/1000 class Neural_Network(object): def __init__(self): self.inputnodes = 3 self.outputnodes = 1 self.hiddennodes1 = 3 self.hiddennodes2 = 3 #weights self.W1 = np.random.randn(self.inputnodes, self.hiddennodes1) self.W2 = np.random.randn(self.hiddennodes1, self.hiddennodes2) self.W3 = np.random.randn(self.hiddennodes2, self.outputnodes) #forward propagation def forward(self, X): self.z = np.dot(X, self.W1) self.z2 = self.sigmoid(self.z) self.z3 = np.dot(self.z2, self.W2) self.z4 = self.sigmoid(self.z3) self.z5 = np.dot(self.z4,self.W3) o = self.sigmoid(self.z5) return o #activation def sigmoid(self, s): return 1/(1+np.exp(-s)) NN = Neural_Network() #defining our output o = NN.forward(X) print "Predicted Output: \n" + str(o) print "Actual Output: \n" + str(y)
873daae0513be4c7dee7336e139c90ff550a7195
christinalycoris/Python
/factorial_while.py
250
4.09375
4
n = int(input("Please enter a number: ")) counter = 0 product = 1 i = 1 while i <= n: product = product * i counter += 1 if i > n: break print(i, end=" × ") i+=1 print("END") print("The product of " + str(n) + "! is " + str(product) )
6256575470f52184c33241ffdb44053e633e4791
sheikhusmanshakeel/leet_code
/strings/3.py
1,092
3.65625
4
# https://leetcode.com/problems/longest-substring-without-repeating-characters/ def longest_substring(s): if not s: return 0 if len(s) == 1: return 1 seen = dict() longest_length = 0 for c in s: if seen.__contains__(c): if longest_length < len(seen): longest_length = len(seen) seen = {c: c} # This is the problem here. I am losing the entire dictionary else: seen[c] = c return longest_length def other_solution(s): start = max_length = 0 seen = {} for i in range(len(s)): if s[i] in seen and start <= seen[s[i]]: start = seen[s[i]] + 1 else: new_length = i - start + 1 max_length = max(max_length, new_length) seen[s[i]] = i return max_length print(other_solution("usman shakeel l")) print(longest_substring(" ")) print(longest_substring("0")) print(longest_substring(" abc abcbb ")) print(longest_substring("pwwkew")) print(longest_substring("abcabcbb")) print(longest_substring("bbbbbbbb"))
2c8f7a232e4908299da31bcd54cd2531e8df6746
Roberick313/First-project
/The_class.py
19,774
4.0625
4
import getpass class Main: def __init__(self, number=None, array=None, first_number=None, second_number=None, operand=None, word=None, parameter=None, my_input=None, input_str=None): self.number = number self.array = array self.first_number = first_number self.second_number = second_number self.operand = operand self.word = word self.parameter = parameter self.my_input = my_input self.input_str = input_str def fibonacci(self, number: int): """This function will calculate the fibonacci of the\r entry parameter""" self.number = number b = 0 result = '' c = 1 final_result = None for _ in range(1, self.number + 1): while b < self.number: result += str(b) + "," b = b + c if c <= self.number: result += str(c) + ',' c = b + c if result.endswith(','): final_result = result[0:len(result) - 1] return final_result def my_factorial(self, number: int): """this function will return the factorial of the entry parameter\r and have a default parameter in case that it doesnt get any parameter.""" self.number = number storage = 1 counter = 1 f = open('My_factorial.txt', 'w') f.write('') f.close() if self.number: while counter <= self.number: storage *= counter counter += 1 return f'the factorial of {self.number} is {storage}' else: self.number = [2, 3, 5, 8, 9] for i in self.number: while counter <= i: storage *= counter counter += 1 f = open('My_factorial.txt', 'a') f.write('the factorial of: ' + str(i) + ' ' + 'is' + ' ' + str(storage) + '\n') f.close() return open('My_factorial.txt').read() def decorator(self, a, b): def my_decorator(func): def inner_func(a, b): if a == 0 or b == 0: raise ValueError return func(a, b) return inner_func @my_decorator def double(a, b): return "the result of divide is %6.2f" % (a / b) return double(a, b) def max_min(self, array): self.array = array if not self.array: self.array = [20, 50, 2] min_number = self.array[0] max_number = self.array[0] for FirstVal in self.array: if float(max_number) < float(FirstVal): max_number = FirstVal elif float(min_number) > float(FirstVal): min_number = FirstVal return f'the Greatest number is: {max_number} and the Least Number is: {min_number}' def vowel_sound(self, word): """this function will count the number of vowel sound that it takes.""" self.word = word a = 0 e = 0 i = 0 o = 0 u = 0 for first_for in self.word: if first_for in 'aA': a += 1 elif first_for in 'eE': e += 1 elif first_for in 'iI': i += 1 elif first_for in 'oO': o += 1 elif first_for in 'uU': u += 1 return f'\ra: {a}\ne: {e}\ni: {i}\no: {o}\nu: {u}' def simple_calculator(self, first_number: float, second_number: float, operand: str): self.first_number = first_number self.second_number = second_number self.operand = operand if self.operand == '+': my_sum = self.first_number + self.second_number return f'the Division of two numbers is: {my_sum}' elif self.operand == '*': multi = self.first_number * self.second_number return f'the Division of two numbers is: {multi}' elif self.operand == '-': sub = self.first_number - self.second_number return f'the Division of two numbers is: {sub}' elif self.operand == '/': div = self.first_number / self.second_number return f'the Division of two numbers is: {div}' elif self.operand == '**': power = self.first_number ** self.second_number return f'the Division of two numbers is: {power}' def ord_asci(self, parameter): """ This Function will return the ascci code of characters and character of numbers that has given to it. ________________________ For call the function you need to enter a single string that can contain numbers and character. for example: main("57 67 39 67 213 Roberick")""" self.parameter = parameter number = '' character = '' sepi = my_separator(self.parameter) def my_ord(i3): nonlocal number number += chr(int(i3)) + ' ' return number def my_char(i2): nonlocal character for ss in i2: character += str(ord(ss)) + ' ' return character for i in sepi: try: if int(i): my_ord(i) except: my_char(i) if number.endswith(" "): number = number[:(len(number) - 1)] if character.endswith(" "): character = character[:(len(character) - 1)] return f'"({self.parameter})" converted to: \nnumbers are:"{number}". \ncharacters are:"{character}".' def lower_upper(self, input_str): """This Function will return the vice versa of the entered sentence""" try: self.input_str = input_str result = '' # todo :-32 my_dict = { 65: 97, 66: 98, 67: 99, 68: 100, 69: 101, 70: 102, 71: 103, 72: 104, 73: 105, 74: 106, 75: 107, 76: 108, 77: 109, 78: 110, 79: 111, 80: 112, 81: 113, 82: 114, 83: 115, 84: 116, 85: 117, 86: 118, 87: 119, 88: 120, 89: 121, 90: 122, } for i in self.input_str: if 65 <= ord(i) <= 90: result += chr(my_dict[ord(i)]) elif 97 <= ord(i) <= 122: for key, value in my_dict.items(): if value == ord(i): result += chr(key) else: result += i except TypeError or ValueError: return f'''You entered wrong value. \rEnter a sentence like: \r"RobeRIcK" ''' except: return f'what the hell did you entered??!? :))' else: return result def counting_str(self, my_input): """This function will return the index and the Repeated time of Roberick in the entered sentence """ self.my_input = my_input counter_test = 0 sentence = '' counter_of_word = 0 try: # checking the length of the Input... if len(self.my_input) < 10: self.my_input = 'python language tutorials by Roberick' print(f'''you entered a sentence less than 10 character. \rthe default sentence is: \r"python language tutorials by Roberick"''') # I used my own module to separate the sentence to a list cup_1 = my_separator(self.my_input) # this loop is just to count the repeated time # of Roberick in the sentence for i in cup_1: if 'roberick' in i.lower(): counter_of_word += 1 # this loop here is to find out the index of the first # Roberick in the sentence for i2 in self.my_input: sentence += i2 counter_test += 1 # to find the roberick and its index if 'roberick' in sentence.lower(): counter_test = counter_test - 8 break # this condition is for clear the # sentence variable if i2 == ' ': sentence = '' continue except: return f'something wrong happens pls try again.' return f'''Repeated time of Roberick: {counter_of_word} \rthe index of first Roberick in this sentence: {counter_test}''' @property def register(self): """ This function will do the registry stuff. check if the username exist or not. add the username to the database. encrypt the password and check if the password enter correct or not. """ while True: try: # Opening the file my_data = open("my_data_base.txt") my_data_2 = open("my_data_base.txt", 'a') # Get username set_username = input("Enter a user name for your account: ") # In case the username is back or end if set_username.lower() == 'back' or set_username.lower() == "end": exit_question = input("Do you want to take a step back?(y/n): ") if exit_question == "y" or exit_question == "yes" or exit_question == "yep": return False else: print("This username that u entered has been reserved. please try something else") continue # Check if the username is exist in database for i in my_data.readlines(): username_checker = my_separator(i) if username_checker == [] or set_username == username_checker[0]: if not username_checker: continue else: raise ValueError # Add the username to the data base else: my_data_2.write('\n' + set_username + ' ' + ":" + " ") # specific loop for getting password while True: print("the password wont show up when you typing...") set_password = getpass.getpass(prompt="Enter a password for your account: ") # set_password = input("Enter a password for your account: ") # Check that the entry password is empty or less than 4 char... if len(set_password) < 4 or len(set_password) > 16: print('Your password should has more than 3 and less than 16 character') continue # make sure that the user typed the desire password correct elif set_password: confirm_password = getpass.getpass(prompt="Enter your password again to confirm it: ") # End the loop if set_password == confirm_password: # Put the encrypted password for the entry user in database my_password = str(encoder(set_password)) my_data_2.write(my_password) # Close the file my_data.close() my_data_2.close() return True else: print("the password doesn't match.") continue # Put the encrypted password for the entry user in database # my_password = str(encoder(set_password)) # my_data_2.write(my_password) # Close the file my_data.close() my_data_2.close() # In case that the username was exist except ValueError: print('the username that you entered has exist. Try another username...') continue except IndexError: print('Something wrong happened!.') pass else: break def log_in(self): """This function is check the entry username in my own created database and encrypted the password that entered and compared it with the one that set for the entered username in the database.""" # set needed value import time counter = 0 flag = False password_checker = None # Main loop while True: try: # set flag in case the user is correct # and stop repeating for getting username # when the password entered wrong or ... if not flag: # Take the username my_data_base = open("my_data_base.txt") take_username = input("Enter your user name please: ") # Check if the value is not empty if take_username: if take_username.lower() == "back" or take_username.lower() == "end": exit_checker = input("Do you want to take a step back?(y/n): ") if exit_checker == "y" or exit_checker == "yes" or exit_checker == "yep": return False else: print("This username has been reserved. please try something else") continue # Search for the entered username in database for i in my_data_base.readlines(): # Make a list of user and password for each line username_checker = my_separator(i) # Check if the entered username # is exist in each line of database if take_username == username_checker[0]: # Change the flag to true to prevent from the repetition # Make an instance of encrypted password that belongs # to the entered username... flag = True password_checker = username_checker[1] break if not flag: # In case that the entered username has not existence print("The username is not exist.Try again or sign up.") continue # Take the password # Encrypt the entered password # Make a counter for avoiding the Bruteforce attack... take_password = getpass.getpass(prompt="Enter your password please: ") encode_password = encoder(take_password) counter += 1 # Check if the entered password is correct if str(encode_password) == password_checker: counter = 0 print("\n" + f"Welcome dear {take_username}") return True # time.sleep(3) # Preventing from BruteForce attack. # Can add some feature or change the waiting time. elif counter == 3: print(f"You tried {counter} time to enter." "You have to wait 10 sec and then try again.") time.sleep(10) counter = 0 continue # For letting the user try entering password # if it was wrong... else: my_data_base.close() continue # Just to make sure that it handle but didnt get any ValueError yet except ValueError: print("ValueError") except IndexError: with open("my_data_base.txt") as f: index = 0 my_list = f.readlines() # len_l = len(my_list) for line in my_list: if take_username in line: del my_list[index] index += 1 f.close() with open("my_data_base.txt", "w") as f: f.writelines(my_list) f.close() flag = False continue def my_separator(character: str) -> list: """This function will make a list of its entry parameter and separate each word or numerical number to a member of the list the criterion of the separator is: ["space", ":", "-", "_", ",", "\n", "\r", ]""" l1 = [] ss = '' counter = 0 for i in character: if i == ' ' or i == ',' or i == '-' or i == '_' or i == ':' or i == '\n' or i == '\r': l1.append(ss) ss = '' counter += 1 elif counter == len(character) - 1: ss += i l1.append(ss) ss = '' else: ss += i counter += 1 if '' in l1: for i2 in l1: if i2 == '': l1.remove(i2) return l1 def first_reverse(str_param): """this func will make the entered parameter, revers""" result = '' length = len(str_param) for i in range(length - 1, -1, -1): result += str_param[i] return result def encoder(password: str = None): """This function will encrypt the parameter that it takes""" out_put = None formula_number = 0 # Check if the parameter is not None if password: # Make a reverse of the entry parameter reverse_input = first_reverse(password) # Convert the each character # to the ascii code of it # and sum each code to the previous one # to have a number of sum all the ascii code... for i in reverse_input: formula_number += ord(i) # Here is my formula for encryption # that write it into a function def encrypt(input_parameter) -> int: en_bowl = ((input_parameter * 7) // 2) - 1 return en_bowl # Call the function out_put = encrypt(formula_number) # return the encrypted password return out_put
19a5dcfea56f7993f664745b66f7e1964c5457a4
stwobe/dropboxcopy01
/1Python/Python3/02_first_scripts_4/Fibonacci/fibo5.py
332
3.59375
4
import time def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print(b) a, b = b, a+b print(b*a) print((b*b*b)*b*b) time.sleep(0.005) print() #fib(1000565656) #this is a module to be imported into another program - or uncomment above line to run as a script
58b9e43550d8e9ae779936b7f34fdbb9c87118f4
rafhaeldeandrade/learning-python
/4 - Estruturas de Repetição em Python/exercicios/ex09.py
403
3.9375
4
""" Faça um programa que leia um número inteiro N e depois imprima os N primeiros números naturais ímpares. """ qtd = int(input('Quantos números deveremos imprimir: ')) qtd_impar = 0 if qtd <= 0: print('Digite um valor maior que 0.') else: for i in range(1, qtd * 3): if qtd_impar == qtd: break elif i % 2 != 0: print(i) qtd_impar += 1
1bb257ed62a3c4992647b895d09aed07f6965b5a
nlpet/codewars
/Puzzles/array_packing.py
1,747
4
4
u""" Simple Fun #9: Array Packing Task You are given an array of up to four non-negative integers, each less than 256. Your task is to pack these integers into one number M in the following way: The first element of the array occupies the first 8 bits of M; The second element occupies next 8 bits, and so on. Return the obtained integer M as unsigned integer. Note: the phrase "first bits of M" refers to the least significant bits of M - the right-most bits of an integer. For further clarification see the following example. Example For a = [24, 85, 0], the output should be 21784 An array [24, 85, 0] looks like [00011000, 01010101, 00000000] in binary. After packing these into one number we get 00000000 01010101 00011000 (spaces are placed for convenience), which equals to 21784. Input/Output [input] integer array a Constraints: 1 ≤ a.length ≤ 4 and 0 ≤ a[i] < 256 [output] an unsigned integer More Challenge Are you a One-Liner? Please try to complete the kata in one line(no test for it) ;-) """ from functools import reduce from operator import add import sys sys.path.append('..') from helpers.test_wrapper import Test def array_packing(a): return int(reduce(add, (map(lambda x: '{0:08b}'.format(x), a[::-1]))), 2) if a else 0 def run_tests(): with Test() as test: test.describe("Basic tests") test.assert_equals(array_packing([24, 85, 0]), 21784) test.assert_equals(array_packing([23, 45, 39]), 2567447) test.assert_equals(array_packing([1, 1]), 257) test.assert_equals(array_packing([0]), 0) test.assert_equals(array_packing([]), 0) test.assert_equals(array_packing([255, 255, 255, 255]), 4294967295) if __name__ == '__main__': run_tests()
9d49c5489ad5e4fdb6d03aed88326f0dc45c4301
ShikhaShrivastava/Python-core
/OOP Concept/Instance Variable.py
1,316
4
4
class Student: def __init__(self, name, marks, subject): self.name = name self.marks = marks self.subject = subject def disp(self): self.city = "Mumbai" # accessing def disp2(self): print(self.name) print(self.marks) print(self.gender) print(s1.name) print(s1.marks) print(s1.gender) # modifying def disp3(self, subject): self.subject = subject def disp4(self): self.subject = "python" # deleting def disp5(self): del self.subject del self.name if __name__ == "__main__": s1 = Student(name="shikha", marks=56, subject="maths") print(s1.__dict__) s1.disp() print(s1.__dict__) s1.gender = "female" print(s1.__dict__) s1.disp2() print(s1.__dict__) s1.disp3(subject="java") print(s1.__dict__) s1.disp4() print(s1.__dict__) # modify s1.name = "shubh" print(s1.__dict__) # remove del s1.marks print(s1.__dict__) s1.disp5() print(s1.__dict__) del s1.__dict__ print(s1.__dict__) # accessing print(self.name) # //error print(self.marks) # //error print(self.gender) # //error print(s1.name) print(s1.marks) print(s1.gender)
5c329b82d2f915342270e5c741005671c631da66
Luisa2017/my-first-blog
/provaSALUTI2017.py
136
3.75
4
name = 'Sonia' if name == 'Ola': print('Ciao Ola!') elif name == 'Sonia': print('Ciao Sonia!') else: print('Ciao anonimo!')
a288c5702a6e04fd3ed4843d818fedb441d40e6a
martinamagdy/python-challenge
/PyBank/main.py
2,375
4.09375
4
import csv import os #function for taking csv file and do budget calculation def budget(filepath): totalmonths=0 totalamount=0 #read csv file with open(filepath,newline='') as csvfile: csvreader=csv.reader(csvfile,delimiter=',') #skip the header next(csvreader,None) bud=[] month=[] secondmonth=0 change=[] for row in csvreader: #change in "Profit/Losses" between months bud.append(int(row[1])) month.append(row[0]) second=int(row[1]) changebetween=second-bud[len(bud)-2] change.append(changebetween) #total number of months totalmonths=totalmonths+1 #The total net amount of "Profit/Losses" over the entire period totalamount=totalamount+int(row[1]) change=change[1:len(change)] #The greatest increase in profits over the entire period increase=max(change) #The greatest decrease in losses over the entire period decrease=min(change) #The average change in "Profit/Losses" between months over the entire period sums=sum(change) averagechange=round(sums/len(change),2) #print the result print("Financial Analysis\n-------------------------") print("Total Months: " +str(totalmonths)) print("Total: $" + str(totalamount)) print("Average Change: $"+str(averagechange)) print("Greatest Increase in Profits: "+str(month[change.index(increase)+1])+"($"+str(increase)+")") print("Greatest Decrease in Profits: "+str(month[change.index(decrease)+1])+"($"+str(decrease)+")") outputfile= open("Financial_Analysis_output.txt","w") outputfile.write("Financial Analysis\n-------------------------\n") outputfile.write("Total Months: " +str(totalmonths)+"\n") outputfile.write("Total: $" + str(totalamount)+"\n") outputfile.write("Average Change: $"+str(averagechange)+"\n") outputfile.write("Greatest Increase in Profits: "+str(month[change.index(increase)+1])+"($"+str(increase)+")\n") outputfile.write("Greatest Decrease in Profits: "+str(month[change.index(decrease)+1])+"($"+str(decrease)+")\n") outputfile.close() path=os.path.join('budget_data.csv') budget(path)
a8ee1bba897ef78f1f8ba2521b9622a16b1da2e6
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_97/1767.py
1,607
3.640625
4
#Program : Recycled Number, Google code jam problem C #Author : Santhosh Unnikrishnan #email : [email protected] #date : 14th April 2012 IN_FILE_NAME = "C-small-attempt.in" OUT_FILE_NAME = "C-small-attempt.out" TEMP_FILE_NAME = "temp.txt" def get_number_of_recycled_numbers(A, B): ''' This function will return the number of recyclable number in [A,B] ''' count = 0 n = A fd = open(TEMP_FILE_NAME, "w") while n <= B: num = len(str(n)) i = 1 while i <= num-1: number = n % (10 ** i) if number == 0: i = i + 1 else: #print n, number m = (number * (10 ** (num-i))) + (n/(10 ** i)) #print "m is %d" %(m) if m > n and m <= B: count = count + 1 string = "%d-%d\n" %(n, m) fd.write(string) i = i + 1 n = n + 1 fd.close() print 'Original count %d' %(count) fd = open(TEMP_FILE_NAME, "r") contents = fd.readlines() i = 0 j = 0 new_count = count while i < count: j = i + 1 while j < count: if contents[i] == contents[j]: new_count = new_count - 1 j = j + 1 i = i + 1 fd.close() return new_count if __name__ == "__main__": fd = open(IN_FILE_NAME, "r") contents = fd.readlines() fd.close() test_cases = int (contents[0]) count = 0 mylist = [] number = 0 fd = open(OUT_FILE_NAME, "w") while count < test_cases: string = contents[count + 1] mylist = string.split(" ") if len(mylist) < 2: number = 0 else : A = int(mylist[0]) B = int(mylist[1]) number = get_number_of_recycled_numbers(A,B) count = count + 1 out_put_string = "Case #%d: %d\n" %(count, number) fd.write(out_put_string) fd.close()
123e27f26ba69c362d48e61c1cc47fe29d6930f6
StarshipladDev/PythonDungeon
/mainjam.py
22,904
3.78125
4
""" Starshipladdev- (21/10/19) This is a highschool python project I created back in 2015. It is a simple text-based dungeon explorer. Horrible commenting will be left as is. """ #colours-snow,honeydew,midnight blue,firebrick,light blue, #IntVar(),StringVar(),Label, font= ("font,size"), Var.set(set),textvariable,randrange() #import n #needed moduels from Tkinter import * from random import * class PlayerClass: #defines the player class and all his attributes.- Will be called apoun during combat equation, buying stuff, and health. def __init__(self,health,attack,gold,haskey): self.health=health self.attack=attack self.gold=gold class Enemy: #defines the enemy class- used to construct random enemies def __init__(self,name,health,attack,givegold): self.name=name self.health=health self.attack=attack self.givegold=givegold nullvalue=0 player=PlayerClass(10,2,0,False)#Before anything else, creates a global playerclass player_inventory=[]#Creates a list of inventory items. By using "name" in palyer_inventory, can call apoun any needed item objects=["Sword Dealer","Health Potion","Key","Door"]#A list of objects that coudl be encountered- defines what type of non-hostiel encounter occurs class MainProcess:#At the current moment, I cannot think of any reason I woudl need multile #classes on screen. Due to this, at the moment ,I will keep all information here def __init__(self,parent,):#set up the widgits to be used(see brief for layout of nessasary widgits.) self.playername=StringVar()#This will be set at the name type section self.eventnumber=IntVar()#Ghostcode,could be sued o nfurther additions, dosn't affect program self.player_health=StringVar()#Not acctualy player.health,just the Strign value to dispaly under player's avatar. Is changed whenever the player.health is affected self.player_health.set("Health:"+str(player.health)) self.eventnumber.set(0)#Ghost code self.face1=PhotoImage(file="C:\Users\Lavoy\Documents\Code\Python\Breif and Log/face1.gif") self.face2=PhotoImage(file="C:\Users\Lavoy\Documents\Code\Python\Breif and Log/face2.gif")#These sections simply load the in file images for later use self.face3=PhotoImage(file="C:\Users\Lavoy\Documents\Code\Python\Breif and Log/face3.gif") self.face4=PhotoImage(file="C:\Users\Lavoy\Documents\Code\Python\Breif and Log/face4.gif") self.maintext=Label(parent,text="Welcome to Adventure Simulator 2015. You need to locate a key, take the magical door out of here, and stay alive. Good luck",wraplength=350,bg="olive drab",) #^is probably the most important component. This is the text that the User will get- #-information about what is occurring from. #also note:ued wraplength instead of two labels for intro text self.maintext.grid(row=0,column=0,columnspan=3) self.avatar=Label(parent,image="")#Avatar is given a grid location, but no display self.avatar.grid(row=0,column=4) self.healthlabel=Label(parent,textvariable=self.player_health)#same goes for dispalyign the palyer's health #BUTTONS:The below __init__'s set up the four buttons that will be manipulated depending on what event is occurring. #they are by default set to send the player to character creation self.option1=Button(parent,text="Continue to Character Creation",command=self.setavatarpic,width=35) self.option1.grid(row=1,column=0) self.option2=Button(parent,text="Continue to Character Creation",command=self.setavatarpic,width=35) self.option2.grid(row=1,column=2) self.option3=Button(parent,text="Continue to Character Creation",command=self.setavatarpic,width=35) self.option3.grid(row=2,column=0) self.option4=Button(parent,text="Continue to Character Creation",command=self.setavatarpic,width=35) self.option4.grid(row=2,column=2) #NAME SELECTION:Another two widgits that will be created for character creation, then removed after storign variables self.nametype=Entry(parent,) self.confirmname=Button(parent,text="confirm",command=self.confirmnamefunc) #FIRST FUNC:This will be the first function the palyer will be taken to, and allows them to select one of the pre-loaded images as a character avatar #it also sets the four options to have the corrosponding face #also temporarily sets buttosn width as 100, as images have diffrent measurmetns from #text #I found I could use the lambda command to stop option 4 automaticly beign called def setavatarpic(self): self.maintext.configure(text="Please select your character's avatar") self.option4.configure(width=100,text="",image=self.face4,command=lambda:self.setavatar1("d")) self.option1.configure(width=100,text="",image=self.face1,command=lambda:self.setavatar1("a")) self.option2.configure(width=100,text="",image=self.face2,command=lambda:self.setavatar1("b")) self.option3.configure(width=100,text="",image=self.face3,command=lambda:self.setavatar1("c")) #SET THE AVATAR LABEL WITH SELECTED IMAGE: #As noted in the log, I realised after I ahd set up these four diffrent functions I could have created one function and jsut set a diffrent image based on arguments given, but #I found there were mroe important issues to deal with, and its a working system. #REREUPDATE-The setavatar function is now 1 function using 4 diffrent variables, not 4 diffrent functions. #THESE CLASSES BELOW EACH SET THE AVATAR IAMGE AND DISPAY DYNAMIC HEALTH def setavatar1(self,x): if x=="a": self.avatar.configure(image=self.face1) elif x=="b": self.avatar.configure(image=self.face2) elif x=="c": self.avatar.configure(image=self.face3) elif x=="d": self.avatar.configure(image=self.face4) else: print("Error") self.setname() self.healthlabel.grid(row=1,column=4) #BELOW IS THE OLD SET IMAGE BUTTONS # def setavatar1(self): # self.avatar.configure(image=self.face1) # self.setname() # self.healthlabel.grid(row=1,column=4) # def setavatar2(self): # self.avatar.configure(image=self.face2) # self.setname() # def setavatar3(self): # self.avatar.configure(image=self.face3) # self.setname() # self.healthlabel.grid(row=1,column=4) # def setavatar4(self): # self.avatar.configure(image=self.face4) # self.setname() # self.healthlabel.grid(row=1,column=4)""" #Set default Character Name as hero #SET THE PLAYERS NAME, STORE IT IN A CLASS SPECIFIC VARIABLE: #The following function changes the U.I to a name input section(No char limit due to word wrap) and a continue button #after this a random event will constantly be called #FUTUREDEV:More character creation options: a stats modifying system woudl be easy enough to implement with buttons def setname(self): self.maintext.configure(text="Please chose your characters name") self.option1.grid_forget() self.option2.grid_forget() self.option3.grid_forget() self.option4.grid_forget() self.nametype.grid(row=1,column=0,columnspan=2) self.nametype.insert(END,"Hero") self.confirmname.grid(row=1,column=4) def confirmnamefunc(self,): self.b=self.nametype.get() self.playername.set(self.b) if "\"" in self.b: self.maintext.configure(text="You can't use quotation marks in your name sorry") elif len(self.b)>15: self.maintext.configure(text="Name is too long, please keep it under 15 characters") elif self.b=="": self.maintext.configure(text="Please input a name") #ERROR CONTROL ^^^. #Checks if the user has inputed any writing into the name entry. Othwerwise asks them to type somthing #Checks if the user name has quotation marks. Sicne quotation amrks are used to talk to the character Later, The program tells the user to remove them #confirm button remaisn unchanged throughout so they can still continue #It also calls the user out if they try and use punctuation used i ngame, liek quotation marks. #Below sets a StringVar as the confirmed,uncourupted strign value. #It then resets the buttosn to 35 from now on. else: self.name=self.playername.get() self.nametype.grid_forget() self.confirmname.grid_forget() self.maintext.configure(text=("your character's name is " +self.name)) self.option1.grid(row=1,column=0,) self.option2.grid(row=1,column=2,) self.option3.grid(row=2,column=0,) self.option4.grid(row=2,column=2,) self.option1.configure(width=35,image="",text="Begin Your Quest",command=self.randomevent) self.option2.configure(width=35,image="",text="Begin Your Quest",command=self.randomevent) self.option3.configure(width=35,image="",text="Begin Your Quest",command=self.randomevent) self.option4.configure(width=35,image="",text="Begin Your Quest",command=self.randomevent) #ONE OF THE MOST PRIMARY FUCNTIONS:FACE THE PALYER WITH A NEW RANDOM EVENT, POSITIVE OR NEGATIVE #This function is what is called when one problem has been resolved and the player wishes to continue #It creates a random number from a range each time its called, with a 50% cahnce of spawning a random monster(decided randomly in a similar manner) #an a 50%chance of spawning a encoutner with an object. The object is called by retreiving a random index from the 'objects' list, and giving an appropriate #change to the options available based on what strign value was used as an argument. #I really like this as it gives a larger content selection #NOTE:I try to input a 'quit' option wherever available for good user usability. this closes the application entierly #FUTUREDEV:Create diffrent chances of event(E.G-morel iekly to encounter a sword dealer than a key) #FUTUREDEVREVISE:The previosu statment was doen for a mosnter. there is a 3/5 chance to encoutner a ratman, the weakest enemy, comapred to #other types of foe def randomevent(self,): type_of_event=randrange(0,3) #moNSter shows up-Crete introduction text, change option buttosn to suitable options, create a isntacne of enemy fro ma selection #of prefab monster stats. if type_of_event==1: self.monster_type= randrange(0,500) if self.monster_type>400: self.monster=Enemy("Goblin",6,3,30) elif self.monster_type>300: self.monster=Enemy("Orc",8,4,50) elif self.monster_type>50: Enemy("Ratman",4,2,10) else:self.monster=Enemy("BROKEN AMMOUNT OF GOLD SECRET CREATURE",20,16,50000000000000) self.maintext.configure(text="You see a "+self.monster.name +" appear in front of you") self.option1.configure(image="",text="attack it",command=self.attack) self.option2.configure(image="",text="run away",command=self.flee) self.option3.configure(image="",text="check it's stats",command=self.statcheck) self.option4.configure(image="",text="Quit",command=root.destroy) if type_of_event==2: self.f=randrange(0,len(objects)) self.objectinstance=objects[self.f] #depending on what object is called, configure the option buttons to realevant options, with assosiated function called self.maintext.configure(text="You stumble across a " +self.objectinstance) if self.objectinstance=="Sword Dealer": self.option1.configure(text="Upgrade Sword(50G)",command=self.swordbuy) self.option3.configure(text="Check your purse",command=self.moneycheck) self.option2.configure(text="Continue on Your Quest",command=self.flee) self.option4.configure(text=" Quit",command=root.destroy) elif self.objectinstance=="Health Potion": self.option1.configure(text="Drink it up",command=self.drink) self.option2.configure(text="Listen to him-Drink it",command=self.drink) self.option3.configure(text="Say no to Peer Pressure and leave",command=self.flee) self.option4.configure(text="Quit ",command=root.destroy) elif self.objectinstance=="Key": self.option1.configure(text="Pick upthe key",command=self.getkey) self.option2.configure(text="Fight it",command=self.fightkey) self.option3.configure(text="Continue on Your Quest",command=self.flee) self.option4.configure(text=" Quit",command=root.destroy) elif self.objectinstance=="Door": self.doorbusted=randrange(0,11) if self.doorbusted>1: self.maintext.configure(text="You come across a Magic door. It's broke yo") self.option1.configure(text="Continue on your Quest",command=self.randomevent) self.option2.configure(text=" ",command=self.null) self.option3.configure(text=" ",command=self.null) self.option4.configure(text=" ",command=self.null) else: self.option1.configure(text="Open the door",command=self.dooropen) self.option2.configure(text="Fight it",command=self.fightkey) self.option3.configure(text="Continue on Your Quest",command=self.flee) self.option4.configure(text=" Quit",command=root.destroy) else:#Error correction in case the random event calls an event I havn't made. Used to make sure newevent fucntion is calling correctly self.maintext.configure(text="The Dev gone done messed up, Plz inform him") #DRINK POTION OPTION #Made a seperate fucntio nfor when palyer drinsk the potion, configures the global player health variable and adds 2. Then dispalys new health def drink(self): self.maintext.configure(text="You gulp down the magic potion. +2 health") player.health=(player.health+2) self.player_health.set("Health:"+str(player.health)) self.option1.configure(text="Continue",command=self.randomevent) self.nullify() #CHECK MONEY AMMOUNT #I thought it woudl be more interactive to manually have to check yoour money rather than having it always rpesent like health #Changes Maintext to the ammount of gold you have, but leaves word buying options there, so you can still buy items after knowign how much you have def moneycheck(self): self.maintext.configure(text="You have "+str(player.gold)+" Gold coins in your purse") #FIGHT INNANIAMTEOBJECT #Dispaly humourous text when a palyer selects to fight a key or door. Leaves other options open to interact with the said object def fightkey(self): self.maintext.configure(text="It's an inanimate object. Why? What did you hope to acheive?") #adds a key string value to the palyer inventory list. This will alter be used as an arugment when trying to open a door #FUTUREDEV:More items that can be given to inventory list #FUTUREDEV:Make it so palyer can only pick up key once #FUTUREDEVREVISED:Key now replaced in objects string after being picked up. #Program still knows player has a key, but the event will never unessacierily show up again. #it also means sword dealer will appear more, fufiling my previous wish def getkey(self): self.maintext.configure(text="You pick up the key. This will come in handy later") player_inventory.append("Key") self.option1.configure(text="Continue",command=self.randomevent) self.nullify() objects[2]="Sword Dealer" #This function then allows the palyer to continue or quit #could call another random event where this function is used, but this leads to a more natural transitio nto a new event. def flee(self): self.maintext.configure(text="You decide you could do without it") self.option1.configure(text="Continue on Your Quest",command=self.randomevent) self.nullify() #OPEN DOOR THAT ISNT BROKEN WITH KEY #This fucntion sees if the palyer_invintory list includes the "key" item. If so it opens the door, otherwise it lets the palyer continue on the game def dooropen(self): if "Key" in player_inventory: self.maintext.configure(text="You open the door and step into a new world. Congratulations ,you win") self.option2.configure(text=" ",command=self.null) self.option3.configure(text=" ",command=self.null) self.option4.configure(text=" ",command=self.null) self.option1.configure(text="Finish",command=root.destroy) elif "Key" not in player_inventory: self.maintext.configure("You need a key") self.option1.configure(text="Continue",command=self.randomevent) self.nullify() #ATTACK ENEMY CREATURE, PROCESS COMBAT SYSTEM, DISPALY LOSER TEXT IF HEALTH<0, DISPALY WIN TEXT AND GIVE GOLD IF #ENEMY CREATURE DESTROYED #The turn time is based on how quickly the player can kill the monster. #since the monsters health varies based on which monster spawned, and the player attack varies based on how many sword upgrades the brought #the turn time is modified by getting these two values each time this function is called. #so that the player can't get to strong to even let the monster get an attack, if turn time=0 or less, it is automatically set to 1 to give the monster a chance to attack #for every 1 in the turn time value, the monster deals a random number damage(subtraction from player.health) between 0 and its max attack #every time thsi happens, the program checks if the palyers health value is 0 or less. If so the program allows the user to exit after being defeated #otherwise it says that the monster has been killed, adds the monsters gold value to the palyer total gold, and allows the player to continue. #Throughout this the player health is displayed every time it is altered, for visual feedback for the user def attack(self): self.turntime=(self.monster.health-player.attack) if self.turntime<=0: self.turntime=1 for x in range(0,self.turntime): player.health=(player.health-(randrange(0,(self.monster.attack+1)))) if player.health<=0: self.player_health.set("Health:0") self.maintext.configure(text="You are slain by the "+self.monster.name+". Your quest has ended") self.option1.configure(text="Finish",command=root.destroy) self.nullify() break else: self.player_health.set("Health:"+str(player.health)) self.maintext.configure(text="You slay the "+self.monster.name) self.option1.configure(text="Continue on your Quest",command=self.randomevent) player.gold=(player.gold+self.monster.givegold) #A useless function that buttons not currently in use are assigned to. Its more aesthetically appealing to have useless buttons temporarily then have them #randomly disappear def null(self): self.nullvalue=nullvalue self.nullvalue=(self.nullvalue+1) #SHOW MOSNTERS STATS #this function gets the statistics of the current instance of mosnter, and dispalys them to user. #This allows the user to make and informed decision wether to ru nor fight, and those options remain unchanged #since they were called in the previous action def statcheck(self): self.maintext.configure(text="The "+self.monster.name+" has the following stats: "+str(self.monster.health)+" health, does up to "+str(self.monster.attack)+" attack and drops "+str(self.monster.givegold)+" gold") #Checks if the player has at least 50 gold. #if so, adds 2 t othe total palyer.attack value, and gives the option to continue on, check total money, or do the same function. #otherwise, the maintext dispalys a text that tells the user they do not have enough gold, and allows them to continue or call the check purse function def swordbuy(self): if player.gold>=50: player.gold=(player.gold-50) self.maintext.configure(text="He improves your sword by 2 damage, and takes your 50 gold. You now have "+str(player.attack)+" attack") player.attack=(player.attack+2) self.option1.configure(text="Upgrade further",command=self.swordbuy) self.option2.configure(text="Check your purse",command=self.moneycheck) self.option3.configure(text=" Continue on your quest",command=self.randomevent) self.option4.configure(text="Quit",command=root.destroy) else: self.maintext.configure(text="He shakes his head,and says \""+self.playername.get()+" You'll need more money for that\"") self.option1.configure(text="Continue on Your Quest",command=self.randomevent) self.option2.configure(text="Check your purse",command=self.moneycheck) self.option3.configure(text=" ",command=self.null) self.option4.configure(text="Quit",command=root.destroy) def nullify(self): self.option2.configure(image="",text=" ",command=self.null) self.option3.configure(image="",text=" ",command=self.null) self.option4.configure(text="Quit",command=root.destroy) #run the main system root = Tk() root.title("Adventure Simulator 2015")#Name of program root.geometry("750x150+100+100")#Set geometry of program in pixles show_label=MainProcess(root) root.mainloop()#run the system in a loop #To sum- #MainProcess- #attack function to resolve fights #confirm name fucntion, put input value as StringValue of players name #drink fucntion, add health to palyer classs health, change the health dispaly #Sword buy, check if palyer has 50 gold. remove if so and add value to palyer.attack. offer to do it again or continue #Open door, check if key string is anywhere in inventory list, if so end game after flavour text, if not allows player to continue #flee- add flavour text the nallow player to encounter new rando mencounter #random encoutner- give the palyer an encounter drawn fro ma rando mrange of int values, each with a corrospondign event #enemy- spawn an enemy class with stats based on its object constructed, whcih si based on a rando mrange. Changes optiosn to a global selection. #changenotes!!!!!!!!!! #I made setavatar one fucntion, isntead of 4 difrrent ones #I swapped repeditive code to nullify 3 buttons into 1 function to call that did the sme thing (self.nullify)
4c93af3f8352776f1c4bd7c1126cd86a9fff005d
theChad/ThinkPython
/chap5/fermat.py
571
4.15625
4
# Exercise 5.2 import math # 4.2.1 def check_fermat(a, b, c, n): if n > 2 and a**n + b**n == c**n: print("Holy smokes, Fermat was wrong!") else: print("No, that doesn't work.") # 4.2.2 def fermat_inputs(): print('Please input positive integers to check Fermat\'s theorem.') # Use input to take input from the keyboard, and int() to convert them # to integers (otherwise they'll be seen as strings) a = int(input('a: ')) b = int(input('b: ')) c = int(input('c: ')) n = int(input('n: ')) check_fermat(a, b, c, n)
368854265b4395352e15b1142d91d5cd59420b4e
ishantk/Enc2019B
/venv/Session22.py
652
3.828125
4
import numpy as np arr = np.arange(10, 51, 3) print("arr is:",arr) print("type of arr is:",type(arr)) print("shape arr is:",arr.shape) print("Size of arr is:",arr.shape[0]) # Access Elements print(arr[1]) print(arr[-1]) # Slicing print(arr[3:]) print(arr[:5]) print(arr[3:5]) slices = slice(1, 10, 2) # -> 1, 3, 5, 7, 9 print(slices) print(type(slices)) print(arr[slices]) arr2D = np.array(([[1,2,3], [4,5,6], [7,8,9]])) print(arr2D) print(arr2D.shape) print("arr2D size is:",arr2D.shape[0]) print(arr2D[0][1]) print(">>>>>><<<<<<") print(arr2D[0:2]) print(">>>>>><<<<<<") print(arr2D[0:2, 0:2]) # print(arr2D[0:2, 0:2, 0:2]) -> For 3-D Array
f676669bcefe7c00698ce0e3c29066d8525f0999
huyngopt1994/python-Algorithm
/bigo/day-1-dyanimic-array-string/problem-518A.py
617
3.8125
4
# http://codeforces.com/problemset/problem/518/A # We just think compare a string like a number, understand the special case to cover this . import string reference_string = list(string.ascii_lowercase) s = list(input()) t = input() len_number = len(s) result = "" is_good = False for index in range(len_number - 1, -1, -1): if s[index] != 'z': refer_index = reference_string.index(s[index]) refer_index += 1 s[index] = reference_string[refer_index] break elif s[index] == 'z': s[index] = 'a' s = ''.join(s) if s == t: print('No such string') else: print(s)
a6c7f1ccd1dcb58d1c81b83260d1e0bc6e010635
Talha-Ahmed-1/DSA-Labs
/Talha Ahmed (18B-024-SE) Lab # 6.py
2,740
3.84375
4
#!/usr/bin/env python # coding: utf-8 # In[15]: # A class ArrayStack: def __init__(self,size): self.size=size self.data=[0 for i in range(size)] self.top=0 def isEmpty(self): if self.top==0: return True else: return False def Push(self,value): if self.top==self.size: print("Stack Overflow !") else: self.data[self.top]=value self.top+=1 def Pop (self): if self.isEmpty(): print("Stack Underflow !") else: x=self.data[self.top-1] self.top-=1 self.data[self.top]=0 return x def Check(self): if self.isempty: self.Push(2) else: self.Pop() def Peek(self): return self.data[self.top-1] def Count(self): return self.top def Printt(self): for i in self.data: print(i) ob=ArrayStack(3) ob.Push(7) ob.Push(6) ob.Push(5) ob.Pop() print(ob.Peek()) print(ob.Count()) ob.Printt() # In[23]: # B class ArrayQueue: def __init__(self,size): self.size=size self.data=[0 for i in range(size)] self.f=-1 self.r=0 def enQueue(self,value): self.data[self.r]=value self.r=(self.r+1)%self.size def deQueue(self): self.f=(self.f+1)%self.size return self.data[self.f] def isEmpty(self): if self.f==-1 and self.r==0: return True else: False def Count(self): return len(self.data) def Printt(self): print(self.Count()) ob=ArrayQueue(4) ob.enQueue(1) ob.enQueue(2) ob.enQueue(3) ob.enQueue(4) ob.enQueue(5) print(ob.deQueue()) ob.Printt() # In[1]: # C class ArrayStack: def __init__(self,lst): self.lst=lst self.size=len(self.lst) self.data=[0 for i in range(self.size)] self.top=0 def StringExp(self): for i in self.lst: print(self.data) if i=="{" or i=="(" or i=="[": self.Push(i) if i=="}" or i==")" or i=="]": self.Pop() def isEmpty(self): if self.top==0: return True else: return False def Push(self,value): if self.top==self.size: print("Stack Overflow !") else: self.data[self.top]=value self.top+=1 def Pop(self): if self.isEmpty(): print("Stack Underflow !") else: x=self.data[self.top] self.top-=1 self.data[self.top]=0 return x str1="{()}[()]{}" ob=ArrayStack(str1) ob.StringExp() ob.Pop() print(ob.data)
c3ef9650b2dace1393c92fe319215d7880b8072b
aviolette/aoc2020
/day8/puzzle8.py
1,265
3.625
4
from elves import striplines def run_program(program): line_num = 0 visited = set() acc = 0 while line_num not in visited and line_num < len(program): instruction, value = program[line_num] visited.add(line_num) jump = 1 if instruction == "acc": acc += int(value) elif instruction == "jmp": jump = int(value) line_num += jump return acc, line_num in visited def get_program(file_name): return [line.split(" ") for line in striplines(file_name)] def find_bad_boot_code(file_name): program = get_program(file_name) for line_num in range(0, len(program)): instruction, value = program[line_num] if instruction != "acc": program[line_num] = ["nop" if instruction == "jmp" else "jmp", value] acc, loops = run_program(program) if not loops: return acc program[line_num] = [instruction, value] def find_acc_value(file_name): return run_program(get_program(file_name))[0] if __name__ == "__main__": print(find_acc_value("example8a.txt")) print(find_acc_value("puzzle8.txt")) print(find_bad_boot_code("example8a.txt")) print(find_bad_boot_code("puzzle8.txt"))
9ca3788f2ae33035312a6b6022cf338606df1aae
MarcGroef/CSVM
/PSO/param_tester.py
2,725
3.921875
4
import abc import time class ParameterTester(object): """ The ParameterTester class provides an interface for tester classes that can evaluate the parameters generated by the ParameterGenerator class. """ __metaclass__ = abc.ABCMeta ################ ## Properties ## ################ param_names = [] parameters = {} _parameters = {} config_file = "" start_command = "" param_path = "" max_reps = 500 # Maximum number of evaluations for a single set of parameters result = None #################### ## Common Methods ## #################### def __init__(self): super(ParameterTester, self).__init__() self.parameters = {} def set_parameters(self, parameters): """ Sets the parameters for the next evaluation """ self._parameters = parameters def get_result(self): """ Returns the result of the last evaluation """ return self.result def write_parameters(self, filename): """ Writes the current set of parameters to the specified path """ config = self.get_config(self._parameters) f = open(filename, 'w') f.write(config) f.close() #################### ## Abstract Method # #################### @abc.abstractmethod def run_algorithm(self): """ This method must be implemented by a subclass to actually evaluate the current set of parameters """ pass ################### ## Class Methods ## ################### @classmethod def add_parameters(cls, generator): """ This method adds the parameter specification to the given generator, and also sets the maximum number of evaluations for each set of parameters. """ for name in cls.param_names: generator.add_parameter(name, **cls.parameters[name]) generator.set_max_reps(cls.max_reps) @classmethod def set_parameter(cls, param_name, config): """ This method changes the settings for a specific parameter. If the config parameter is set to None, the parameter will be deleted """ if config == None: if param_name in cls.parameters: del cls.parameters[param_name] else: cls.parameters[param_name] = config @classmethod def get_config(cls, parameters): """ This method returns a valid configuration file/representation, by formatting the config_file parameter using the given set of parameters """ return cls.config_file % parameters
162c65f5351374c09c3b9e21517af0b2399240a1
zmunro/advent_of_code_2020
/advent3_part2.py
1,342
3.75
4
from typing import List input_trees = [] with open("files/advent3_input.txt", "r") as in_f: for line in in_f.readlines(): input_trees.append(line.strip()) class Spot: row: int col: int def __init__(self, row: int, col: int): self.row = row self.col = col class TreeGrid: base_grid: List[str] def __init__(self, tree_grid: List[str]): self.base_grid = tree_grid def get_grid_height(self): return len(self.base_grid) def get_coord(self, spot: Spot) -> str: assert spot.row <= len(self.base_grid), "row out of bounds" col = spot.col % len(self.base_grid[0]) return self.base_grid[spot.row][col] def calculate_trees_hit_for_slope(right: int, down: int): trees_hit = 0 tree_grid = TreeGrid(input_trees) spot = Spot(0, 0) while True: if spot.row >= tree_grid.get_grid_height(): break if tree_grid.get_coord(spot) == "#": trees_hit += 1 spot = Spot(spot.row + down, spot.col + right) return trees_hit # Right 1, down 1. # Right 3, down 1. # Right 5, down 1. # Right 7, down 1. # Right 1, down 2. slopes = [ (1, 1), (3, 1), (5, 1), (7, 1), (1, 2) ] mult = 1 for slope in slopes: mult *= calculate_trees_hit_for_slope(slope[0], slope[1]) print(mult)
9f756e9e1a298a6db48677a2f48fefbabbf30aba
PAYNE1Z/python-learn
/luffycity-s8/第一模块_开发基础/第2章 _数据类型_字符编码_文件操作/列表copy.py
2,076
3.6875
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # Author: Payne Zheng <[email protected]> # Date: 2019/4/28 # Location: DongGuang # Desc: do the right thing import copy name = [['pony', 'dong'], 'jack', 'robin'] print("########### name: %s\n" % name) name1 = name print("###>>> name1 = name") print("===============================") print("修改前列表内存地址:", id(name), id(name1)) print("修改前列表索引1的值的内存地址:", id(name[1]), id(name1[1])) print("> 将name中索引1的值改为 dong") name[1] = 'dong' print("修改后列表内存地址:", id(name), id(name1)) print("修改后列表索引1的值的内存地址:", id(name[1]), id(name1[1]), "\n") name2 = name.copy() print("###>>> name2 = name.copy()") print("===============================") print("修改前列表内存地址:", id(name), id(name2)) print("修改前列表索引1的值的内存地址:", id(name[1]), id(name2[1])) print("> 将name中索引1的值改为 dong") name[1] = 'lei' print("修改后列表内存地址:", id(name), id(name2)) print("修改后列表索引1的值的内存地址:", id(name[1]), id(name2[1])) print("> 将name中子列表中索引1的值改为 long") name[0][1] = 'long' print("修改后列表内存地址:", id(name), id(name2)) print("修改后列表索引1的值的内存地址:", id(name[0][1]), id(name2[0][1]), "\n") name3 = copy.deepcopy(name) print("###>>> name3 = copy.deepcopy(name)") print("===============================") print("修改前列表内存地址:", id(name), id(name3)) print("修改前列表索引1的值的内存地址:", id(name[1]), id(name3[1])) print("> 将name中索引1的值改为 dong") name[1] = 'zhang' print("修改后列表内存地址:", id(name), id(name3)) print("修改后列表索引1的值的内存地址:", id(name[1]), id(name3[1])) print("> 将name中子列表中索引1的值改为 long") name[0][1] = 'cheng' print("修改后列表内存地址:", id(name), id(name3)) print("修改后列表索引1的值的内存地址:", id(name[0][1]), id(name3[0][1]), "\n")
8b3b835822de39f98d4bfb1af53640c569815c28
odinfor/leetcode
/pythonCode/No401-450/no434.py
718
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/5/11 4:04 下午 # @Site : # @File : no434.py # @desc : class Solution: def countSegments(self, s: str) -> int: if not s or len(s) == 0: return 0 is_dc_start, num = False, 0 for i in s: if i != " " and not is_dc_start: # 单词开头 is_dc_start = True if is_dc_start and i == " ": # 单词结尾 num += 1 is_dc_start = False if is_dc_start: # 以单词结尾,num加1 num += 1 return num if __name__ == "__main__": s = Solution() print(s.countSegments("Hello, my name is John"))
c9efb93bbd7132589f8f0d0b4a63286871e85d83
Xaraxx/curso_Python3
/basics/listCom.py
509
3.703125
4
#List Comprenhention # Is method for resume your code and makeit more readable pares = [] for i in range(1, 31): if i % 2 == 0.0: pares.append(i) print(pares) # List Comprenhention # note: you have to remember this sintax pares2 = [i for i in range(1, 31) if i % 2 == 0 ] print(pares2) cuadrados = {} for i in range(1, 11): cuadrados[i] = i**2 print(cuadrados) squares = {i : i**2 for i in range(1,11)} print(squares) # Note search more about 'sintactic sugar' and modify past codes
618c7d255cb21394cd8db6bca3920c3d5426684f
Fastwriter/Pyth
/Daulet Demeuov t1/D.py
417
4.0625
4
#STUDENT: Daulet Demeuov #GROUP: EN1-C-04 #TASK: Task1 proble D #Description: Write program that reads N. Prompts N float numbers and finds MAXIMUM, MINIMUM and MEDIAN value between them. d=int(input('Enter N: ')) import statistics list=[] for n in range(d): n=float(input('Enter number: ')) list.append(n) print('MAXIMUM is ',max(list)) print('MINIMUM is ',min(list)) print('MEDIAN is ',statistics.median(list))
e1a7a552daa30dfe7f75366544803506000ae735
RickBahague/python-solutions
/03_builtins/file.py
1,531
4.28125
4
# task 6 def step1(): ''' Writes a string to a file. Always remember to close the file handle. You can check the results by opening the file with any text editor. ''' file = open('myfile.txt', 'w') file.write("hello") file.close() def step2(): ''' Opens the loremipsum file from the "res" directory and prints the file, line by line, to the console. The `for` loop comes in handy for this. ''' with open('res/loremipsum.txt', 'r') as myfile: # iterate over the lines of the file for line in myfile: print(line) def step3(): ''' Reads the content of a file and writes it back. Since this requires two file openings and closings, we need to save the lines of the file in a separate variable (here called `backup`) ''' backup = [] # because of scoping with open('res/loremipsum.txt', 'r') as f: backup = f.readlines() # f.readlines() returns a list of lines # alternatively you can use f.read() which gives you the whole content as string with open('res/loremipsum.txt', 'w') as f: for line in backup: f.write(line) def step4(): ''' Appends a line of text to the `lorem ipsum` file. We use the context manager for this example. ''' with open('res/loremipsum.txt', 'a') as myfile: myfile.write('Warum ist es immer "Lorem Ipsum..."?') def main(): step1() step2() step3() step4() if __name__ == '__main__': main()
8ace49362f88d5f5b44f915405c40f804d2e4e9f
nsk324/TIL
/남수경/0821/fibo.py
491
3.890625
4
# def factorial(n): # if n <= 1: # return 1 # else: # return n*factorial(n-1) # # def fibo(n): # if n ==1 : # return 1 # if n ==0: # return 0 # else: # return fibo(n-1)+fibo(n-2) def fibo1(n): global memo if n >=2 and len(memo) <=n : #계산되었는지 안 되었는지 list의 크기로 하겠습니다. memo.append(fibo1(n-1)+fibo1(n-2)) return memo[n] memo = [0 , 1] # print(factorial(4)) print(fibo1(7))
b1ab266fa72e1bfc8f51105ffa103ea0cd2b67b5
youkx1123/hogwarts_ykx
/python_Recordedlesson/Python_Basis/020day3.py
2,433
4.25
4
""" 列表的基本使用 一、列表(list类型) 1、在python是用中括号表示(和其他语言中的数组看起来差不多) 2、例子:[11,22,33,‘python’] 3、列表中可以存储任何类型的数据 4、空字符串 s1=‘’ <class 'str'> 5、空列表 li = [] <class 'list'> 6、列表和字符串(后续会讲的元组,有一个公共操作):切片和索引取值 """ li = [11, 1.3, True, '788', [11, 22]] print(li) s1 = '' li = [] print(type(s1), type(li)) ''' 二、索引(下标) 1、列表里的每个数据是用“逗号”隔开的 2、下标也是从“0”开始的 3、正向索引:从前往后数,从0开始 4、反向索引:从后往前数,从-1开始(全是负数) ''' # 三、索引取值:通过下标的值,获取指定位置的数据 ''' 1、(正向索引)字符串使用下标“1”,取到的值为2 2、(正向索引)列表使用下标为“1”,取到的值为22 3、(反向索引)字符串使用下标“-3”,取值为2 4、(反向索引)字符串使用下标“-3”,取值为333 ''' s = "12345" print(s[-3]) l1 = [111, 223, 333, 444, 5555] print(l1[-3]) # 四、切片:通过下标,获取多个值 ''' 1、“冒号”前后都不写,默认是最开始和最末尾,会把所有数据打印出 2、“冒号”前写“1”,默认从下标为1的数据开始,取到末尾 3、[a:b]:切片操作是左闭右开 ==>数学中范围表示[a,b) 4、切片也可以使用反向下标取值(建议:要么都正向、要么都反向) ''' l2 = ['hello', 20210204, 'i like python'] print(l2[:]) print(l2[1:]) print(l2[1:2]) print(l2[1:-1]) # 五、切片的步长 ''' 1、格式:[a:b:c] ===> [起始位置:终止位置:步长] 2、将起始和终止之间的数据“345678”,按照步长2划分区域“34 56 78”,每个区域取第一个“357” ''' l3 = "123456789" res = l3[2:8:2] print(res) # 六、反向步长切片 ''' 1、反向步长时,起始和终止如果无法形成闭区间,无法取到值 2、默认“起始”是末尾,“终止”是开始,结果是闭区间,可以取到值 3、反向步长是从后往前进行切片 4、起始位置和终止位置:起始位置 > 终止位置 5、使用步长3,分块“987 65”,取值“96” ''' l4 = "123456789" print(F"我是方向取{l4[8:2:-1]}") print(f"我的方向步长是3奥!{l4[8:3:-3]}")
5af7e79fb22f4f557e8a75d318332c2f46bc267f
fis-jogos/ep1-shape
/actors/aircraft.py
1,692
3.75
4
import shared.constants as C class Aircraft: """ This class represents the aircraft controlled by the user. """ def __init__(self, actor): self.actor = actor self.positionX = C.MINIMAL_X self.positionY = C.HEIGHT / 2 self.acceleration = 0 self.shape = 'circle' self.vx = 100 self.directionY = 1 self.directionX = 1 def draw(self): """ Draw the aircraft in the screen. """ self.actor.x = self.positionX self.actor.y = self.positionY self.actor.draw() def change_shape(self): self.shape = next(C.SHAPE) self.actor.image = 'aircraft-' + self.shape def go_ahead(self): if self.shape == 'triangle': if self.positionX <= C.MAXIMAL_X: self.positionX += 10 def go_back(self): if self.shape == 'triangle': if self.positionX >= C.MINIMAL_X: self.positionX -= 10 def circleMove(self, dt): if self.directionY == 1: if self.positionY <= 550: self.positionY += C.GRAVITY * dt else: self.directionY = -1 else: if self.positionY >= 45: self.positionY -= C.GRAVITY * dt else: self.directionY = 1 if self.directionX == 1: if self.positionX <= C.MAXIMAL_X: self.positionX += self.vx * dt else: self.directionX = -1 else: if self.positionX >= C.MINIMAL_X: self.positionX -= self.vx * dt else: self.directionX = 1
af76497612f1c9cc55361e29052adca9219fa7fd
ginnyyang/MyPython
/learning_process/itertools_test.py
956
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #计算圆周率可以根据公式 #利用Python提供的itertools模块,我们来计算这个序列的前N项和 #itertools模块提供的全部是处理迭代功能的函数,它们的返回值不是list,而是Iterator,只有用for循环迭代的时候才真正计算。 import itertools def pi(N): ' 计算pi的值 ' # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ... digits=itertools.count(1,2) # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1. digits=itertools.takewhile(lambda x:x<2*N,digits) # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ... digits=map(lambda x: 4/x if x%4 == 1 else -4/x,digits) # step 4: 求和: pi=sum(digits) return pi # 测试: print(pi(10)) print(pi(100)) print(pi(1000)) print(pi(10000)) assert 3.04 < pi(10) < 3.05 assert 3.13 < pi(100) < 3.14 assert 3.140 < pi(1000) < 3.141 assert 3.1414 < pi(10000) < 3.1415 print('ok')
3e2aae48a4e139dcecca2d3bb3e4e20c8dc635bb
awong05/epi
/find-the-k-largest-elements-in-a-BST.py
1,184
4.28125
4
class BSTNode: def __init__(self, data=None, left=None, right=None): self.data, self.left, self.right = data, left, right """ A BST is a sorted data structure, which suggests that it should be possible to find the k largest keys easily. Write a program that takes as input a BST and an integer k, and returns the k largest elements in the BST in decreasing order. For example, if the input is the BST in Figure 14.1 on Page 198 and k = 3, your program should return <53,47,43>. Hint: What does an inorder traversal yield? NOTES: - A better approach is to begin with the desired nodes, and work backwards. - This amounts to a reverse-inorder traversal. """ def find_k_largest_in_bst(tree, k): """ Space complexity: O(1) Time complexity: O(h + k) """ def find_k_largest_in_bst_helper(tree): if tree and len(k_largest_elements) < k: find_k_largest_in_bst_helper(tree.right) if len(k_largest_elements) < k: k_largest_elements.append(tree.data) find_k_largest_in_bst_helper(tree.left) k_largest_elements = [] find_k_largest_in_bst_helper(tree) return k_largest_elements
e0d1b4c37b1ef78c86be6f3d3b20d5dcf838ad99
yash-khandelwal/python-wizard
/Complete Developer Course 2021/basics/operators.py
235
3.921875
4
# augmented assignment operator some_value = 5 # augmented assignment cannot be used while declaring a variable some_value = some_value + 2 # simple assignment print(some_value) some_value += 2 # augmented assignment print(some_value)
3e5ae70cecb96047fcd6cd7dfe9ffab3589b6871
gkanishk44/Python-Projects
/stackimplementation.py
298
3.53125
4
from collections import deque stack = deque() stack.append('a') stack.append('b') stack.append('c') print('Initial stack:') print(stack) print('\nElements poped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('\nStack after elements are poped:') print(stack)
8045e2648ba548139212c68f8c936e0d781fc512
AbhiShake1/Hangman
/Hangman.py
885
3.84375
4
from random_word import RandomWords import ASCIIList as hangmen secretWord = str(RandomWords().get_random_word()).lower() #to stringify even when it returns None game = "-" * len(secretWord) game = game[:0] + secretWord[0] + game[0 + 1:] game = game[:3] + secretWord[3] + game[3 + 1:] #hint at 1st and 3rd words print(game, end="\n\n") tries = 0 while "-" in game: guess = input("Guess a letter: ").lower() for index in range(0, len(secretWord)): if guess == secretWord[index]: game = game[:index] + secretWord[index] + game[index + 1:] #replacing char at x index if (not (guess in secretWord)): tries += 1 print(game, end=hangmen.hangmen[tries]) if tries >= 7: print("\n\nYou have lost :( \nHope you will win next time") exit() #exit the program print("\n\nCongratulations! You have won :)")
7bd14638fcc8ef0f31a11fb563925274e986a83a
lampkid/jingwuyuan-python
/codec/__init__.py
552
3.515625
4
# -*- coding=utf-8 -*- import traceback def setDefaultEncodingUTF8(): import sys reload(sys) sys.setdefaultencoding('utf-8') def codecText(text, coding='utf-8'): textType = type(text) if textType is int: text = str(text) if textType is not unicode: try: text = text.decode('utf-8') except: #traceback.print_exc() text = text.decode('gbk').encode('utf-8') if coding != 'utf-8': text = text.encode(coding) return text setDefaultEncodingUTF8()
13f752495099eafb7431aea275120bf7742ae593
zysymu/Metodos-Computacionais-da-Fisica
/Métodos B/12-estabilidade_pontos_fixos.py
546
3.515625
4
import matplotlib.pyplot as plt import numpy as np plt.style.use("ggplot") lamb = [0.5, 2, 3, 3.2, 4] x = np.linspace(0,1) def f(x): return l*x*(1-x) def g(x): return f(f(x)) #ciclo 2 def h(x): return g(g(x)) #ciclo 4 plt.ylim(0,1) for l in lamb: plt.plot(x, x, linestyle="--") plt.plot(x, f(x), marker=".", label="f(x): ciclo 1") plt.plot(x, g(x), marker=".", label="g(x): ciclo 2") plt.plot(x, h(x), marker=".", label="h(x): ciclo 4") plt.title(r"$\lambda$ = " + str(l)) plt.legend() plt.show()
52f3ba154ae3f135c6a45d9875bb0b688326a217
sky-183/42ai_python_bootcamp
/day00/ex07/filterwords.py
1,727
4.3125
4
# **************************************************************************** # # # # ::: :::::::: # # filterwords.py :+: :+: :+: # # +:+ +:+ +:+ # # By: vflander <[email protected]> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2020/04/29 15:41:29 by vflander #+# #+# # # Updated: 2020/04/29 15:41:29 by vflander ### ########.fr # # # # **************************************************************************** # from string import punctuation from sys import argv def short_words_filter() -> list: """removes all the words in a string that are shorter than or equal to n letters, and returns the filtered list with no punctuation. The program will accept only two parameters: a string, and an integer n. :return: list """ if len(argv) != 3: return "ERROR" string = argv[1] # valid strings cannot have only digits (as in last example) if string.isdigit(): return "ERROR" try: n = int(argv[2]) except ValueError: return "ERROR" words_list = string.split(' ') words_list = [word.strip(punctuation) for word in words_list] words_list = [word for word in words_list if len(word) > n] return words_list if __name__ == "__main__": print(short_words_filter())
293e7adf1da8915212331fe095e900d0660e9877
iApotoxin/Python-Programming
/60_EcepFinally.py
256
3.546875
4
try: fh = open("myfile", "r") fh.write("This is my file for exception handling!!") except: print("IO Error with File") else: print("Written content in the file successfully") finally: print("This file is closed completely")
4eaa27e28ff35c7a8f6cdc1fe519af6688049012
budavariam/advent_of_code
/2017/23_1/code.py
6,710
4.0625
4
""" Advent of code 2017 day 23/1 """ from argparse import ArgumentParser import re from collections import defaultdict, deque class Instruction(object): """ Instruction for the parser """ @staticmethod def parse(line): """ Create the proper instance for the parser """ return OPERATION[line[:3]](line) @staticmethod def is_digit(value): """ Returns True if the given string represents a number """ return value.lstrip('-').isdigit() def operate(self, p_data): """ Abstract method for the operation """ raise NotImplementedError class OperationSet(Instruction): """set X Y sets register X to the value of Y.""" pattern = re.compile(r'set (\w) (.+)') def __repr__(self): return self.repr def __init__(self, line): """ Constructor """ self.repr = line match = re.match(self.pattern, line) self.val_x = match.group(1) self.val_y = match.group(2) self.is_value = self.is_digit(self.val_y) if self.is_value: self.val_y = int(self.val_y) def operate(self, p_data): """ Run the operation """ if self.is_value: p_data.memory[self.val_x] = self.val_y else: if self.val_y in p_data.memory: p_data.memory[self.val_x] = p_data.memory[self.val_y] else: p_data.memory[self.val_x] = 0 p_data.memory[self.val_y] = 0 return p_data.ptr+1 class OperationMul(Instruction): """mul X Y sets register X to the result of multiplying the value contained in register X by the value of Y.""" pattern = re.compile(r'mul (\w) (.+)') def __repr__(self): return self.repr def __init__(self, line): """ Constructor """ self.repr = line match = re.match(self.pattern, line) self.val_x = match.group(1) self.val_y = match.group(2) self.is_value = self.is_digit(self.val_y) if self.is_value: self.val_y = int(self.val_y) def operate(self, p_data): """ Run the operation """ p_data.mulinvoked += 1 if self.is_value: p_data.memory[self.val_x] *= self.val_y else: if self.val_y in p_data.memory: p_data.memory[self.val_x] *= p_data.memory[self.val_y] else: p_data.memory[self.val_x] = 0 p_data.memory[self.val_y] = 0 return p_data.ptr+1 class OperationJnz(Instruction): """jnz X Y jumps with an offset of the value of Y, but only if the value of X is not zero. (An offset of 2 skips the next instruction, an offset of -1 jumps to the previous instruction, and so on.)""" pattern = re.compile(r'jnz (\w) (.+)') def __repr__(self): return self.repr def __init__(self, line): """ Constructor """ self.repr = line match = re.match(self.pattern, line) self.val_x = match.group(1) self.val_y = match.group(2) self.is_x_value = self.is_digit(self.val_x) if self.is_x_value: self.val_x = int(self.val_x) self.is_y_value = self.is_digit(self.val_y) if self.is_y_value: self.val_y = int(self.val_y) def operate(self, p_data): """ Run the operation """ if (self.is_x_value and self.val_x > 0) or ((not self.is_x_value) and self.val_x in p_data.memory and p_data.memory[self.val_x] != 0): if self.is_y_value: p_data.ptr += self.val_y else: if self.val_y in p_data.memory: p_data.ptr += p_data.memory[self.val_y] else: p_data.ptr += 1 return p_data.ptr class OperationSub(Instruction): """add X Y decreases register X by the value of Y.""" pattern = re.compile(r'sub (\w) (.+)') def __repr__(self): return self.repr def __init__(self, line): """ Constructor """ self.repr = line match = re.match(self.pattern, line) self.val_x = match.group(1) self.val_y = match.group(2) self.is_value = self.is_digit(self.val_y) if self.is_value: self.val_y = int(self.val_y) def operate(self, p_data): """ Run the operation """ if self.is_value: p_data.memory[self.val_x] -= self.val_y else: if self.val_y in p_data.memory: p_data.memory[self.val_x] -= p_data.memory[self.val_y] else: #p_data.memory[self.val_x] += 0 p_data.memory[self.val_y] = 0 return p_data.ptr+1 OPERATION = { 'set': OperationSet, 'mul': OperationMul, 'jnz': OperationJnz, 'sub': OperationSub, } class Parser(object): """ Program implementation """ def __init__(self, name, data): """Constructor for the parser """ self.instr = self.read_data(data.split('\n')) self.ptr = 0 self.memory = defaultdict(int) self.name = name self.mulinvoked = 0 def __repr__(self): """Representation of the parser """ return "Parser_{}"# waits for {} with {} messages".format(self.name, self.needs_value, len(self.messages)) @staticmethod def read_data(data): """ Create the proper instances of the instructions """ return [Instruction.parse(line) for line in data] def process(self): """ Process the input data until the end""" condition = True max_ptr = len(self.instr) while condition: if self.ptr >= max_ptr or self.ptr < 0: condition = False else: instr = self.instr[self.ptr] self.ptr = instr.operate(self) return condition def solution(data): """ Solution to the problem """ parser = Parser(0, data) parser.process() return parser.mulinvoked if __name__ == "__main__": PARSER = ArgumentParser() PARSER.add_argument("--input", dest='input', action='store_true') PARSER.add_argument("--test") ARGS = PARSER.parse_args() if ARGS.input: with(open('input.txt', 'r')) as input_file: print(solution(input_file.read())) elif ARGS.test: print(solution(str(ARGS.test))) else: DEBUG = """set b 81 set c b jnz a 2 jnz 1 5 mul b 100 sub b -100000 set c b sub c -17000 set f 1 set d 2 set e 2 set g d mul g e sub g b jnz g 2 set f 0 sub e -1 set g e sub g b jnz g -8 sub d -1 set g d sub g b jnz g -13 jnz f 2 sub h -1 set g b sub g c jnz g 2 jnz 1 3 sub b -17 jnz 1 -23""" print(solution(DEBUG))
a6b4edcabb259befe9a3e11f310111a873dc38d9
uCognitive/Python-Beginner
/src/while loop/check prime number.py
377
4.0625
4
num = int(input("Enter number to check: ")) # user inpit i = 2 #loop variable initialization p = 0 # conitional variable while i < num: if num%i == 0: #check p = p+1 # if condition become true then change the value of variable p i = i +1 #loop increament if p == 0: # if value of p is not change then it is prime print("prime") else: print("Not prime")
f74416b179acac639c73cfe8a0e2d3938e874c0a
tuseto/PythonHomework
/week2/2-List-Problems/sum_numbers.py
266
4.0625
4
n = int(input("Enter n: ")) count = 1 numbers = [] result = 0 while count <= n: number = int(input("Enter number: ")) numbers = numbers + [number] count += 1 for num in numbers: result = result + num print("The sum is: " + str(result))
9e121f56559fc8da2424c605841a8e4a2be947a2
radekkania/python-projects
/src/algorithms/pattern_search/pattern_search_algorithm.py
7,142
3.59375
4
"""by radoslaw kania""" class SundaySearch: """Sunday pattern search algorithm. """ def _matches_at(self, text, index, pattern): for i in range(len(pattern)): self._counter += 1 if text[index + i] != pattern[i]: return -1 return index def __init__(self, alphabet, pattern): self.last = [] self.last_dict = {} self._pattern = pattern self._alphabet = alphabet self._prepare_tab() self._counter = 0 # prepares 'last' tab, table with index of last occurrence # for each letter from alphabet def _prepare_tab(self): for letter in self._alphabet: index = self._get_last_index_of(letter) self.last_dict[letter] = index # returns index of last letter occurrence in pattern def _get_last_index_of(self, letter): j = 1 for i in range(len(self._pattern) - 1, -1, -1): if self._pattern[i] == letter: return j j += 1 return len(self._pattern) + 1 """ method creates list of last occurrence of sign of pattern """ def _pre_process(self): for j in range(len(self._alphabet)): self.last_dict[self._pattern[j]] = len(self._pattern) + 1 for k in range(len(self._pattern)): sign = self._pattern[k] self.last_dict[sign] = k def search2(self, text): i = 0 while i <= len(text) - len(self._pattern): match_index = self._matches_at(text, i, self._pattern) if match_index == -1 and i + len(self._pattern) < len(text)-1: next_elem = text[i + len(pattern)] i = i + self.last_dict[next_elem] else: return i return -1 def search(self, text): i = 0 while i <= len(text) - len(self._pattern): match_index = self._matches_at(text, i, self._pattern) if match_index == -1: if i + len(self._pattern) > len(text) -1: return -1 next_elem = text[i + len(self._pattern)] i = i + self.last_dict[next_elem] else: return i return -1 def print_tab(self): print(self.last) def get_counter(self): return self._counter class NaiveSearchAlgorithm: """" Naive pattern search algorithm""" def __init__(self): self._counter = 0 def _matches_at(self, text, index, pattern): for i in range(len(pattern)): self._counter += 1 if text[index + i] != pattern[i]: return -1 return index def search(self, text, pattern): for i in range(len(text) - len(pattern) + 1): match_index = self._matches_at(text, i, pattern) if match_index != -1: return match_index return -1 def get_counter(self): return self._counter class MorrisPrattAlgorithm: def __init__(self): self.__PI = [] self.__counter = 0 def _matches_at(self, text, index, pattern): for i in range(len(pattern)): self.__counter += 1 if text[index + i] != pattern[i]: return -1 return index def prepare_tab(self, pattern): pattern_size = len(pattern) self.__PI = [None for _ in range(pattern_size)] self.__PI[0] = -1 # sentry ps_len = self.__PI[0] # length = prefix_suffix_length for i in range(1, pattern_size, 1): while ps_len > -1 and pattern[ps_len] != pattern[i-1]: ps_len = self.__PI[ps_len] ps_len += 1 self.__PI[i] = ps_len # pp - pattern position # lp - dlugosc prefiksu wzorca p pasujacego do okna wzorca w lanchu # i - index of matching sign # P - pattern def search(self, text, p): self.prepare_tab(p) pp = -1 lp = 0 for i in range(len(text)-1): while lp > -1 and p[lp] != text[i]: lp = self.__PI[lp] lp += 1 if lp < len(p): while pp < i - lp + 1: pp += 1 pp += 1 lp = self.__PI def print_PI(self): print(self.__PI) def get_counter(self): return self.__counter if __name__ == "__main__": import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt import random # test 1 pattern = "abcab" alphabet = "abcdef" text = '' for _ in range(1000): text += random.choice(alphabet) text += pattern print("length of text" + str(len(text))) print("Sunday method") s = SundaySearch(alphabet, pattern) print(s.search(text)) sundayCount = s.get_counter() print("Naive method") n = NaiveSearchAlgorithm() print(n.search(text, pattern)) naiveCount = n.get_counter() # charts algorithms = ('Sunday', 'Naive') y_pos = np.arange(len(algorithms)) results = [sundayCount, naiveCount] plt.bar(y_pos, results, align='center', alpha=0.5) plt.xticks(y_pos, algorithms) plt.ylabel('count of comparision for booth algorithms') plt.title('sunday and naive comparision for text of length 10000') plt.show() # tests 2 text_alphabets = ['ab', 'abcd', 'abcdefgh', 'abcdefghijklmno', 'abcdefghijklmnopqrstuvwxyz'] patterns = [] texts = [] pattern_sizes = [4, 8, 16, 20] text_sizes = [1000, 5000, 10000, 50000] # preparing patterns for i in range(len(pattern_sizes)): pattern = '' for _ in range(pattern_sizes[i]): pattern += random.choice(text_alphabets[i]) patterns.append(pattern) text = '' for _ in range(1000): text += random.choice(text_alphabets[i+1]) texts.append(text) sunday_results = [] naive_results = [] for i in range(len(patterns)): sunday = SundaySearch(text_alphabets[i+1], patterns[i]) sunday.search(texts[i]) sunday_results.append(sunday.get_counter()) naive = NaiveSearchAlgorithm() naive.search(texts[i], patterns[i]) naive_results.append(naive.get_counter()) print(sunday_results) print(naive_results) n_test = 4 fig, ax = plt.subplots() index = np.arange(n_test) bar_width = 0.35 opacity = 0.8 sunday = tuple(sunday_results) naive = tuple(naive_results) rects1 = plt.bar(index, sunday_results, bar_width, alpha=opacity, color='b', label='sunday') rects2 = plt.bar(index + bar_width, naive_results, bar_width, alpha=opacity, color='g', label='naive') plt.xlabel('Tests') plt.ylabel('count of comparision of letters') plt.title('comparision sunday vs naive') plt.xticks(index + bar_width, ('Test 1', 'Test 2', 'Test 3', 'Test 4')) plt.legend() plt.tight_layout() plt.show()
68b4f7a3c409b3cb9fd92b0e1b95dffe8cea1729
AdamZhouSE/pythonHomework
/Code/CodeRecords/2975/60691/248001.py
91
3.796875
4
str1 = input("input a string:") list1 = list(str1) list1.sort() s = "".join(list1) print(s)
818008bac140c37d20dbdbaf46ea1ffa547a2a03
alex8937/CS61A-The-Structure-and-Interpretation-of-Computer-Programs
/lec/lec11/linked_list.py
1,075
3.921875
4
empty = 'empty' def link(head, rest = empty): assert is_link(rest), 'rest is not a linked list' return [head, rest] def is_link(s): return s == empty or (len(s) == 2 and is_link(s[1])) def head(s): assert is_link(s), 'head only applies to linked list' assert s != empty, 'empty list has no head' return s[0] def rest(s): assert is_link(s), 'head only applies to linked list' assert s != empty, 'empty list has no rest' return s[1] def len_link(s): length = 0 while s != empty: s, length = s[1], length + 1 return length def getitem_link(s, i): while i > 0: s, i = rest(s), i - 1 return head(s) def extend_link(s, t): assert is_link(s), 's is not a linked list' assert is_link(t), 't is not a linked list' if s == empty: return t else: return link(head(s), extend_link(rest(s), t)) def apply_to_all(fun, s): assert is_link(s), 's is not a linked list' if s == empty: return s else: return link(fun(head(s)), apply_to_all(fun, rest(s)))
9d66a8ae68552fdd598b7c9c9f2dd97c09f2f542
marvance/MIT-OCW-problemsets
/mit60001/ps4/ps4c.py
9,610
3.625
4
# Problem Set 4C # Name: <your name here> # Collaborators: # Time Spent: x:xx import string from ps4a import get_permutations ### HELPER CODE ### def load_words(file_name): ''' file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. ''' print("Loading word list from file...") # inFile: file inFile = open(file_name, 'r') # wordlist: list of strings wordlist = [] for line in inFile: wordlist.extend([word.lower() for word in line.split(' ')]) print(" ", len(wordlist), "words loaded.") return wordlist def is_word(word_list, word): ''' Determines if word is a valid word, ignoring capitalization and punctuation word_list (list): list of words in the dictionary. word (string): a possible word. Returns: True if word is in word_list, False otherwise Example: >>> is_word(word_list, 'bat') returns True >>> is_word(word_list, 'asdf') returns False ''' word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") return word in word_list ### END HELPER CODE ### WORDLIST_FILENAME = 'words.txt' # you may find these constants helpful VOWELS_LOWER = 'aeiou' VOWELS_UPPER = 'AEIOU' CONSONANTS_LOWER = 'bcdfghjklmnpqrstvwxyz' CONSONANTS_UPPER = 'BCDFGHJKLMNPQRSTVWXYZ' class SubMessage(object): def __init__(self, text): ''' Initializes a SubMessage object text (string): the message's text A SubMessage object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words) ''' self.message_text = text self.valid_words = load_words(WORDLIST_FILENAME) def get_message_text(self): ''' Used to safely access self.message_text outside of the class Returns: self.message_text ''' return self.message_text def get_valid_words(self): ''' Used to safely access a copy of self.valid_words outside of the class. This helps you avoid accidentally mutating class attributes. Returns: a COPY of self.valid_words ''' return self.valid_words.copy() def build_transpose_dict(self, vowels_permutation): ''' vowels_permutation (string): a string containing a permutation of vowels (a, e, i, o, u) Creates a dictionary that can be used to apply a cipher to a letter. The dictionary maps every uppercase and lowercase letter to an uppercase and lowercase letter, respectively. Vowels are shuffled according to vowels_permutation. The first letter in vowels_permutation corresponds to a, the second to e, and so on in the order a, e, i, o, u. The consonants remain the same. The dictionary should have 52 keys of all the uppercase letters and all the lowercase letters. Example: When input "eaiuo": Mapping is a->e, e->a, i->i, o->u, u->o and "Hello World!" maps to "Hallu Wurld!" Returns: a dictionary mapping a letter (string) to another letter (string). ''' letter_dictionary = {} punctuation = list(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") for i, char in enumerate(vowels_permutation.lower()): letter_dictionary[VOWELS_LOWER[i]] = char for i, char in enumerate(vowels_permutation.upper()): letter_dictionary[VOWELS_UPPER[i]] = char for char in CONSONANTS_LOWER: letter_dictionary[char] = char for char in CONSONANTS_UPPER: letter_dictionary[char] = char for symbol in punctuation: letter_dictionary[symbol] = symbol return letter_dictionary def apply_transpose(self, transpose_dict): ''' transpose_dict (dict): a transpose dictionary Returns: an encrypted version of the message text, based on the dictionary ''' encrypted_message = [] for char in self.message_text: encrypted_message.append(transpose_dict[char]) return ''.join(encrypted_message) class EncryptedSubMessage(SubMessage): def __init__(self, text): ''' Initializes an EncryptedSubMessage object text (string): the encrypted message text An EncryptedSubMessage object inherits from SubMessage and has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words) ''' SubMessage.__init__(self, text) def decrypt_message(self): ''' Attempt to decrypt the encrypted message Idea is to go through each permutation of the vowels and test it on the encrypted message. For each permutation, check how many words in the decrypted text are valid English words, and return the decrypted message with the most English words. If no good permutations are found (i.e. no permutations result in at least 1 valid word), return the original string. If there are multiple permutations that yield the maximum number of words, return any one of them. Returns: the best decrypted message Hint: use your function from Part 4A ''' #list of possible vowel transpositions from possible vowels permutations tranpose_dict_list = [] #list of decrypted messages de_message_list = [] #list of all permutations (letter orders) of aeiou perm_list = get_permutations('aeiou') #for each possible permutation for perm in perm_list: #add to trans_dict_list the dictionary that assigns #transpositions according to the current permutation tranpose_dict_list.append(self.build_transpose_dict(perm)) #for dictonary in list of possible transposition dictionaries for dic in tranpose_dict_list: #decrypted message equals text after you transpose it #with the current dictionary de_message = self.apply_transpose(dic) #append current decrypted message to list of decrypted messages de_message_list.append(de_message) #store True or False values when checking to see if #a portion of the message is a real word test = [] #store messages plus their number of True values from test[] big_test = [] #get list of valid words to compare decrypted text to word_list = self.get_valid_words() #for message in list of decrypted messages for mes in de_message_list: #decrypted words equals each word in message separated de_words = mes.split() print("decrypted words: ", de_words) #for each word in decrypted message for word in de_words: #check to see if it's a real word if is_word(word_list, word): #if it is, append a value of True to list of #"is it a word?" booleans test.append(1) else: #if it's not, append a value of false test.append(0) #append to list of _______ a tuple containing the total number of True values for #the current message in message list, #plus the message itself big_test.append((sum(test), mes)) print("big test: ",big_test) #you're done using test, so delete all its contents del test[0:len(test)] #best choice is the maximum key in big_test best_choice = max(big_test) #store possible decrypted messages that might become result possible_de_message = [] #for tuple in list of messages and number of True values for tup in big_test: #if the first tuple has the max number of True values #and the second tuple is not already in possible decrypted messages if tup[0] == best_choice[0] and tup[1] not in possible_de_message: #add to possible decrypted messages the second tuple possible_de_message.append(tup[1]) #initialize empty string to hold result de_string = '' #for message in possible results for mes in possible_de_message: #result equals current result, a comma to separate, and the message de_string = de_string + ', ' + mes #return everything after the comma in result return de_string[1:] if __name__ == '__main__': # Example test case message = SubMessage("Hello World!") permutation = "eaiuo" enc_dict = message.build_transpose_dict(permutation) print("Original message:", message.get_message_text(), "Permutation:", permutation) print("Expected encryption:", "Hallu Wurld!") print("Actual encryption:", message.apply_transpose(enc_dict)) enc_message = EncryptedSubMessage(message.apply_transpose(enc_dict)) print("Decrypted message:", enc_message.decrypt_message()) #TODO: WRITE YOUR TEST CASES HERE
1e7451dfe7910eaac2abb7847adecd39b20534f2
JDer-liuodngkai/LeetCode
/offer/40-最小的k个数.py
4,146
3.890625
4
""" 输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。 不要求按顺序输出 """ from typing import List # def quick_sort2(arr): # if len(arr) < 2: # return arr # # left, right = [], [] # mid = arr[len(arr) // 2] # arr.remove(mid) # # for v in arr: # if v <= mid: # left.append(v) # else: # right.append(v) # # return quick_sort2(left) + [mid] + quick_sort2(right) # # # def partition(arr, low, high): # pivot = arr[low] # 随便取 数列首元素位 枢轴,划分元素到左右 # # while low < high: # # 设置 pivot 为 low,先 high 才能实现二者替换 # while low < high and arr[high] >= pivot: # high -= 1 # arr[low], arr[high] = arr[high], arr[low] # a[low] 枢轴替换到 a[high] # # # 如果 low 在前,替换的并不是 枢轴的值 # while low < high and arr[low] <= pivot: # low += 1 # arr[low], arr[high] = arr[high], arr[low] # a[high] 枢轴替换到 a[low] # # return low # 枢轴元素 所在位置 # def partition(arr, low, high): # i = (low - 1) # 最小元素索引 # pivot = arr[high] # # for j in range(low, high): # # 当前元素小于或等于 pivot # if arr[j] <= pivot: # i += 1 # 对应当前 j 所在 elem # arr[i], arr[j] = arr[j], arr[i] # # arr[i + 1], arr[high] = arr[high], arr[i + 1] # return i + 1 # arr[high] 是 pivot,所以最终 pivotLoc = i+1 # # def quick_sort(arr, low, high): # if low < high: # 递归终止条件,当不满足时,表示不需要排序 # # 虽然可以合并位1个函数,但是 partition 独立出来更清晰 # pivLoc = partition(arr, low, high) # 分治 # quick_sort(arr, low, pivLoc - 1) # 注意 low, high # quick_sort(arr, pivLoc + 1, high) class Solution: """ 取出最小的 k 个数 1. 快排 寻找下标为 k-1 的数, 左侧的数都 < 枢轴值 2. 堆排序,小根堆,k 次取堆顶 3. 排序 + 截取 4. """ def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: if not arr or k == 0 or k > len(arr): return [] def partition(low, high): pivot = arr[low] # 随便取 数列首元素位 枢轴,划分元素到左右 while low < high: # 设置 pivot 为 low,先 high 才能实现二者替换 while low < high and arr[high] >= pivot: high -= 1 arr[low], arr[high] = arr[high], arr[low] # a[low] 枢轴替换到 a[high] # 如果 low 在前,替换的并不是 枢轴的值 while low < high and arr[low] <= pivot: low += 1 arr[low], arr[high] = arr[high], arr[low] # a[high] 枢轴替换到 a[low] return low # 枢轴元素 所在位置 def quick_search(low, high): pivotLoc = partition(low, high) # 不管 low,high 为多少, pivotLoc 对应全局位置 if pivotLoc == k - 1: return arr[:k] # > 左侧, < 右侧 return quick_search(low, pivotLoc - 1) if pivotLoc > k - 1 else quick_search(pivotLoc + 1, high) return quick_search(0, len(arr) - 1) def getLeastNumbers3(self, arr: List[int], k: int) -> List[int]: return sorted(arr)[:k] def getLeastNumbers4(self, arr: List[int], k: int) -> List[int]: # 冒泡排序,将 len(arr) - k 个最大数排好; # O(n^2) 超出时间限制 for i in range(len(arr) - k): for j in range(0, len(arr) - i - 1): # 末次: (0, len(arr)-k), 恰好到 [0,k-1] 之后全是较大数 if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr[:k] s = Solution() # arr, k = [3, 2, 1], 2 arr, k = [0, 0, 0, 2, 0, 5], 1 print(s.getLeastNumbers(arr, k)) print(s.getLeastNumbers3(arr, k))
b5920d757099c82a445968a3ec820256906846e3
Ericmanh/cac_ham_python
/CacHamToanHoc/ham_time.py
235
3.796875
4
# Hàm time gồm clock và time from time import clock print("enter your name:", end="") start_time =clock() name = input() print("nhập name") elapsed = clock() - start_time print(name, "it took you", elapsed ,"second to repond")
89b2eba528ea05816b56830c2057f568c9f5ca89
gracerichardson0/Functions
/examscore.py
242
3.953125
4
n = 0 total = 0 exam = int(input("Enter exam (-1 to quit)")) while exam != -1 : total += exam n +=1 exam = int (input ("Enter exam (-1 to quit)")) if n > 0 : print ("Average: ", total/n) else : print ("No exams entered")
387363a8892d50a37cccdebe13635949120768a5
ODYTRON/Challenge-Modules-Classes-Error-Handling-And-List-Comprehension
/First Class example in python.py
1,884
4.4375
4
# First Class example in python. the example is a dataset which has to do # with NFL suspensions # Class name class Suspension(): # Initial function , initiated with self and a key word to archive columns # note that you set columns # you call positions of a single arbitrary row for the moment , then it will be specific , which row def __init__(self,column): # we set all the properties to the coresponding columns self.name = column[0] self.team = column[1] self.games = column[2] self.suspensions = column[3] # now let's play with the exceptions here we need to convert the year to integer # if this fails we set the particular value of the year to 0 (for example if the line dont exist) try: # here is the conversion self.year = int(column[5]) # if there is fail the exception sets year property to 0 except Exception: self.year = 0 # METHODS LETS MAKE SOME METHODS TO RETURN VALUES FROM OUR ROWS def get_year(self): return(self.year) def get_name(self): return(self.name) def get_team(self): return(self.team) def get_games(self): return(self.games) def get_suspensions(self): return(self.suspensions) # make an instance for the first suspension # note that you call lines # now we have specific row , our class instance has inside which columns to access first_suspension = Suspension(nfl_suspensions[0]) # call all the methods to archive info about the first line of the data set get_first_suspension_year = first_suspension.get_year() get_first_suspension_name = first_suspension.get_name() get_first_suspension_team = first_suspension.get_team() get_first_suspension_games = first_suspension.get_games() get_first_suspension_suspensions = first_suspension.get_suspensions()
23370a55d7322338154cb1e60eb57121efcf3cdc
energy-in-joles/Advent-of-Code-2020-Solutions
/Day10/Day10.py
2,741
3.796875
4
from math import factorial def main(): with open('test.txt', 'r') as file: joltages = sorted([int(joltage.strip()) for joltage in file]) # Part 1: count number of j_dff of 1 and 3 and multiply j_1 = j_3 = 0 in_j = 0 # input joltage diff_lst = [] joltages.insert(0, in_j) # add to the front joltages.append(joltages[-1] + 3) # append final output that is always 3 more than max adapter print(joltages) for i in range(len(joltages) - 1): # simple count of diff 1 and 3 j_diff = joltages[i + 1] - joltages[i] diff_lst.append(j_diff) if j_diff == 1: j_1 += 1 elif j_diff == 3: j_3 += 1 elif j_diff != 2: # if j_diff == 2, ignore for Part 1 print(f"ERROR: Voltage Difference larger than 3 between {joltages[i]} and {joltages[i + 1]}") print(f"Part 1: {(j_1) * (j_3)}") print(f"Part 2: {calculate_combis(3, diff_lst)}") better_part2_solution(joltages) # Part 2: find number of combinations # only block of diff = 1 can have numbers removed while not exceeding a difference of 3, so calculate combinations using blocks of 1. # Solution makes 2 assumptions: # Firstly, that there are only 2 cases: diff = 1 or 3 (which is true for all cases given) # Secondly, that one_count - 1 (the len(consecutive block of diff = 1)) < max_diff (3) + 2 (too complicated to account for and not an issue for this problem) # for max_diff of x, number of allowed consecutive 1s is x - 1 # n = one_count - 1 (ignore last 1 ignored because if last 1 removed, difference = 4) # So the combinations of C for each block of 1s are nC(x-1) + nC(x-2) + ... + nC(1) # total combinations equals produt of all 1s block combinations def calculate_combis(max_diff, diff_lst): total_product = 1 one_count = -1 # starts at -1 because last 1 ignored for diff in diff_lst: if diff == 1: one_count += 1 # count if difference is 1 else: if one_count >= -1: n_sum = 1 for j in range(1, max_diff): n_sum += combi(one_count, j) total_product *= n_sum # multiply all individual 1 block combinations one_count = -1 return total_product def combi(n, r): # n choose r (implemented for use prior to python 3.8) if n < r: return 0 # return 0 instead of error return int(factorial(n) / (factorial(r) * factorial(n - r))) #Taken from u/RobBobertsThe3rd's solution on r/adventofcode def better_part2_solution(joltages): tribo_seq = [1] + [0 for i in range(1,len(joltages))] for i in range(1,len(tribo_seq)): tribo_seq[i] = sum(tribo_seq[o] for o in range(i-3,i) if joltages[o] + 3 >= joltages[i]) print(tribo_seq) return tribo_seq[-1] if __name__ == "__main__": main()
0d8aa04f331936c62772491130c4150638cca531
vivian2943/01
/23 w_for.py
177
3.90625
4
for i in range(0,3): a = input('輸入密碼:') if a == 'key': print('登入') else: print('錯誤,剩餘嘗試次數為'+ str(2 - i))