blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8a7be25112d5c763143b86a99757412d9a2913a6
pavdmyt/leetcode
/reference/linked-lists/linked_deque.py
2,217
3.921875
4
from doubly_linked_list import _DoublyLinkedBase class LinkedDeque(_DoublyLinkedBase): """Double-ended queue implementation based on a doubly linked list.""" def first(self): """Return (but do not remove) the element at the front of the deque.""" if self.is_empty(): raise Empty("Deque is empty") return self._header._next._element # real item just after header def last(self): """Return (but do not remove) the element at the back of the deque.""" if self.is_empty(): raise Empty("Deque is empty") return self._trailer._prev._element # real item just before trailer def insert_first(self, e): """Add an element to the front of the deque.""" self._insert_between(e, self._header, self._header._next) # after header def insert_last(self, e): """Add an element to the back of the deque.""" self._insert_between(e, self._trailer._prev, self._trailer) # before trailer def delete_first(self): """Remove and return the element from the front of the deque. Raise Empty exception if the deque is empty. """ if self.is_empty(): raise Empty("Deque is empty") return self._delete_node(self._header._next) def delete_last(self): """Remove and return the element from the back of the deque. Raise Empty exception if the deque is empty. """ if self.is_empty(): raise Empty("Deque is empty") return self._delete_node(self._trailer._prev) class Empty(Exception): """Empty ADT.""" def main(): ld = LinkedDeque() print("* Insert first") for e in "abcdef": print(f"inserting {repr(e)} to deque head") ld.insert_first(e) print(f"* Deque length: {len(ld)}") print("\n* Delete first") for _ in range(len(ld) // 2): e = ld.delete_first() print(f"deleting: {repr(e)}") print(f"* Deque length: {len(ld)}") print("\n* Delete last") for _ in range(len(ld)): e = ld.delete_last() print(f"deleting: {repr(e)}") print(f"* Deque length: {len(ld)}") if __name__ == '__main__': main()
aed88f94f2e7eb2795ede3feedf5436bf89c7bbc
bellatrixdatacommunity/data-structure-and-algorithms
/leetcode/string/student-attendance-record-i.py
1,158
3.828125
4
""" ## Questions ### 551. [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i/) You are given a string representing an attendance record for a student. The record only contains the following three characters: 'A' : Absent. 'L' : Late. 'P' : Present. A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). You need to return whether the student could be rewarded according to his attendance record. Example 1: Input: "PPALLP" Output: True Example 2: Input: "PPALLL" Output: False """ ## Solutions class Solution: def checkRecord(self, s: str) -> bool: A = 0 L = -1 if s == "": return True try: A = s.count("A") except: pass if A > 1: return False try: L = s.find("LLL") except: pass if L != -1: return False return True # Runtime: 28 ms, faster than 64.72% of Python3 online submissions # Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions
e16f84920fd97a58ea59fd80c83cee30def863e2
bermec/challenges
/re_check.py
107
3.5
4
import re a = 'XX X' ans = re.findall('\S{2}|\S', a) print(ans) ans = re.findall('\S{3}|\S', a) print(ans)
5c6e171f77c9e4038aa2c4c9aa45500e65809060
erdiay/DataStructuresAndAlgorithmsPython
/SortingAlgorithms/selectionSort.py
394
3.671875
4
#Space complexity is O(1) #Time complexity is O(n^2) def selectionSort(A): length = len(A) i = 0 while i < length: min = A[i] minIndex = i j = i + 1 while j < length: if A[j] < min: min = A[j] minIndex = j j += 1 temp = A[i] A[i] = min A[minIndex] = temp i += 1
e0d1a5296a2f5b48c04f00ef88c543b87583f445
4roses41/COM404
/1.basics/3-decision/8-nestception/bot.py
811
4.125
4
whereToLook = input("Where should I look? (bedroom/ bathroom /lab): ") print(whereToLook) if whereToLook == "bedroom": whereInBedroom = input("Where in the bedroom should I look?") if whereInBedroom == "under the bed": print("Found some shoes but no battery") else: print("Found some mess but no battery") if whereToLook == "bathroom": whereInBathroom = input("Where in the bathroom should I look?") if whereInBathroom == "in the bathtub": print("Found a rubber duck but no battery") else: print("It is wet but I found no battery.") if whereToLook == "lab": whereInlab = input("Where in the lab should I look?") if whereInlab == "on the table": print("Yes! I found my battery!") else: print("Found some tools but no battery.")
e5386a1e074ce87f3fb15ad3ee889a2549c3cf08
nampng/self-study
/python/CTCI/Chapter2/Stack.py
847
3.78125
4
# Stack class # A stack is a data structure that mainly focuses on whats on the top # Data can only be added to the top # Data can only be removed from the top # Data can only be viewed from the top # Like a stack of dinner plates. class Stack: def __init__(self): self.stack = [] self.top = -1 def Push(self, value): self.stack.append(value) self.top += 1 return self.top def Pop(self): if self.top > -1: val = self.stack.pop() self.top -= 1 return val else: return None def Top(self): if self.top > -1: return self.stack[self.top] else: return None def Count(self): if self.top > -1: return len(self.stack) else: return None
f68a0413d675af64b20037c82d5bc02c1658d03d
douglasmarcelinodossantos/Douglas_lista1_Python
/list1_12.py
913
3.71875
4
""" 12. Escreva uma função que liste todos os números primos até 258 (mais o dia do seu aniversário). Utilize a divisão modular (%). """ meu_aniversario = int(input('Informe o dia do seu aniversário, caso você deseja saber os ' 'números primos contidos no intervalo compreendido entre 1 e o número 258 ' 'somado ao dia do seu aniversário: ')) def primos_aniversario (meu_aniversario): primos = [2] contador = 0 ultimo_dia = 258 + meu_aniversario for i in range (2, ultimo_dia): for each in primos: if i % each == 0: contador = 1 if contador != 1: primos.append(i) contador = 0 primos.append(1) primos.append(meu_aniversario) primos.sort() print ("Os números primos entre 1 e 258 acrescido do seu aniversários estão a seguir:") print (primos) primos_aniversario (meu_aniversario)
a88803281b183f11674c4e53e26c4492b7b186a3
porosya80/checkio
/Electronic_Station/multicolored_lamp.py
1,882
4.0625
4
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run multicolored-lamp # https://py.checkio.org/mission/multicolored-lamp/ # The New Year is coming and you've decided to decorate your home. But simple lights and Christmas decorations are so boring, so you have figured that you can use your programing skills and create something really cool and original.Your task is to create the class Lamp() and method light() which will make the lamp glow with one of the four colors in the sequence - (‘Green’, ‘Red’, ‘Blue’, ‘Yellow’). When the light() method is used for the first time, the color should be 'Green', the second time - 'Red' and so on.If the current color is 'Yellow', the next color should be 'Green' and so on.In this mission you can use theStatedesign pattern. It's highly useful in the situations where object should change its behaviour depending on the internal state. # # Example: # lamp_1 = Lamp() # lamp_2 = Lamp() # # lamp_1.light() #Green # lamp_1.light() #Red # lamp_2.light() #Green # # lamp_1.light() == "Blue" # lamp_1.light() == "Yellow" # lamp_1.light() == "Green" # lamp_2.light() == "Red" # lamp_2.light() == "Blue" # # # # Input:A few strings indicating the number of times the lamp is being turned on. # # Output:The color of the lamp. # # Precondition:4 colors: Green, Red, Blue, Yellow. # # # END_DESC class Lamp: pass if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing lamp_1 = Lamp() lamp_2 = Lamp() lamp_1.light() #Green lamp_1.light() #Red lamp_2.light() #Green assert lamp_1.light() == "Blue" assert lamp_1.light() == "Yellow" assert lamp_1.light() == "Green" assert lamp_2.light() == "Red" assert lamp_2.light() == "Blue" print("Coding complete? Let's try tests!")
a37de490c4738e54d1f68f6194af7c2a47c96969
pavarotti305/python-training
/if_else_then.py
2,994
4.4375
4
print('') print('''Here is the structure: if expression: like on this example if var1 is true that means = 1 print the value of true expression statement(s) else: else var1 is false that means = 0 print the value of false expression statement(s)''') truevalue = 1 if truevalue: print("1 - Got a true expression value") print(truevalue) else: print("1 - Got a false expression value") print(truevalue) falsevalue = 0 if falsevalue: print("2 - Got a true expression value") print(falsevalue) else: print("2 - Got a false expression value") print(falsevalue) print("Good bye!") print('') print('''Here is the second structure with elif: if expression1: elif expression2: statement(s) elif expression3: statement(s) else: statement(s)''') var = 100 if var == 200: print("1 - Got a true expression value") print(var) elif var == 150: print("2 - Got a true expression value") print(var) elif var == 100: print("3 - Corresponding to a true expression value") print(var) else: print("4 - Got a false expression value") print(var) print("Good bye!") print('''Python operators: + Addition Adds values on either side of the operator. - Subtraction Subtracts right hand operand from left hand operand. * Multiplication Multiplies values on either side of the operator / Division Divides left hand operand by right hand operand % Modulus Divides left hand operand by right hand operand and returns remainder ** Exponent Performs exponential (power) calculation on operators // Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. like 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0 == If the values of two operands are equal, then the condition becomes true. != If values of two operands are not equal, then condition becomes true. <> If values of two operands are not equal, then condition becomes true. > If the value of left operand is greater than the value of right operand, then condition becomes true. < If the value of left operand is less than the value of right operand, then condition becomes true. >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. <= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. = Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c += It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a -= Subtract AND subtracts right operand from the left operand and assign the result to left operand c -= a = c = c - a *= Multiply AND c *= a is equivalent to c = c * a /= Divide AND c /= a is equivalent to c = c / a %= Modulus AND c %= a is equivalent to c = c % a **= Exponent AND c **= a is equivalent to c = c ** a //= Floor Division c //= a is equivalent to c = c // a''')
dfdd6d5b5b72b781f302703f7fcf356474f76610
nickfang/classes
/projectEuler/webScraping/problemTemplates/362.py
596
3.640625
4
# Squarefree factors # # #Consider the number 54. #54 can be factored in 7 distinct ways into one or more factors larger than 1: #54, 2×27, 3×18, 6×9, 3×3×6, 2×3×9 and 2×3×3×3. #If we require that the factors are all squarefree only two ways remain: 3×3×6 and 2×3×3×3. # # #Let's call Fsf(n) the number of ways n can be factored into one or more squarefree factors larger than 1, so #Fsf(54)=2. # # #Let S(n) be ∑Fsf(k) for k=2 to n. # # #S(100)=193. # # #Find S(10 000 000 000). # # import time startTime = time.time() print('Elapsed time: ' + str(time.time()-startTime))
b803d6de6e8a65638d91d59e9cdcfaf43d998031
SWKANG0525/Algorithm
/BaekJoon/BOJ 15652.py
414
3.515625
4
# Author : Kang Ho Dong # Date : 2020 - 07 - 18 # Title : BOJ 15652 # Language : Python 3 def func_backtracking(n,m,ls,idx): if len(ls) == m and len(ls) != 0: for i in ls: print(i,end=" ") print() return for i in range(idx,n+1): ls.append(i) func_backtracking(n,m,ls,i) ls.pop() N,M = map(int,input().split()) func_backtracking(N,M,[],1)
ba4244504b874614efa92ec2702e22e54a304d10
RedRingGalaxy/DCP
/P443.py
1,221
4.15625
4
#Problem Statement [Medium] ''' Implement a queue using Two Statcks. Recall that queue is a FIFO DS with the following methods: 1.Enqueue, which insert an element into queue 2.Dequeuq, which remove an element from the queue ''' # Implement a Queue usign two stacks # Here we consider list as stack class Stacked_Queue: def __init__(self): self._stack1 = list() self._stack2 = list() # Enqueue append the value into the stack1 def enqueue(self,value): self._stack1.append(value) # Dequeue pop all items except last one from statk1 and append it to stack2 # pop last item from stack1 and store it to the local variable for return # Pop all items from stack2 and append it to stack1 def dequeue(self): for i in range(len(self._stack1)-1): self._stack2.append(self._stack1.pop()) pop_itm = self._stack1.pop() for i in range(len(self._stack2)): self._stack1.append(self._stack2.pop()) return pop_itm if __name__ == "__main__": q1 = Stacked_Queue() q1.enqueue(1) q1.enqueue(2) q1.enqueue(3) print(q1.dequeue(),q1.dequeue(),q1.dequeue())
fc89d32460b196474a8fc24e88ffba0c76276d14
deepankermishra/Code
/Coding/sinkZerosBinaryTree.py
1,324
3.78125
4
""" https://massivealgorithms.blogspot.com/2019/02/sink-zeros-in-binary-tree.html """ class Node: def __init__(self, val): self.val = val self.left = self.right = None class SinkZeros: def sinkZeros(self, root): self.stack = [] self.zeros = 0 def dfs(node): if not node: return if node.val == 0: self.zeros += 1 else: self.stack.append(node.val) dfs(node.left) dfs(node.right) if self.zeros > 0: node.val = 0 self.zeros -= 1 else: node.val = self.stack.pop() dfs(root) return root def printTree(self, node): def helper(node): if not node: print('x', end=' ') return print(node.val, end=' ') helper(node.left) helper(node.right) print("------") helper(node) print() print("------") def testSk(self, node): self.printTree(node) self.sinkZeros(node) self.printTree(node) def test(): root0 = Node(0) root0.left = Node(0) root0.left.left = Node(0) root0.right = Node(0) root0.right.left = Node(1) root1 = Node(0) root2 = Node(0) root2.left = Node(3) root2.left.left = Node(4) root2.right = Node(0) root2.right.left = Node(0) root2.right.left.right = Node(1) root2.right.right = Node(2) tests = [root0, root1, root2] sk = SinkZeros() for tt in tests: sk.testSk(tt) SinkZeros.test()
703133968ef7bbf223b677f8bfd9ec7915b54c96
Anju-PT/pythonfilesproject
/Functions/calculator.py
851
4.09375
4
def add(num1,num2): s=num1+num2 print(num1,"+",num2,"=",s) def sub(num1,num2): s=num1-num2 print(num1,"-",num2,"=",s) def mul(num1,num2): m=num1*num2 print(num1,"*","num2","=",m) def div(num1,num2): d=num1/num2 print(num1,"/",num2,"=",d) # def fdiv(num1,num2): # f=num1//num2 # print(num1,"//",num2,"="f) print("Select Operation") print("1.Addition") print("2.Subtraction") print("3.Multiplication") print("4.Division") while True: ch=int(input("enter choice")) num1=float(input("enter num1")) num2=float(input("enter num2")) if(ch>0): if(ch==1): add(num1,num2) elif(ch==2): sub(num1,num2) elif(ch==3): mul(num1,num2) elif(ch==4): div(num1,num2) break else: print("invalid choice")
d0c0a67dfa4b4bbfff8ba4600c4a316d01e8e00d
stonecharioteer/notes-deprecated
/source/interview-prep/ds-algo/algorithms/sorting/insertion.py
1,462
4.40625
4
"""Insertion Sort""" def insertion_sort(inp_list): """Insertion Sort O(n**2) sorting algorithm. This algorithm will assume that the left portion is sorted. At the beginning, the first item in the list is assumed to be sorted. Then, the first item of the unsorted portion is *inserted* into this sorted sublist at the right position. When this is done, the items in the sublist that are greater than this item are shifted to the right. """ for index in range(1, len(inp_list)): position = index while position > 0 and inp_list[position] < inp_list[position-1]: # shift greater items to the left inp_list[position-1], inp_list[position] = ( inp_list[position], inp_list[position-1] ) position -= 1 return inp_list def binary_insertion_sort(inp_list): """Binary Insertion Sort. This is a modification of selection sort, wherein instead of comparing *all* items in the sorted list to the key value, we find the best place to put it. However, since the insertion will mandate the shifting of the numbers anyway, this will still take O(n**2). """ def test_insertion_sort(): import random array = [random.randint(0, 1000) for _ in range(10)] sorted_array = sorted(array) insertion_sorted_array = insertion_sort(array) assert insertion_sorted_array == sorted_array, "Insertion sort failed"
25cea8fb7480a27f43349fcd9a70b531df3fe9eb
Swierad/python_basics
/numbers game.py
461
3.53125
4
from random import randint rnd_num = int(randint(1,101)) result = False while result == False: try: answer = int(input("podaj liczbę\n")) except Exception: print("podana wartość to nie liczba") continue # eliminuje przerwę w programie if answer > rnd_num: print("za dużo!") elif answer < rnd_num: print("za mało!") else: print("Brawo, to jest ta liczba") result = True
a9343079691cd793ef3e6457d2cbe88cd9f676cf
jianai0496/python3_exercise
/求取质数.py
377
3.703125
4
import math cal_range = int(input("请输入计算质数的范围:")) prime_nums = [] for i in range(cal_range+1): if i==0 or i==1: continue num = 2 while num <= math.sqrt(i): if i%num == 0: break else: num += 1 if num >math.sqrt(i): prime_nums.append(i) for k in prime_nums: print(k)
46fd1e1735c2059f6d13a48c78f7b7e9a728f6e7
Aasthaengg/IBMdataset
/Python_codes/p02404/s863248717.py
454
3.71875
4
def print_side(W): for j in range(W): print("#",end="") print("") def print_body(W): for j in range(W): if j==0 or j==W-1: print("#",end="") else: print(".",end="") print("") while True: H,W = [int(x) for x in input().split()] if (H,W)==(0,0): break for i in range(H): if i==0 or i==H-1: print_side(W) else: print_body(W) print("")
2caccedce001df1445f18dca10875db3ab22ca44
jxhangithub/lintcode
/Dynamic_Programming/514.Paint Fence/Solution.py
721
3.625
4
class Solution: """ @param n: non-negative integer, n posts @param k: non-negative integer, k colors @return: an integer, the total number of ways """ def numWays(self, n, k): # write your code here if n == 1: return k if n == 2: return k * k if k == 1: return 0 # initialization # f[i] represents the number of ways to paint first i posts f = [0 for _ in range(n + 1)] f[0] = 0 f[1] = k f[2] = k * k # function: (k - 1) * f[i - 1] + (k - 1) * f[i - 2] for i in range(3, n + 1): f[i] = (k - 1) * f[i - 1] + (k - 1) * f[i - 2] return f[-1]
31aeee5b4d19f3e4eaf24d7ec45bb03298be0520
kkyoung28/Programming-Python-
/StudentNumber2Major.py
1,793
3.859375
4
#학번입력받아 #학과 출력하기 #예: "2320"을 입력하면, "뉴미디어웹솔루션과"를 출력 # print("학번을 입력하셈") # num=(input()) # if num[0:3] == 11 or 12 or 21 or 22 : # print("뉴미디어소프트웨어과") # elif num[0:3] == 13 or 14 or 23 or 24 : # print("뉴미디어웹솔루션과") # elif num[0:3] == 15 or 16 or 25 or 26 or 34 or 35 : # print("뉴미디어디자인과") # elif num[0:3] == 31 or 32 : # print("인터랙티브미디어과") # elif num[0:3] == 35 or 36 : # print("뉴미디어솔루션과") majors = [["뉴미디어소프트웨어과","뉴미디어웹솔루션과","뉴미디어디자인과"], ["뉴미디어소프트웨어과","뉴미디어웹솔루션과","뉴미디어디자인과"], ["인터랙티브미디어과","뉴미디어디자인과","뉴미디어솔루션과"]] #start student_number=input("학번을 입력하세야 :") grade = student_number[0] grade = int(grade) classroom = student_number[1] classroom = int(classroom) print(majors[grade-1][(classroom-1)//2]) #end # if grade == "1" or grade == "2": # print(majors12학년[classroom-1]) # elif grade == 3: # print(majors3학년[classroom-1]) # if classroom == "1" or classroom == "2": # print("뉴미디어소프트웨어과") # elif classroom == "3" or classroom == "4": # print("뉴미디어웹솔루션과") # elif classroom == "5" or classroom == "6": # print("뉴미디어디자인과") # elif grade == "3": # if classroom == "1" or classroom == "2": # print("인터랙티브미디어과") # elif classroom == "3" or classroom == "4": # print("뉴미디어디자인과") # elif classroom == "5" or classroom == "6": # print("뉴미디어솔루션과")
6730e5a8c5133133ecbc45438a846d6134ddf4a5
YuHongYu-ch/Python
/04_数据类型.py
340
3.9375
4
num1 = 18 num2 = 1.1 print(type(num1)) print(type(num2)) a = 'Hello World' print(type(a)) b = False print(type(b)) # list--列表 c = [1, 3, 5, 7] print(type(c)) # tuple--元组 d = (2, 4, 6, 8) print(type(d)) # set--集合 e = {12, 23, 33} print(type(e)) # dict--字典--键值对 f = {'name': 'TOM', 'age': 18} print(type(f)) #111
9fa4367fb3545d91cde91dbff84f3102dca276aa
abhii100/Tiffin-Service
/fooditem.py
3,571
3.546875
4
from connection import * con = connection.connection("") class fooditem: def addfooditem(self, itemname, price, description, categoryid, partnerid, availabledays): global con cursor = con.cursor() m = "" for k in availabledays: m += k + "," m = m[:-1] print(m) s = "Select * from itemtable where itemname='" + itemname + "' and categoryid='" + categoryid + "'" cursor.execute(s) result1 = cursor.fetchone() if result1 != None: return 3 else: s = "insert into itemtable values (null,'" + itemname + "','" + price + "','" + description + "','" + categoryid + "','Active','" + str( partnerid) + "','" + m + "')" # print(s) res = con.cursor() c = res.execute(s) con.commit() return c def getcategory_item(self, partnerid='', categoryid=''): global con cursor = con.cursor() if partnerid != '' and categoryid == '': s = "SELECT categoryid,categorytable.cname FROM `itemtable`,categorytable where itemtable.categoryid=categorytable.id and partnerid='" + partnerid + "' group by categoryid" elif partnerid != '' and categoryid != '': s = "select * from itemtable where categoryid='" + str(categoryid) + "' and partnerid='" + str(partnerid) + "'" print(s) cursor.execute(s) result1 = cursor.fetchall() return result1 def viewfooditem(self, id='', partnerid='', categoryid=''): global con cursor = con.cursor() if id == '' and partnerid == '': s = "Select itemtable.id,itemtable.itemname,itemtable.price,itemtable.description,categorytable.id,categorytable.cname,itemtable.availabledays from itemtable,categorytable where itemtable.categoryid=categorytable.id" elif id == '' and partnerid != '': s = "Select itemtable.id,itemtable.itemname,itemtable.price,itemtable.description,categorytable.id,categorytable.cname,itemtable.availabledays from itemtable,categorytable where itemtable.categoryid=categorytable.id and partnerid='" + str( partnerid) + "'" elif id != '' and partnerid == '': s = "Select itemtable.id,itemtable.itemname,itemtable.price,itemtable.description,categorytable.id,categorytable.cname,itemtable.availabledays from itemtable,categorytable where itemtable.categoryid=categorytable.id and itemtable.id='" + id + "'" elif id == '' and partnerid != '' and categoryid != '': s = "Select itemtable.id,itemtable.itemname,itemtable.price,itemtable.description,categorytable.id,categorytable.cname,itemtable.availabledays from itemtable,categorytable where itemtable.categoryid=categorytable.id and itemtable.categoryid='" + categoryid + "' and partnerid='" + str( partnerid) + "'" else: s = "Select itemtable.id,itemtable.itemname,itemtable.price,itemtable.description,categorytable.id,categorytable.cname,itemtable.availabledays from itemtable,categorytable where itemtable.categoryid=categorytable.id and itemtable.id='" + id + "' and partnerid='" + str( partnerid) + "'" # print(s) cursor.execute(s) result1 = cursor.fetchall() return result1 def deletefooditem(self, id): global con s = "delete from itemtable where id='" + str(id) + "'" cursor = con.cursor() res = cursor.execute(s) con.commit() return res
8eb5e245d38049d499699af36037c52433f36e23
Mekeda/CSCI-1300-Introduction-to-Programming
/Assignment 3/spencer_milbrandt_assignment3.py
1,543
4.21875
4
""" Add your required comments up here. You can get them from the assignment 2 file if you would like. """ # futval.py # A program to compute the value of an investment # carried 10 years into the future def main(): # Step 1: it isn't always a 10 year investment now, change this so it makes sense print("This program calculates the future value of a nominal investment.") principal = eval(input("Enter the initial principal: ")) # Step 2: there isn't an annual interest rate now, so change this # variable name and input string prompt to something more appropriate. npr = eval(input("Enter the nominal interest rate: ")) # Step 3: add a statement below to get the number of compound periods period = eval(input("Enter the number of compounding periods per year: ")) # Step 4: add a statement below to get the number of years for the investment year = eval(input("Enter the number of years: ")) # Step 5: the for-loop is no longer always going to execute 10 times # You need to change the expression inside range to make the # loop iterate the correct number of times range(<expr>). # Hint: You will use two variables entered by the user to do this. for i in range(year*period): # Step 6: The principal calculation needs to be updated to use the # nominal interest rate instead of annual percentage rate principal = principal * (1 + (npr/period)) # Step 6: Change this print statement so that it displays the # number of years the user enters print("The value in", year,"years is:", principal) main()
b3588c6a1af19dad845ac9ccb3b4fa6dc71ae296
christopherc1331/cs-module-project-hash-tables
/applications/word_count/word_count.py
1,139
3.84375
4
import string def word_count(s): # Your code here alpha = string.ascii_lowercase if len(s) == 0: return {} words = s.split() for i in range(len(words)): words[i] = words[i].lower() new_words = [] for i in range(len(words)): new_word = "" for x in range(len(words[i])): curr_letter = words[i][x] if curr_letter in alpha or curr_letter == "'": new_word += curr_letter if new_word != "": new_words.append(new_word) my_dict = {} for word in new_words: if word in my_dict: my_dict[word] += 1 else: my_dict[word] = 1 return my_dict if __name__ == "__main__": print(word_count("")) print(word_count("Hello")) print(word_count("Hello hello")) print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.')) print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.')) print(word_count( 'This is a test of the emergency broadcast network. This is only a test.')) print(word_count('a a\ra\na\ta \t\r\n'))
86f8df082e714a05f09512cc87050132a2c6f59d
Tenbatsu24/Project-Euler
/divisors.py
276
3.5
4
import math def f(n): divisors = set({1, n}) for i in range(2, math.ceil(math.sqrt(n)) + 1): if (n % i) == 0: divisors.add(i) divisors.add(n // i) return divisors if __name__ == '__main__': print(f(4001)) print(f(2689))
e72a77306a6e408fc92249424d0134b064891779
Kuralamudhu/python44
/python44.py
149
3.765625
4
hy=input() count=0 for i in range(len(hy)): if(hy[i].isdigit() or hy[i].isalpha() or hy[i]==(" ")): continue else: count+=1 print(count)
47891021384707f7f8dfe82c7ebb08df545774b2
Ingejp/Curso-Basico-Python
/OperadoresBasicos.py
778
3.5625
4
#Operadores aritmeticos primerNumero = 15 segundoNumero = 10 #print(primerNumero+segundoNumero) #print(primerNumero-segundoNumero) resultado=primerNumero-segundoNumero #print(resultado) resultadoMultiplicacion = primerNumero * segundoNumero #print(resultadoMultiplicacion) primerNumero = 2.5 resultadoMultiplicacion = primerNumero * segundoNumero #print(resultadoMultiplicacion) exponente=primerNumero**segundoNumero segundoNumero=2 exponente= primerNumero ** segundoNumero #print(exponente) primerNumero = 80 segundoNumero = 4 resultadoDivision = primerNumero / segundoNumero #print(resultadoDivision) resultadoDivision = primerNumero // segundoNumero #print(resultadoDivision) #% resultadoDivision = primerNumero % segundoNumero print(resultadoDivision)
ca81cef21daa74a204d2f35134a2588d1c14ed41
pratikdk/dsaprobs_s1
/stack/4_341_flatten_nested_list_iterator.py
774
3.890625
4
class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.stack = [] self.prepare_next(nestedList) def next(self): """ :rtype: int """ if not self.hasNext(): return None return self.stack.pop().getInteger() def hasNext(self): """ :rtype: bool """ while len(self.stack) > 0 and not self.stack[-1].isInteger(): self.prepare_stack(self.stack.pop().getList()) return len(self.stack) > 0 def prepare_stack(self, array): for i in range(len(array)-1, -1, -1): self.stack.push(array[i])
242375fd13e41c2e553164ceda10fa25399f9971
sanqit/credit_calculator
/Problems/snake_case/task.py
211
4.1875
4
camel_word = input() snake_word = "" for letter in camel_word: if letter.isupper(): snake_word += "_" snake_word += letter.lower() else: snake_word += letter print(snake_word)
bd7b643941ffeb53eee7f3058f592c6cffb4133c
btjd/coding-exercises
/stack_queue/walls_gates.py
1,454
3.703125
4
""" LeetCode 286 You are given a m x n 2D grid initialized with these three possible values. -1 - A wall or an obstacle. 0 - A gate. INF - Infinity means an empty room. We use the value 2^31 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. """ from collections import deque def walls_gates(rooms): INF = 2147483647 directions = set([(0,1), (0,-1), (1,0), (-1,0)]) num_rows = len(rooms) if num_rows == 0: return num_cols = len(rooms[0]) q = deque() for r in range(num_rows): for c in range(num_cols): if rooms[r][c] == 0: q.append((r,c)) while q: current_cell = q.popleft() row, col = current_cell for move in directions: r = row + move[0] c = col + move[1] if (r < 0 or c < 0 or r >= num_rows or c >= num_cols or rooms[r][c] != INF): continue else: rooms[r][c] = rooms[row][col] + 1 q.append((r,c)) def test_walls_gates(): matrix = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]] walls_gates(matrix) assert matrix == [[3, -1, 0, 1], [2, 2, 1, -1], [1, -1, 2, -1], [0, -1, 3, 4]]
25c20e9bcebb84448e2a8d56ac4ef3f55441b96f
ThamirisMrls/Computer-Science
/sqrt.py
397
3.859375
4
def sqrt(n): approx = n/2.0 better = (approx + n/approx)/2.0 while better != approx: approx = better better = (approx + n/approx)/2.0 print better return approx sqrt(25) def print_triangular_numbers(n): i=2 j=1 r=1 while n !=0 : print j, '\t', r r=r+i i +=1 j +=1 n =n-1 print_triangular_numbers(100)
149a1778627e06f361185ad2a7ca7853787e4a42
bishnoimukesh/ML
/python/greater:less.py
304
4.03125
4
print "Hello World" a = raw_input("Enter a : ") b = raw_input("Enter b : ") c = int(a) + int(b) print "Sum is : " + str(c) if(c > 100): print "Greater than 100" if(c > 200): print "Greater than 200" elif(c > 50): print "Greater than 50" else: print "Smaller than 50" print "End of Programe"
7238d63b393a764731ec02fa3d0d2b6dbf7d0638
rupali23-singh/list_question
/loop.py
219
3.796875
4
num=int(input("enter the number=")) a=num sum=0 b=len(str(num)) while a>0: digit=a%10 sum=sum+digit a=a//10 if a%num==0: print("it is harshad number=") else: print("this is not harshad number=")
cf3651e01a0fa048a4bc9237e5c8fe01c9c9cd61
SimonHettrick/2017_UK_RSE_Survey_regional_analysis
/regional_analysis.py
2,907
4
4
#!/usr/bin/env python # encoding: utf-8 import pandas as pd import numpy as np import math def import_csv_to_df(location, filename): """ Imports a csv file into a Pandas dataframe :params: an xls file and a sheetname from that file :return: a df """ return pd.read_csv(location + filename + '.csv') def export_to_csv(df, location, filename, index_write): """ Exports a df to a csv file :params: a df and a location in which to save it :return: nothing, saves a csv """ return df.to_csv(location + filename + '.csv', index=index_write) def main(): df = import_csv_to_df('./', 'cleaned_data') # Get rid of the private sector and unknown categories df = df[df['currentEmp1. What type of organisation do you work for?']!='Private company'] df = df[df['currentEmp1. What type of organisation do you work for?']!='Other'] # Combine the columns with the detail about the organisation into one column df['organisations'] = df['currentEmp2. Which university?'].fillna('') + df['currentEmp4. Which organisation do you work for?'].fillna('') # Get rid of commans in the salary df['socio4. Please select the range of your salary'] = df['socio4. Please select the range of your salary'].str.replace(',','') # Get the first part of the salary range df['first_salary'] = df['socio4. Please select the range of your salary'].str.extract('(\d+)', expand=False) # Extract the second part of the salary range, then convert it into an integer df['second_salary'] = df['socio4. Please select the range of your salary'].str.split('and', expand=False).str[1] df['second_salary'] = df['second_salary'].str.extract('(\d+)', expand=False) # Get rid of results where the person did not record their salary df.dropna(subset = ['first_salary', 'second_salary'], inplace=True) # Find the mid-point between the two salaries df['mid_salary'] = df['first_salary'].astype(int) + (df['second_salary'].astype(int) - df['first_salary'].astype(int))/2 # Get a list of the unique organisation names organisation_list = df['organisations'].unique().tolist() # Remove the blank organisation and the 'Other' organisation_list.remove('') organisation_list.remove('Other') # Sort organisation_list.sort() # Initialise results_df = pd.DataFrame(index=organisation_list) # Go through each organisation, find the average salary, then save it into a dataframe for curr_org in organisation_list: temp_df = df[df['organisations']==curr_org] average_salary = temp_df['mid_salary'].mean() results_df.loc[curr_org, 'mean salary'] = round(average_salary,0) results_df.loc[curr_org, 'number of results used to calculate mean'] = len(temp_df) export_to_csv(results_df, './', 'results', True) if __name__ == '__main__': main()
102189db63f1b65c3979c362945d9019858a173e
Meeeek/finding_reviews
/main.py
1,524
4.03125
4
# Conrad Fukuzawa # August 2020 import web_nav import time # Steps to follow # 1. find website # 2. use browser things to search # 3. figure out link from first option # Websites # 1. rotten tomatoes # 2. imdb # 3. metacritic (REDACTED) # Issues # 1. Handling bad stuff from rotten tomatoes def main(): name = input("What movie?\n") direc = '' # NOT IMPLEMENETED mov1 = {} mov2 = {} mov3 = {} # TEMP CODE ------------ mov1['rating'] = 50 mov2['rating'] = 50 mov3['rating'] = 50 # This is so that the code doesn't break when showing stats # TEMP CODE ENDS -------- # Getting movie info from Rotten Tomatoes rot = web_nav.Rotten(name, direc) mov1 = rot.get_movie() rot.close() # Getting movie info from IMDB imdb = web_nav.Imdb(name, direc) mov2 = imdb.get_movie() imdb.close() # Getting movie info from metacritic METACRITIC BLOCKS # meta = web_nav.Meta(name, direc) # mov2 = meta.get_movie() # meta.close() # SHOWING STATS --------------------------------------------- avg = (mov1['rating'] + mov2['rating']) / 2 print("############################") print(f"Rotten Tomatoes: {mov1}") print(f"IMDB: {mov2}") #print(f"Metacritic: {mov3}") print("############################") print(f"average is {avg}") if __name__=='__main__': tim1 = time.clock() main() print('---------------------------------------') print(f'time passed is {time.clock() - tim1}')
49ef05c3bdcfa2120c91c92c39f628069d5c300c
Nightwing007/Pro-135
/Pro-135.py
716
3.546875
4
import csv import pandas as pd import plotly.express as px rows = [] with open("star_with_gravity.csv","r") as f : csvR = csv.reader(f) for row in csvR : rows.append(row) header = rows[0] planetData = rows[1:] header[0] = "Index" name = [] distance = [] mass = [] radius = [] gravity = [] for planet_data in planetData: name.append(planet_data[1]) distance.append(planet_data[2]) mass.append(planet_data[3]) radius.append(planet_data[4]) gravity.append(planet_data[5]) fig = px.bar(x=name, y=mass) fig.show() fig1 = px.bar(x=name, y=radius) fig1.show() fig2 = px.bar(x=name, y=distance) fig2.show() fig3 = px.bar(x=name, y=gravity) fig3.show()
7dce1cb37b2a81208b1c9934271a30ddea303680
MrAttoAttoAtto/PythonToPseudocode
/test.py
3,309
3.84375
4
'''Customer choose components script''' '''Task 1 setup''' # var for storing the estimate number, incremented to make unique estimate_number = 0 # category list CATEGORIES = ["processor", "RAM", "storage", "case"] # 3D array for storing categories, choices, and prices COMPONENTS = [[["P5", 100], ["P7", 200]], [["32GB", 75], ["64GB", 150]], [["1TB", 50], ["2TB", 100]], [["Mini Tower", 100], ["Midi Tower", 150]]] '''Task 2 setup''' # stock, starts at 10 STOCK_LEVELS = [[10, 10], [10, 10], [10, 10], [10, 10]] '''Task 3 setup''' # total for all orders ALL_ORDER_TOTAL = 0 total = 0 estimate_number += 1 choice_list = [0, 0, 0, 0] # 4 categories so 4 times for i in range(4): valid_choice = False # while the user has not inputted a 1 or a 2 while not valid_choice: # asks the question, formatted for that part choice = input("\nWhat type of " + CATEGORIES[i] + " would you like?\n1. " + COMPONENTS[i][0][0] + "\n2. " + COMPONENTS[i][1][0] + "\nEnter choice: ") # checks it is one of the two valid inputs if choice == 1 or choice == 2: # checks the stock is above 0 - TASK 2 if STOCK_LEVELS[i][choice-1] > 0: valid_choice = True STOCK_LEVELS[i][choice-1] -= 1 else: # asks if the user wants to cancel or choose another part - TASK 2 alt_or_cancel = input("Sorry, that part is out of stock, would you like to cancel (c) or choose and alternative part (a): ") if alt_or_cancel == "a": continue elif alt_or_cancel == "c": exit() else: print("Invalid choice!") continue # adds the price to total (-1 because arrays start at 0) total += COMPONENTS[i][choice-1][1] # adds the choice to the choice list choice_list[i] = choice # applied 20% VAT total *= 1.2 print("\nEstimate number " + str(estimate_number) + "\nYou chose:") for i in range(4): # prints the formatted parts (4 times as there are 4 parts) print(COMPONENTS[i][choice_list[i]-1][0] + " for " + CATEGORIES[i]) print("Total price: £" + str(total)) # until a valid option has been chosen... - TASK 2 place_choice_make = True while place_choice_make: # asks if they want to place the order - TASK 2 place_choice = input("Would you like to place the order? [y/n] ") if place_choice == "n": exit() elif place_choice == "y": place_choice_make = False # asks the name name = input("Enter your name: ") # until a valid email has been entered... email_needed = True while email_needed: # asks the email email = input("Enter your email: ") # checks that the email has an @ in it if "@" in email: email_needed = False else: print("Invalid email") # adds this order's total to the total for the day ALL_ORDER_TOTAL += total # displays it print("Today's order total: " + str(ALL_ORDER_TOTAL)) # for every component type (4) for i in range(4): # print the heading print("\n" + CATEGORIES[i].title() + " stock: ") # for every component choice of that type (2) for c in range(2): # print the stock print(COMPONENTS[i][c][0] + " stock: " + str(STOCK_LEVELS[i][c]))
b0b0d8bffae817654af4d6e6e7db64cdee1d000b
99ashr/PyCode
/Basics_of_python/Generators/generator.py
1,462
4.53125
5
#!/usr/bin/env python3 #* -------------------------------- Generators -------------------------------- # #! Generators return traversable objects, that too one at a time. Also For loops in python use generator to implement. #! Generators save memory as they produce item one at a time thus saving lots of operations. # ! Instead of return generators use yield keyword to produce iterable items, and instead of function name they are called using __next__() function. # ---------------------------------------------------------------------------- # def gen_func(a): yield a a = [2, 3, 4, 5] b = gen_func(a) # Initializing generator and creating object named b. print("Gen Function01:", next(b)) # Calling item of object b one at a time. # ---------------------------------------------------------------------------- # def new(dict): for x, y in dict.items(): yield x, y a = {1: "Hi", 2: "Welcome"} b = new(a) print("Generator Function02 Called for once:", next(b)) print("Generator Function02 Called twice:", next(b)) # ---------------------------------------------------------------------------- # #* ---------------- For loop gives all the items of generators ---------------- # print("Generator using for loop") def ex(): n = 3 yield n n *= n yield n v = ex() for i in v: print(i) #* ------------------------------------ EOF ----------------------------------- #
7adfd5996609914456741a71d2438a6f7ec703bb
charlml1/Appreciation-Today
/tkinter_project.py
2,727
3.765625
4
from tkinter import * from tkcalendar import Calendar import sqlite3 import tkinter.messagebox root=Tk() root.geometry("800x600") root.title("Appreciation Today") title = Label(root,text="Appreciation Today\n(choose today's date)",fg = 'navy blue',width=20, font=("Fixedsys", 19,"bold")) title.pack(side='top') def exit1(): exit() def thank_win(event): window = Tk() window.geometry("600x400") window.title("Thankfulness") title = Label(window, text="Write three things you are thankful for", fg='navy blue', font=("Fixedsys", 16, "bold")) title.pack(side='top') def submit(): first1 = first_entry.get() sec2 = second_entry.get() third3 = third_entry.get() conn = sqlite3.connect("Thanks.db") with conn: cursor = conn.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS Thanks(Date TEXT,First TEXT,Second TEXT, Third TEXT)') cursor.execute('INSERT INTO Thanks(Date,First,Second,Third) VALUES(?,?,?,?)', (cal.get_date(), first1, sec2, third3)) conn.commit() tkinter.messagebox.showinfo("Nice Job!", "Your data has been saved to the file, Thanks.db") exit1() first_label = Label(window, text = '1.', font=("Fixedsys", 15, "bold"), fg='#99ffbb', bg='white') first_label.place(x=50,y=75) first_entry = Entry(window,font=("Fixedsys", 15), fg='#99ffbb', bg='white',width=47) first_entry.place(x=100,y=75) sec_label = Label(window, text = '2.', font=("Fixedsys", 15, "bold"), fg='#99ccff', bg='white') sec_label.place(x=50,y=150) second_entry = Entry(window,font=("Fixedsys", 15), fg='#99ccff', bg='white',width=47) second_entry.place(x=100,y=150) third_label = Label(window, text = '3.', font=("Fixedsys", 15, "bold"), fg='#c299ff', bg='white') third_label.place(x=50,y=225) third_entry = Entry(window,font=("Fixedsys", 15), fg='#c299ff', bg='white',width=47) third_entry.place(x=100,y=225) quit_but = Button(window,text="Quit", width=12, bg='navy blue', fg='white', font = "Fixedsys", command=exit1).place(x=150,y=300) save_but = Button(window,text="Save", width=12, bg='navy blue', fg='white', font = "Fixedsys", command=submit).place(x=350,y=300) cal = Calendar(root, font="Courier 14", locale='en_US', cursor="hand2", bordercolor='black', headersbackground='orange', normalbackground='#ffff80', weekendbackground='#ffff80',selectbackground='#cccc00') cal.pack(fill="both", expand=True) cal.bind('<<CalendarSelected>>', thank_win) root.mainloop()
d011114d9be1cad912a44371681cc60ea05dd417
juno7803/Algorithm-ANALYSIS-School-
/과제3/2016104154+이준호(퀵 소트).py
484
4.03125
4
def partition(s,low,high): pivot = s[low] j = low for i in range(low+1,high+1): if(s[i] < pivot): j+=1 s[i],s[j] = s[j],s[i] pivot = j s[low],s[pivot] = s[pivot],s[low] return pivot def quicksort(s,low,high): if(high>low): pivot = partition(s,low,high) quicksort(s,low,pivot-1) quicksort(s,pivot+1,high) s=[3,5,2,9,10,14,4,8] print("before sorting: ",s) quicksort(s,0,7) print("after sorting: ",s)
9daba5e74e2385bd00e272cff61f1d97b765d1d1
ivo-bass/SoftUni-Solutions
/programming_basics/EXAM_PREPARATION/5_series.py
634
3.75
4
budget = float(input()) count = int(input()) total_price = 0 for _ in range(count): name = input() price = float(input()) if name == "Thrones": price *= 0.5 elif name == "Lucifer": price *= 0.6 elif name == "Protector": price *= 0.7 elif name == "TotalDrama": price *= 0.8 elif name == "Area": price *= 0.9 total_price += price money_difference = budget - total_price if money_difference >= 0: print(f"You bought all the series and left with {money_difference:.2f} lv.") else: print(f"You need {abs(money_difference):.2f} lv. more to buy the series!")
d1d505e5e199e46334a4d3a872880b2fb3955e44
marketcoach/STM401
/HWK2/loopa.py
296
3.84375
4
num= 0.0 tot= 0.0 while True : sval = input( "Enter A Number or Enter end: " ) try : fval = float(sval) continue except : print("Invalid Input") if sval == 'end': break print(fval) num = num + 1 tot = tot + fval print("All Done") print(tot,num,tot/num)
052b817d697e3e533d73fc7beb77edd3347b7c71
MariusBalanean/Tema-Lab
/Tema lab/Sumapare.py
135
3.6875
4
def suma(n): s = 0 for i in range(1, n+1): s = s+i return 2*s n = int(input()) print ("Suma este", suma(n))
d63cd82d678aabe712f70d73c91d2985627c5713
SaiCharithaJosyula/100-Python-Programming-Exercises
/Day 7/35.py
396
4.28125
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 5 11:04:59 2020 @author: saura """ ''' Question 35 Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. ''' def sq_func(elements): li = [i**2 for i in range(1,21)] print(li[-5:]) sq_func(5)
dcdc6e453b153bcdaba0ae21c55986e9179f6435
razzlestorm/cs-modeule-project-hash-tables
/applications/word_count/word_count.py
547
3.828125
4
import string from collections import Counter def word_count(s): output = s for ele in output: if ele in '":;,.-+=/\|[]}{()*^&': output = output.replace(ele, "") output = output.lower() print(output) return dict(Counter(output.split())) if __name__ == "__main__": print(word_count("")) print(word_count("Hello")) print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.')) print(word_count('This is a test of the emergency broadcast network. This is only a test.'))
42d5c42f055cc3be10b565f1476da0d3a49a190c
Yuhan-Liu-Heidi/bme547tsh
/tsh.py
3,492
3.71875
4
def read_file(): """Read data from test_data.txt Args: None Returns: data (str): test data """ f = open("test_data.txt", "r") data = f.read() return data def separate_data(data): """Separate data into different patients Args: data (str): test data Returns: Name (list): name Age (list): age Gender (list): gender TSH (list): TSH results """ Data = data.split('\n') Name = [] Age = [] Gender = [] TSH = [] patient_num = 0 for i, item in enumerate(Data): if item != 'END': patient_num += 1 if i % 4 == 0: Name.append(item) elif i % 4 == 1: Age.append(item) elif i % 4 == 2: Gender.append(item) else: TSH.append(item) else: break return Name, Age, Gender, TSH def sort_name(name): """Separate data into first/last name Args: name (list): patient names Returns: FName (list): first names LName (lish): last names """ FName = [] LName = [] for item in name: n = str(item).split() FName.append(n[0]) LName.append(n[-1]) return FName, LName def sort_tsh(tsh): """Sort TSH result and make diagnosis Hyperthyroidism - any of TSH results < 1.0; Hypothyroidism - any of TSH results > 4.0; Normal thyroid function - other; Assuming no single patient will have test results both above 4.0 and below 1.0; Number of results may vary. Args: tsh (list): TSH test results Returns: TSH (list): TSH results without 'TSH' string diagnosis (str): result of diagnosis """ TSH = [] diagnosis = [] for item in tsh: n = str(item).split(',') n.remove('TSH') n.sort() TSH.append(n) diag = 'Normal thyroid function' if float(n[0]) < 1.000: diag = 'Hypothyroidism' elif float(n[-1]) > 4.000: diag = 'Hyperthyroidism' diagnosis.append(diag) return TSH, diagnosis def save_file(dic): """Save dictionary to JSON file Args: dic: Dictionary of assembled individual info Returns: None """ import json fname = dic['First name'] lname = dic['Last name'] file_name = str('{}-{}.json'.format(fname, lname)) out_file = open(file_name, "w") json.dump(dic, out_file) out_file.close() def main(): """Main function Use modules to read TSH test data from file, convert into lists of information (one information per list, in the same order). A dictionary is generated from the lists for each patient, and then saved into a JSON file. Print the progress and mark when finished. Args: None Returns: None """ data = read_file() Name, Age, Gender, TSH = separate_data(data) FName, LName = sort_name(Name) TSH, diagnosis = sort_tsh(TSH) for i in range(len(FName)): dic_patient = { "First name": FName[i], "Last name": LName[i], "Age": Age[i], "Gender": Gender[i], "Diagnosis": diagnosis[i], "TSH": TSH[i] } print("Finished {}/{}".format(i + 1, len(FName))) save_file(dic_patient) print("Task finished") if __name__ == "__main__": main()
12babd96a930da6ec4f19895de1a53e2373ada4c
abusamrah2005/Saudi-Developer-Organization
/Week4/Quiz.py
383
4.0625
4
# quiz q1 solution set = {1, 3, 5, 7, 8} newNum = {4, 8, 12} for x in newNum: set.add(x) print(set) ####### # quiz q2 solution dic = {'name': 'pigeon', 'type': 'bird', 'skin cover': 'feathers'} # print type value print(dic['type']) # change skin cover value dic['skin cover'] = 'human skin' # show all items. for x in dic: print('key-> '+str(x)+' value-> '+str(dic[x]))
75cf0d85b19b582e5f5ac1486125ba74782c9f29
AdamColton/eulerProblems
/euler65.py
322
3.5625
4
def continuousFractionSieriesForE(x): for i in xrange(x,1, -1): if i%3 == 0: yield i*2 / 3 else: yield 1 yield 2 def sumOfDigits(x): return sum([int(i) for i in str(x)]) n=1 d=0 for i in continuousFractionSieriesForE(100): n,d = i*n+d, n print sumOfDigits(n)
a1a0f0bc1f29e9567a7d7038087fb9a18f9ccd9b
ackee/katas
/codewars/narcissistic/narcissistic.py
277
3.671875
4
def narcissistic(value): digits = numtodigitslist(value) if cubedsum(digits) == value: return True return False def numtodigitslist(num): return [int(d) for d in str(num)] def cubedsum(dlist): return sum(list(map(lambda x: x**len(dlist), dlist)))
28b09cf64e448891591935325affbcd94ddcbfc2
muzaffermetehanalan/CSE321_-Introduction-to-Algorithm-Design-
/CSE321_HW2_151044038/TOHtime[151044038].py
768
3.890625
4
def TOHtime(fromP,toP,withP): height = int(input("Input size is ")) liste = [] for i in range(0,(height)): liste.append(0) movingTower(height,fromP,toP,withP,liste) for i in range(0,height): print ("Elasped time for disk " + str(i+1) + ":" + str(liste[i])) def movingTower(height,fromP, toP, withP,liste): if height >= 1: movingTower(height-1,fromP,withP,toP,liste) movingDisk(height,fromP,toP,liste) movingTower(height-1,withP,toP,fromP,liste) def movingDisk(height,fp,tp,liste): print("disk " + str(height) + ":" + fp + " to " + tp) if( (fp == "SRC" and tp == "DST") or (fp == "DST" and tp == "SRC")): value = 2*height else: value = height liste[height-1]+= value TOHtime("SRC","DST","AUX")
ee59e66533530409309f2f31b7552b6255a577fe
Marlrero/2019_Python
/chap09_tkinter/chap09_font.py
174
3.53125
4
from tkinter import * window = Tk() label = Label(window, text="Label", font="Helvetica 16") # font에서 ("Helvetica", 16)으로 해도 됨 label.pack() window.mainloop()
da2e24a0578600c2136eb9e1daccfb22c9fea003
ofreshy/interviews
/questions/bst_old.py
2,154
4.03125
4
# TODO class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None def __str__(self): print self.value class Tree(object): def __init__(self): self.root = None def depth_first(self): pass def breadth_first(self): pass def get(self, value): def _search(node): if node is None: return False elif node.value == value: return True elif value < node.value: return _search(node.left) else: return _search(node.right) return _search(self.root) def get2(self, value): n = self.root while n is not None: if n.value == value: return True elif value < n.value: n = n.left elif value > n.value: n = n.right return False def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert(self.root, value) def _insert(self, parent, value): n_value = parent.value if value < n_value: if parent.left is None: parent.left = Node(value) else: self._insert(parent.left, value) else: if parent.right is None: parent.right = Node(value) else: self._insert(parent.right, value) def put(self, value): self.root = self._put(self.root, value) def _put(self, node, value): if node is None: return Node(value) if value < node.value: node.left = self._put(node.left, value) else: node.right = self._put(node.right, value) return node def __repr__(self): node = self.root t = Tree() t.insert(5) t.insert(10) t.insert(7) print t.get(5) print t.get(10) print t.get(19) print t.get2(5) print t.get2(10) print t.get2(19) t.put(15) t.put(110) t.put(17) print t.get(15) print t.get(110) print t.get(117)
e0c3fb3491d4c2e6d0cb09636c46a5dd2ebffd03
drewconway/networkx
/examples/graph/erdos_renyi.py
864
3.890625
4
# -*- coding: utf-8 -*- #!/usr/bin/env python """ Create an G{n,m} random graph with n nodes and m edges and report some properties. This graph is sometimes called the Erdős-Rényi graph but is different from G{n,p} or binomial_graph which is also sometimes called the Erdős-Rényi graph. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __credits__ = """""" # Copyright (C) 2004-2006 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * import sys n=10 # 10 nodes m=20 # 20 edges G=gnm_random_graph(n,m) # some properties print("node degree clustering") for v in nodes(G): print('%s %d %f' % (v,degree(G,v),clustering(G,v))) # print the adjacency list to terminal try: write_adjlist(G,sys.stdout) except TypeError: # Python 3.x write_adjlist(G,sys.stdout.buffer)
a2bb557c8d7985085ac6aad337770c8c934a8c6b
JASONews/Coding-Day-by-Day
/Distinct Subsequences 10.8/Distinct Subsequences.py
1,299
3.765625
4
""" Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). Here is an example: S = "rabbbit", T = "rabbit" """ class Solution(object): def numDistinct(self, s, t): """ :type s: str :type t: str :rtype: int """ n = len(s) m = len(t) if n is 0: return 0 if m is 0: return 1 if m > n: return 0 arr = [[0 for i in range(0, n)] for j in range(0, m)] if s[0] == t[0]: arr[0][0] = 1 for j in range(1, n): if s[j] == t[0]: arr[0][j] = arr[0][j-1] + 1 else: arr[0][j] = arr[0][j-1] for i in range(1, m): for j in range(1, n): if s[j] == t[i]: arr[i][j] = arr[i-1][j-1]+arr[i][j-1] else: arr[i][j] = arr[i][j-1] return arr[-1][-1]
fd471362179a2a1a226bc1abc921ab00b25add03
denregr/test
/main.py
296
3.640625
4
#1_в_ожидании нового года def newYearTimeCount(m,n): n = 1440 - (n + m * 60) m, n = n // 60, n % 60 return m, n # Куб со спицами def cubes(): pass #отгадай слово def world(): pass print(newYearTimeCount(int(input()),int(input())))
48028d48c2aa8fc92ba135880d690141922438fd
vijgan/HackerRank
/Search/ice_cream_palor.py
1,118
4.0625
4
#!/usr/bin/python import sys from itertools import combinations ''' In this function, 1. We take all the input 2. Create tuple combination using combinations() functions from itertools from the list 3. If the sum of the tuple elements equals the actual amount, we will get the index of those 2 items 4. For getting the index, get the first index using list_name.index(value) 5. For getting the second index, use index() functions optional paramater of start index e.g: list_name.index(value,last_index+1) ''' def icecream_parlour(amount,flavours,element): flavour_combinations=combinations(element,2) for flavour in flavour_combinations: if flavour[0]+flavour[1]==amount: first_index=element.index(flavour[0]) second_index=element.index(flavour[1],first_index+1) print (first_index+1,second_index+1,end=' ') print(end='\n') test=int(input()) for _ in range(0,test): amount=int(input()) flavours=int(input()) elements=input().strip().split() elements=list(map(int,elements)) icecream_parlour(amount,flavours,elements)
1441f1cee646f51901f0c23abcd9f605ca4c4362
fatezy/Algorithm
/leetCode/top50/035searchInsert.py
810
3.90625
4
# 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 # # 你可以假设数组中无重复元素。 # # 示例 1: # # 输入: [1,3,5,6], 5 # 输出: 2 class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if not nums: return 0 ind = -1 for i,val in enumerate(nums): if nums[i] == target: return i if nums[i] < target: ind = i if nums[i] > target: break return ind+1 if __name__ == '__main__': print(Solution().searchInsert([1,3,5,6], 0))
6f610b505cc9eecaf09d2177f857c6da449816f8
maschwanden/boxsimu
/boxsimu/descriptors.py
6,797
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 24 2017 at 11:08UTC @author: Mathias Aschwanden (mathias.aschwanden@gmail.com) Descriptors used in boxsimu in order to facilitate the handling of different attributes (e.g. immutable attributes, or attributes that must have a certain pint-dimensionality). """ import pint import collections from attrdict import AttrDict from . import validation as bs_validation from keyword import iskeyword from . import condition as bs_condition from . import errors as bs_errors from . import function as bs_function class PintQuantityDescriptor: """Check correct pint-dimensionality of attribute. Raise an exception if either a newly assigned value to the attribute under consideration is not a pint.Quantity or if the dimensionality of the pint.Quantity is not correct. """ def __init__(self, name, units, default=None): self.name = '_' + name self.units = units self.default = default def __get__(self, instance, instance_type): return getattr(instance, self.name, self.default) def __set__(self, instance, value): if instance is None: return self if value is None: return bs_validation.raise_if_not(value, self.units) setattr(instance, self.name, value.to_base_units()) class QuantifiedPintQuantityDescriptor(PintQuantityDescriptor): """Check correct pint-dimensionality of attribute. If the attribute is set correctly the instance is marked as quantified (e.g. the Fluid or Variable instance is then marked as quantified). """ def __set__(self, instance, value): super().__set__(instance, value) instance._quantified = True class ImmutableDescriptor: """Check that an attribute is immutable. Raise an exception if an attribute is assigned a value for the second time. """ def __init__(self, name): self.name = '_' + name self.name_raw = name def __get__(self, instance, instance_type): return getattr(instance, self.name, None) def __set__(self, instance, value): if hasattr(instance, self.name): raise AttributeError( 'Cannot set immutable attribute "{}".'.format(self.name_raw)) setattr(instance, self.name, value) class ImmutableIdentifierDescriptor(ImmutableDescriptor): """Check that the name is immutable and a valid identifier. Raise an exception if the """ def __set__(self, instance, value): if not value.isidentifier() or iskeyword(value): raise ValueError('Name must be a valid python expression!') super().__set__(instance, value) class BaseDictDescriptor: """Check if keys and values are instances of certain classes. Descriptor that assures that an attribute is a dict with key-value pairs of certain classes. E.g. key-value pairs of an integer as a key and an instance of Box as value. Args: name (str): name of the attribute of the parents class. key_classes (list of classes): Classes that are allowed as key instances. value_class (list of classes): Classes that are allowed as value instances. """ dict_class = dict def __init__(self, name, key_classes, value_classes): self.name = '_' + name self.name_raw = name if not isinstance(key_classes, list): raise bs_errors.NotInstanceOfError('key_classes', 'list') self.key_classes = key_classes if not isinstance(value_classes, list): raise bs_errors.NotInstanceOfError('value_classes', 'list') self.value_classes = value_classes def __get__(self, instance, instance_type): return getattr(instance, self.name) def __set__(self, instance, value): if instance is None: return self if value is None: return value = self._check_key_value_types(value) setattr(instance, self.name, value) def _check_key_value_types(self, value): if not isinstance(value, self.dict_class): raise bs_errors.NotInstanceOfError(self.name_raw, self.dict_class) for k, v in value.items(): key_isinstance_list = [isinstance(k, i) for i in self.key_classes] if not any(key_isinstance_list): raise bs_errors.DictKeyNotInstanceOfError( self.name_raw, self.key_classes) value_isinstance_list = [isinstance(v, i) for i in self.value_classes] if not any(value_isinstance_list): raise bs_errors.DictValueNotInstanceOfError( self.name_raw, self.value_classes) return value class AttrDictDescriptor(BaseDictDescriptor): dict_class = AttrDict class PintQuantityValueDictDescriptor(BaseDictDescriptor): """Check if keys have the correct type and values are pint quantites. Attribute must be a dict with instances of one type of {key_classes} and pint.Quantities with dimensionality equal to these of units as values. """ def __init__(self, name, key_classes, *units): super().__init__(name, key_classes, value_classes=[ pint.quantity._Quantity]) self.units = units def _check_key_value_types(self, value): value = super()._check_key_value_types(value) for k, v in value.items(): bs_validation.raise_if_not(v, *self.units) return value class PintQuantityExpValueDictDescriptor(BaseDictDescriptor): """Check if keys have the correct type and values are pint quantites. Attribute must be a dict with instances of one type of {key_classes} and pint.Quantities with dimensionality equal to these of units or callables that return pint.Quantites with dimensionality equal to these of units as values. """ def __init__(self, name, key_classes, *units): super().__init__(name, key_classes, value_classes=[ pint.quantity._Quantity, collections.Callable]) self.units = units def _check_key_value_types(self, value): value = super()._check_key_value_types(value) for k, v in value.items(): value[k] = bs_function.UserFunction(v, *self.units) return value class ConditionUserFunctionDescriptor(BaseDictDescriptor): dict_class = bs_condition.Condition def __init__(self, name, key_classes): super().__init__(name, key_classes, value_classes=[ pint.quantity._Quantity, collections.Callable]) def _check_key_value_types(self, value): value = super()._check_key_value_types(value) for k, v in value.items(): value[k] = bs_function.UserFunction(v, *self.units) return value
8ccc844d3601ea9c67a37a530ba708a88941170f
arsamigullin/problem_solving_python
/leet/Stack/439_Ternary_Expression_Parser.py
587
3.703125
4
class Solution: # # since the given expression is valid and only consists of digits 0-9, ?, :, T and F (T and F represent True and False respectively). # we can use expression def parseTernary(self, expression): def dfs(it): first, second = next(it), next(it, None) if not second or second == ':': return first else: T, F = dfs(it), dfs(it) return T if first == 'T' else F return dfs(iter(expression)) if __name__ == '__main__': s = Solution() s.parseTernary("F?1:T?4:5")
3228fb676fe1a957a8c9f1b07614966c42cd22b1
EmmetDuggan/MIS41110-Project
/project_exceptions.py
1,415
3.8125
4
class DataUnavailableException(Exception): """Custom exception class. Raised if a particular company's records do not go back as far as the user wants, but the records of the first company entered by the user does.""" ticker = "" date = "" def __init__(self, ticker, date): self.message = "Data unavailable for \"" + ticker + "\" for the date: " + date self.ticker = ticker self.date = date super().__init__(self.message) class MultiDataUnavailableException(Exception): """Custom exception class. Bundles several DataUnavailableExceptions into a single exception which is raised when the records of multiple companies do not go back as far as the user wants.""" exceptions = [] tickers = [] def __init__(self): self.message = "Multiple companies have limited data." super().__init__(self.message) def add_exception(self, exception, ticker): self.exceptions.append(exception) self.tickers.append(ticker) class InvalidTickerException(Exception): """Custom exception class. Raised if the entered ticker is not found.""" ticker = "" def __init__(self, ticker): self.message = "The ticker " + ticker + " was not found in the database.\nPlease re-enter the company tickers." self.ticker = ticker super().__init__(self.message)
475e6242798013ca0ef6981c6c5f381afe9bcf10
362515241010/TueyDH
/Home-Work-20-9-62_7.py
1,388
3.984375
4
#!/usr/bin/env python # coding: utf-8 # In[2]: max = 0 #input รับตัวเลขจำนวนเต็มเข้ามาทางแป้นพิมพ์ #Define of variable กำหนดให้ค่า max เริ่มต้นที่ 0 และกำหนดให้ตัวเลขที่รับเข้าเป็น int หรือจำนวนเต็ม number = int(input("Enter number :")) #process นำตัวเลขที่ได้มา เข้าในเงื่อนไข while ถ้าตัวเลขที่รับเข้ามามีค่ามากกว่า 0 ให้รับเข้ามาเรื่อยๆ แต่ถ้าตัวเลขน้อยกว่า 0 ให้หยุดรับตัวเลข while number > 0: #process แล้วมาเข้าเงื่อนไข if ต่อเพื่อหาตัวเลขที่มีค่ามากที่สุด if number > max: max = number number = int(input("Enter number :")) #output เมื่อทำขั้นตอน process เสร็จแล้วให้แสดงผล output ออกทางหน้าจอด้วยคำสั่ง print print("จำนวนที่มีค่ามากที่สุด :", max) # In[ ]:
63b51d88f42e902508b279b77c9b43c23f09b3c0
OrlandoBitencourt/hoteis
/main.py
4,425
3.671875
4
""" Criar um sistema de busca de hotéis O usuário colocará o nome de uma cidade e o sistema deverá listar os 10 melhores hotéis na região do estado. Ex: Blumenau -> lista os 10 melhores hotéis do Nordeste de SC Regras: 1. Cada estado será constituído por 5 regiões, sendo elas: Nordeste, Noroeste, Sudeste, Sudoeste e Centro. 2. Os hotéis serão classificados de melhor a pior com bases em estrelas, sendo 1 estrela o pior, e 5 estrelas o melhor. 3. O usuário poderá também filtrar os resultados (Ex: caso ele ative o filtro de ser necessária uma academia, devem ser listados novos 10 hotéis com academia). 4. Cada hotel deve conter as seguintes informações no DataBase: Nome, anos na ativa, Classificação (estrelas), Preço do quarto por noite, Tem academia, Tem piscina, Inclui (café da manhã, almoço e jantar) na tarifa, cidade, estado, vagas disponíveis. 5. Na listagem dos hotéis, devem aparecer todas informações sobre cada hotel. 6. Caso o hotel não tenha vagas disponíveis, ele nem deve aparecer na listagem. """ from banco_de_dados import BancoDeDados bd = BancoDeDados() bd.conectar_db() def listar_valores(cabecalho_consulta, consulta): tamanho_tupla = 24 lista = [] for tupla in cabecalho_consulta: lista.append(tupla[0].capitalize() + " " * (tamanho_tupla - len(str(tupla[0])))) print("".join(lista)) for tupla in consulta: lista = [] for item in tupla: lista.append(str(item) + " " * (tamanho_tupla - len(str(item)))) print("".join(lista)) while True: id_regiao = "" academia_digitada = "" piscina_digitada = "" all_inclusive_digitado = "" cidade_digitada = str(input("digite o nome da cidade: ")) sql = f"select id_regioes from cidades where nome_cidades like '%{cidade_digitada}%' limit 1" colunas, id_regiao = bd.executar_select(sql) if id_regiao: academia_digitada = input("deseja listar apenas hoteis que tenham academia? Digite S para confirmar: ") piscina_digitada = input("deseja listar apenas hoteis que tenham piscina? Digite S para confirmar: ") all_inclusive_digitado = input("deseja listar apenas hoteis que tenham servico de all inclusive " "(cafe/almoço/jantar)? Digite S para confirmar: ") query = "select " \ "h.nome_hoteis, " \ "h.classificacao_hoteis, " \ "case when h.piscina_hoteis = 0 then 'Não possui piscina' " \ "else 'Possui piscina' " \ "end as piscina, " \ "case when h.academia_hoteis = 0 then 'Não possui academia' " \ "else 'Possui academia proria' " \ "end as academia, " \ "case when all_inclusive_hoteis = 0 then 'Não oferece' " \ "else 'café/almoço/jantar' " \ "end as all_inclusive, " \ "q.descricao_quartos, " \ "q.preco_quartos, " \ "c.nome_cidades, " \ "r.nome_regioes, " \ "e.nome_estados, " \ "e.uf_estados " \ "from hoteis h " \ "inner join quartos q on (h.id_hoteis = q.id_hoteis) " \ "inner join cidades c on (h.id_cidades = c.id_cidades) " \ "inner join regioes r on (c.id_regioes = r.id_regioes) " \ "inner join estados e on (r.id_estados = e.id_estados) " \ "where 1=1 " \ "and q.disponibilidade <> '0' " if academia_digitada.lower() == 's': query = query + "and h.academia_hoteis = 1 " if piscina_digitada.lower() == 's': query = query + "and h.piscina_hoteis = 1 " if all_inclusive_digitado.lower() == 's': query = query + "and h.all_inclusive_hoteis = 1 " sql = query + f"and r.id_regioes = {id_regiao[0][0]} " \ "order by 2 desc, 1 " \ "limit 10" cabecalho_consulta, consulta = bd.executar_select(sql) listar_valores(cabecalho_consulta, consulta) else: print("Digite uma cidade válida.")
250d3e8d59457d7b38a78dc4b64af94d407b57aa
rajya-talatam/factorial-and-lcm-of-two-numbers
/factorial and lcm of two numbers.py
652
4.28125
4
#Factorial of number import math def fact(num): if num==1: return 1 else: return (num * (math.factorial(num - 1))) num=int(input("inter the value:")) a=fact(num) print("The factorial of {b} is {c}".format(b=num,c=a)) #LCM for two numbers def lcm(a,b): #function if a>b: #checking greater=a else: greater=b while(True):#while the condition is true then it excicuit if greater%a==0 and greater%b==0: lcm = greater break greater *= 2 return lcm Val=lcm(a=int(input("a:")), b=int(input("b:"))) print("Lcm of two numbers is:",Val)
08e71694bd2f54c8b3131912cab43b11156d41ae
keithkay/python
/python_crash_course/modulo.py
128
3.875
4
num_1 = input("First number: ") num_2 = input("Second number: ") result = int(num_1) % int(num_2) print("The result is", result)
70733e74e8bb0461821d2a50f1e05940b5246826
aj3sh/nepali
/nepali/number/_nepalinumber.py
19,561
3.859375
4
""" Contains the class for the nepalinumber feature """ from typing import Any, Tuple, Type, Union from .utils import NP_NUMBERS, NP_NUMBERS_SET, english_to_nepali class nepalinumber: """ Represents the nepali(devanagari) numbers and the features related to arithmetic operations on them """ def __init__(self, value: Any) -> None: """ Constructor/Initializer """ self.__value = self.__parse(value) def get_parse_exception( self, obj: object, ex_class: Type[Exception] = ValueError ) -> Exception: """ Returns the exception object to be raised when the parse is failed. The methods also sets a proper message to the exception class. :param obj: Object that is failed during the parse :type obj: object :param ex_class: Exception class type to be returned, defaults to ValueError :type ex_class: Type[Exception], optional :return: Exception object to be raised :rtype: Exception """ return ex_class( f"could not convert {obj.__class__.__name__} to {self.__class__.__name__}: '{obj}'" ) def __parse(self, value: Any) -> Union[int, float]: """ Parses nepali number input into a valid value. Eg: >>> self.__parse("१२") 12 >>> self.__parse("१२.३") 12.3 >>> self.__parse(1) 1 >>> self.__parse("invalid") ValueError: could not convert str to nepalinumber: 'invalid' :param value: Value to be parsed. :return: returns value int or float :raises ValueError: If the value is invalid :raises TypeError: If the value object can't be parsed """ if isinstance(value, int): return int(value) elif isinstance(value, float): return float(value) elif isinstance(value, str): return self.__parse_str(value) return self.__parse_object(value) def __parse_str(self, value: str) -> Union[int, float]: """ Parses str object into int and float. This is a low level implementation. :raises ValueError: If the value is invalid """ result: float = 0 sign = 1 decimal_found = False decimal_place: float = 1 i = 0 # for negative sign if value[0] == "-": sign = -1 i = 1 while i < len(value): # decimal number found if value[i] == ".": if decimal_found: # decimal was already found raise self.get_parse_exception(value) from None decimal_found = True i += 1 continue digit = ord(value[i]) - ord("0") if digit < 0 or digit > 9: # checking nepali character if value[i] not in NP_NUMBERS_SET: raise self.get_parse_exception(value) from None digit = NP_NUMBERS.index(value[i]) if decimal_found: decimal_place /= 10 result += digit * decimal_place else: result = result * 10 + digit i += 1 return sign * result def __parse_object(self, obj: Any) -> Union[int, float]: """ Parses object using __int__, __float__, and __str__. :raises TypeError: If the value object can't be parsed """ try: if hasattr(obj, "__float__"): return float(obj) elif hasattr(obj, "__int__"): return int(obj) return self.__parse_str(str(obj)) except (ValueError, TypeError): # object conversion must raise TypeError if fails raise self.get_parse_exception(obj, ex_class=TypeError) from None def __convert_or_return(self, obj) -> Union["nepalinumber", object]: """ Will try to parse the given object and convert to nepalinumber else will return the same object :param obj: The object to convert :returns: Either a nepalinumber or the same object unchanged """ try: return nepalinumber(obj) except (TypeError, ValueError): return obj def __str__(self) -> str: """ Called when the object is called with functions like print or logger.debug() """ return str(self.__value) def __repr__(self) -> str: return str(self.__value) def __int__(self) -> int: """ Called when the object is typecasted into integer """ return int(self.__value) def __float__(self) -> float: """ Called when the object is typecasted into float """ return float(self.__value) def __add(self, other) -> Union[int, float]: """ Adds the value in the object with the passed object :param other: The other number/object to be added to the object :raises TypeError: Raised when unsupported data types are added to the nepalinumber object :return: A new nepalinumber object with the added values """ if isinstance(other, nepalinumber): return self.__value + other.value return self.__value + other def __mul(self, other) -> Union[int, float]: """ Multiplies the value in the object with the passed object :param other: The other number/object to be added to the object :raises TypeError: Raised when unsupported data types are multiplied to the nepalinumber object :return: A new nepalinumber object with the multiplied values """ if isinstance(other, nepalinumber): return self.__value * other.value return self.__value * other def __eq__(self, other) -> bool: """ Checks if nepalinumber is equal to another object :param other: The other number/object which is to be checked for equality against nepalinumber :return: True if equal else False """ if isinstance(other, nepalinumber): return self.__value == other.value return self.__value == other def __ne__(self, other) -> bool: """ Checks if nepalinumber is not equal to another object :param other: The other number/object which is to be checked for equality against nepalinumber :return: True if not equal else False """ if isinstance(other, nepalinumber): return self.__value != other.value return self.__value != other def __neg__(self) -> "nepalinumber": """ Returns the negative value of the nepalinumber value """ return nepalinumber((-1) * self.__value) def __add__(self, other) -> Union["nepalinumber", object]: """ Called when the addition operator + is used after the nepalinumber object :param other: The other number/object that is to be added to the value onto the nepalinumber object :raises TypeError: Raised when unsupported data types are added to the nepalinumber object :return: Returns the added value as a nepalinumber object """ try: return self.__convert_or_return(self.__add(other)) except TypeError: return NotImplemented def __radd__(self, other) -> Union["nepalinumber", object]: """ Called when the addition operator + is used before the nepalinumber object :param other: The other number/object that is to be added to the value onto the nepalinumber object :raises TypeError: Raised when nepalinumber object is added to unsupported data types :return: Returns the added value as a nepalinumber object """ try: return self.__convert_or_return(self.__add(other)) except TypeError: return NotImplemented def __sub__(self, other) -> Union["nepalinumber", object]: """ Called when the subtraction operator - is used after the nepalinumber object :param other: The other number/object that is to be subtracted from the value in the nepalinumber object :raises TypeError: Raised when unsupported data types are subtracted from nepalinumber object :return: Returns the subtracted number as a nepalinumber object """ try: if isinstance(other, nepalinumber): return self.__convert_or_return(self.__value - other.value) return self.__convert_or_return(self.__value - other) except TypeError: return NotImplemented def __rsub__(self, other) -> Union["nepalinumber", object]: """ Called when the subtraction operator - is used before the nepalinumber object :param other: The other number/object that is to get subtracted by the value in the nepalinumber object :raises TypeError: Raised when nepalinumber object is subtracted from unsupported data types :return: Returns the subtracted number as a nepalinumber object """ try: if isinstance(other, nepalinumber): return self.__convert_or_return(other.value - self.__value) return self.__convert_or_return(other - self.__value) except TypeError: return NotImplemented def __mul__(self, other) -> Union["nepalinumber", object]: """ Called when the multiplication operator * is used after the nepalinumber object :param other: The other number/object that is to be multiplied to the value onto the nepalinumber object :raises TypeError: Raised when unsupported data types are multiplied to the nepalinumber object :return: Returns the multiplied value as a nepalinumber object """ try: if isinstance(other, str): return self.__value * other # type: ignore return self.__convert_or_return(self.__mul(other)) except TypeError: return NotImplemented def __rmul__(self, other) -> Union["nepalinumber", object]: """ Called when the multiplication operator * is used before the nepalinumber object :param other: The other number/object that is to be multiplied to the value onto the nepalinumber object :raises TypeError: Raised when nepalinumber object is multiplied to unsupported data types :return: Returns the multiplied value as a nepalinumber object """ try: if isinstance(other, str): return other * self.__value # type: ignore return self.__convert_or_return(self.__mul(other)) except TypeError: return NotImplemented def __truediv__(self, other) -> Union["nepalinumber", object]: """ Called when the division operator / is used after the nepalinumber object :param other: The other number/object that is to divide the value in the nepalinumber object :raises TypeError: Raised when unsupported data types are used to divide nepalinumber object :return: Returns the quotient number as a nepalinumber object """ try: if isinstance(other, nepalinumber): return self.__convert_or_return(self.__value / other.value) return self.__convert_or_return(self.__value / other) except TypeError: return NotImplemented def __rtruediv__(self, other) -> Union["nepalinumber", object]: """ Called when the division operator / is used before the nepalinumber object :param other: The other number/object that is to get divided by the value in the nepalinumber object :raises TypeError: Raised when nepalinumber object is used to divide unsupported data types :return: Returns the quotient number as a nepalinumber object """ try: if isinstance(other, nepalinumber): return self.__convert_or_return(other.value / self.__value) return self.__convert_or_return(other / self.__value) except TypeError: return NotImplemented def __floordiv__(self, other) -> Union["nepalinumber", object]: """ Called when the floor/integer division operator // is used after the nepalinumber object :param other: The other number/object that is to divide the value in the nepalinumber object :raises TypeError: Raised when unsupported data types are used to divide nepalinumber object :return: Returns the quotient number as a nepalinumber object """ try: if isinstance(other, nepalinumber): return self.__convert_or_return(self.__value // other.value) return self.__convert_or_return(self.__value // other) except TypeError: return NotImplemented def __rfloordiv__(self, other) -> Union["nepalinumber", object]: """ Called when the floor/integer division operator // is used before the nepalinumber object :param other: The other number/object that is to get divided by the value in the nepalinumber object :raises TypeError: Raised when nepalinumber object is used to divide unsupported data types :return: Returns the quotient number as a nepalinumber object """ try: if isinstance(other, nepalinumber): return self.__convert_or_return(other.value // self.__value) return self.__convert_or_return(other // self.__value) except TypeError: return NotImplemented def __mod__(self, other) -> Union["nepalinumber", object]: """ Called when the modulo operator % is used after the nepalinumber object :param other: The other number/object that is to be perform modulo division from the value in the nepalinumber object :raises TypeError: Raised when unsupported data types are modulo divided from nepalinumber object :return: Returns the remainder number as a nepalinumber object """ try: if isinstance(other, nepalinumber): return self.__convert_or_return(self.__value % other.value) return self.__convert_or_return(self.__value % other) except TypeError: return NotImplemented def __rmod__(self, other) -> Union["nepalinumber", object]: """ Called when the modulo operator % is used before the nepalinumber object :param other: The other number/object that is to get modulo divided by the value in the nepalinumber object :raises TypeError: Raised when nepalinumber object is used modulo divide unsupported data types :return: Returns the remainder number as a nepalinumber object """ try: if isinstance(other, nepalinumber): return self.__convert_or_return(other.value % self.__value) return self.__convert_or_return(other % self.__value) except TypeError: return NotImplemented def __divmod__( self, other ) -> Tuple[Union["nepalinumber", object], Union["nepalinumber", object]]: """ Called when the built-in function divmod() is used with nepalinumber as the dividend and other as divisor :param other: The other number/object that is to be divisor for the value in the nepalinumber object :raises TypeError: Raised when unsupported data types are used as divisor for nepalinumber object :return: Returns a tuple of quotient and remainder """ try: if isinstance(other, nepalinumber): quotient, remainder = divmod(self.__value, other.value) quotient, remainder = divmod(self.__value, other) return self.__convert_or_return(quotient), self.__convert_or_return( remainder ) except TypeError: return NotImplemented def __rdivmod__( self, other ) -> Tuple[Union["nepalinumber", object], Union["nepalinumber", object]]: """ Called when the built-in function divmod() is used with nepalinumber as the divisor and other as dividend :param other: The other number/object that is to be dividend for the value in the nepalinumber object :raises TypeError: Raised when unsupported data types are used as dividend for nepalinumber object :return: Returns a tuple of quotient and remainder """ try: if isinstance(other, nepalinumber): quotient, remainder = divmod(other.value, self.__value) quotient, remainder = divmod(other, self.__value) return self.__convert_or_return(quotient), self.__convert_or_return( remainder ) except TypeError: return NotImplemented def __pow__(self, other) -> Union["nepalinumber", object]: """ Called when the power operator ** is used after the nepalinumber object :param other: The other number/object that is to be powered to the value onto the nepalinumber object :raises TypeError: Raised when unsupported data types are powered to the nepalinumber object :return: Returns the powered by value as a nepalinumber object """ try: if isinstance(other, nepalinumber): return self.__convert_or_return(self.__value**other.value) return self.__convert_or_return(self.__value**other) except TypeError: return NotImplemented def __rpow__(self, other) -> Union["nepalinumber", object]: """ Called when the power operator ** is used before the nepalinumber object :param other: The other number/object that is to be powered by the value onto the nepalinumber object :raises TypeError: Raised when unsupported data types are powered by the nepalinumber object :return: Returns the powered by value as a nepalinumber object """ try: if isinstance(other, nepalinumber): return self.__convert_or_return(other.value**self.__value) return self.__convert_or_return(other**self.__value) except TypeError: return NotImplemented def str_ne(self) -> str: """ Returns nepali (devanagari) format for the number :return: Stringified Nepali number """ if not hasattr(self, "__str_ne"): self.__str_ne = english_to_nepali(self.__value) return self.__str_ne @property def value(self): return self.__value
e1a5b98f180d37d976b8887df4b5a6d1e735b277
OvidiuSirb/hangman_game
/ui/console.py
1,845
3.625
4
class Ui: def __init__(self,controller): self._controller = controller @staticmethod def PrintMenu(): string = "1-Add a sentence\n" string += "2-Start the game\n" string += "0-Exit" print(string) def MainMenu(self): while True: self.PrintMenu() cmd = input("Please insert command:") if cmd == '1': sentence = input("Please enter sentence:") self._controller.store(sentence) elif cmd == '0': return False elif cmd == '2': (hang,sentence) = self._controller.HangSentence() for x in hang: print(x) h = 0 while h < 7: if h == 0: print("H\n") if h == 1: print("HA\n") if h == 2: print("HAN\n") if h == 3: print("HANG\n") if h == 4: print("HANGM\n") if h == 5: print("HANGMA\n") if h == 6: print("HANGMAN\n") break letter = input("Please enter a letter: ") hangprop = self._controller.ContinueSentence(sentence,hang,letter) if hangprop == 0: h+=1 else: hang = hangprop for t in hangprop: print(t) ver = self._controller.Verify(hangprop) if (ver == 0): print("YOU WON") break
819aad4824c545cc47370edeab058e3117da4312
vmatos/tiva-c-projects
/examples_tm4c129/freertos_lwip_tcp_client/scripts/make_server.py
515
3.5625
4
#!/usr/bin/env python import socket #create an INET, STREAMing socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #bind the socket to a public host, # and a well-known port serversocket.bind(('', 8080)) #become a server socket serversocket.listen(5) while 1: #accept connections from outside (clientsocket, address) = serversocket.accept() print "socket ", clientsocket print "Ip", address print "Got: ", clientsocket.recv(1024) clientsocket.send("Who's there?")
253ac71bcf46f28f5f9f28faf162b1e59b93f2b3
tanuj208/CipherForces
/encryption_codes/custom_algo/encrypt.py
1,267
3.859375
4
import json import sys import generate_key def take_input(): """Takes all necessary inputs for encryption.""" plaintext = sys.argv[1] return plaintext def get_keys(): with open('keys.json', 'r') as f: keys = json.load(f) return keys def vigenere_encryption(plaintext, key): """Encrypts the message using vigenere cipher.""" ciphertext = [] for i in range(len(key)): p = ord(plaintext[i]) k = ord(key[i]) min_val = ord('a') p -= min_val k -= min_val p += k p %= 26 p += min_val ciphertext.append(chr(p)) return ''.join(ciphertext) def decrypt_key(encrypted_key, alphabet_map): """Decrypts the key using mono-alphabetic substitution cipher.""" reverse_map = {} for key in alphabet_map: reverse_map[alphabet_map[key]] = key key = [] for char in encrypted_key: key.append(reverse_map[char]) return ''.join(key) def encrypt_message(plaintext): """Encrypts the plaintext.""" plaintext_len = len(plaintext) keys = get_keys() vigenere_key = decrypt_key(keys['encrypted_key'], keys['map']) ciphertext = vigenere_encryption(plaintext, vigenere_key) return ciphertext if __name__ == '__main__': plaintext = take_input() ciphertext = encrypt_message(plaintext) print("Encrypted message is {}".format(repr(ciphertext)))
c0094c123093823e55bb10740df6fd76327a3f22
MrTejpalSingh/Problem-Solving
/Small Practise Programs/OOP/1_Premium_Vehicle.py
1,468
3.609375
4
class Vehicle: def __init__(self): pass def set_vehicle_type(self,type): self.__vehicle_type = type def set_vehicle_premium_amount(self,amount): self.__vehicle_premium_amount = amount def set_vehicle_id(self,id): self.__vehicle_id = id def set_vehicle_cost(self,cost): self.__vehicle_cost = cost def get_vehicle_type(self): return self.__vehicle_type def get_vehicle_id(self): return self.__vehicle_id def get_vehicle_cost(self): return self.__vehicle_cost def get_vehicle_premium_amount(self): return self.__vehicle_premium_amount def calculate_premium(self): if self.__vehicle_type == "Two Wheeler": self.set_vehicle_premium_amount((self.get_vehicle_cost()*2)/100) elif self.__vehicle_cost == "Four Wheeler": self.set_vehicle_premium_amount((self.get_vehicle_cost()*6)/100) def show_details(self): print( 'Vehicle Type:'+ self.get_vehicle_type()+' ,Vehicle id:'+ str(self.get_vehicle_id())+' ,Vehicle Cost:'+ str(self.get_vehicle_cost())+' ,Vehicle Premium Amount:'+ str(self.get_vehicle_premium_amount()) ) v1 = Vehicle() v1.set_vehicle_cost(50000) v1.set_vehicle_id(1001) v1.set_vehicle_type("Two Wheeler") v1.calculate_premium() v1.show_details() v1 = Vehicle() v1.set_vehicle_cost(80000) v1.set_vehicle_id(1002) v1.set_vehicle_type("Four Wheeler") v1.calculate_premium() v1.show_details()
91cd589cd7b40e80ab3d4f7511aa021564d46e08
ytakzk/basic_data_structures_and_algorithms_in_python
/geometry.py
5,138
3.59375
4
from point import Point class Line(object): def __init__(self, start, end): self.start = start self.end = end def project_from(self, point): base = self.end - self.start r = (point - self.start) * base / base.norm return self.start + base * r def reflect_from(self, point): return point + (self.project_from(point) - point) * 2 def distance_from_point(self, point, as_segment=False): base = self.end - self.start if as_segment: if (point - self.start) * base < 0: # outside return (point - self.start).length elif (point - self.end) * base < 0: # outside return (point - self.end).length else: # inside self.distance_from(point, False) else: # The magnitude of the cross product equals the area of a parallelogram with the vectors for sides area = (self.end - self.start).cross_product(point - self.start).length return area / (self.end - self.start).length def distance_from_line(self, line, as_segment=False): # Referenced http://paulbourke.net/geometry/pointlineplane/ as well d = lambda m, n, o, p: (m.x - n.x) * (o.x - p.x) + (m.y - n.y) * (o.y - p.y) + (m.z - n.z) * (o.z - p.z) d1343 = d(self.start, line.start, line.end, line.start) d4321 = d(line.end, line.start, self.end, self.start) d1321 = d(self.start, line.start, self.end, self.start) d4343 = d(line.end, line.start, line.end, line.start) d2121 = d(self.end, self.start, self.end, self.start) a = (d2121 * d4343 - d4321 * d4321) if a == 0: # in case lines are pararrel, get the shortest distance between the ends of each line d1 = self.distance_from_point(line.start, as_segment=as_segment) d2 = self.distance_from_point(line.end, as_segment=as_segment) d3 = line.distance_from_point(self.start, as_segment=as_segment) d4 = line.distance_from_point(self.end, as_segment=as_segment) return min(min(d1, d2), min(d3, d3)) else: mua = (d1343 * d4321 - d1321 * d4343) / (d2121 * d4343 - d4321 * d4321) mub = (d1343 + mua * d4321) / d4343 if not as_segment or (0 <= mua and mua <= 1 and 0 <= mub and mub <= 1): pa = self.start + (self.end - self.start) * mua pb = line.start + (line.end - line.start) * mub # cast from vector to point pa = Point(pa.x, pa.y, pa.z) pb = Point(pb.x, pb.y, pb.z) dist = pa.distance_to(pb) return dist d1 = self.distance_from_point(line.start, as_segment=as_segment) d2 = self.distance_from_point(line.end, as_segment=as_segment) d3 = line.distance_from_point(self.start, as_segment=as_segment) d4 = line.distance_from_point(self.end, as_segment=as_segment) return min(min(d1, d2), min(d3, d3)) def __repr__(self): return str(self) def __str__(self): return 'L(%s, %s)' % (self.start, self.end) class Circle(object): def __init__(self, center, radius, normal): self.center = center self.radius = radius self.normal = normal class Polygon(object): def __init__(self, points): self.points = points if __name__ == '__main__': from point import Point p0 = Point(0, 0, 0) p1 = Point(10, 0, 0) p2 = Point(5, 5, 0) p3 = Point(-1, -1, 0) print('p0: ', p0) print('p1: ', p1) print('p2: ', p2) print('p3: ', p3) print('-' * 30) line = Line(p0, p1) projected = line.project_from(p2) reflected = line.reflect_from(p2) print('Point ', p2, ' is projected to ', projected, ' on line ', line) print('Point ', p2, ' is reflected to ', reflected, ' on line ', line) print('-' * 30) print('The distance between p3 and L(p0, p1) is', line.distance_from_point(p3)) print('The distance between p3 and S(p0, p1) is', line.distance_from_point(p3, as_segment=True)) print('-' * 30) line1 = Line(Point(0, 0, 0), Point(10, 0, 0)) line2 = Line(Point(0, 10, 0), Point(10, 10, 0)) print('distance between %s and %s =' % (line1, line2), line1.distance_from_line(line2)) line3 = Line(Point(0, 0, 0), Point(10, 0, 0)) line4 = Line(Point(0, 0, 0), Point(10, 0, 0)) print('distance between %s and %s =' % (line3, line4), line3.distance_from_line(line4)) line5 = Line(Point(10, 10, 10), Point(-10, -10, -10)) line6 = Line(Point(10, -10, 10), Point(-10, 10, -10)) print('distance between %s and %s =' % (line5, line6), line5.distance_from_line(line6)) line7 = Line(Point(0, 0, 0), Point(1, 2, -4)) line8 = Line(Point(-10, -5, 0), Point(10, 5, 3)) print('distance between %s and %s =' % (line7, line8), line7.distance_from_line(line8))
51af1103fc2ca0831bccb54475c50a09b99bbf8d
shedolkar12/DS-Algo
/Tree/identical.py
1,223
4.3125
4
# Python Program to find the size of binary tree # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.val = data self.left = None self.right = None def check(root1, root2): if root1 is None and root2 is None: return True elif (root1 is None and root2 is not None) or (root1 is not None and root2 is None): return False return root1.val==root2.val and check(root1.left, root2.left) and check(root1.right, root2.right) # Driver program to test above function #input 1 root1 = Node(1) root1.left = Node(2) root1.right = Node(3) root1.left.left = Node(4) root1.left.right = Node(5) root2 = Node(1) root2.left = Node(2) root2.right = Node(3) root2.left.left = Node(4) print check(root1, root2) #input 2 root1 = Node(1) root1.left = Node(2) root1.right = Node(3) root1.left.left = Node(4) root1.left.right = Node(5) root1.left.left.left = Node(6) root2 = Node(1) root2.left = Node(2) root2.right = Node(3) root2.left.left = Node(4) root2.left.right = Node(5) root2.left.left.left = Node(6) print check(root1, root2) # input 3 root1 = Node(None) root2 = Node(None) print check(root1, root2)
54b2e7af9729ef3b15d55850cb7bbf431dfc4f07
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/174 Dungeon Game.py
3,110
4
4
""" The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers). In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Write a function to determine the knight's minimum initial health so that he is able to rescue the princess. For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN. -2(K) -3 3 -5 -10 1 10 30 -5(P) Notes: The knight's health has no upper bound. Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. """ __author__ 'Daniel' _______ ___ c_ Solution: ___ calculateMinimumHP dungeon """ dp Let F represent the HP Starting backward DP transition function: path = min(F[i+1][j], F[i][j+1]) # choose the right or down path with minimum HP required F[i][j] = max(1, path-dungeon[i][j]) # adjust for current cell :type dungeon: list[list[int] :rtype: int """ m l..(dungeon) n l..(dungeon 0 F [[___.maxint ___ _ __ x..(n+1)] ___ _ __ x..(m+1)] ___ i __ x..(m-1, -1, -1 ___ j __ x..(n-1, -1, -1 __ i __ m-1 a.. j __ n-1: F[i][j] m..(1, 1-dungeon[i][j]) ____ p.. m..(F[i+1][j], F[i][j+1]) # choose the path with minimum HP required F[i][j] m..(1, p..-dungeon[i][j]) # adjust for current cell r.. F 0 0 ___ calculateMinimumHP_error dungeon """ dp Not just the end results. We have to ensure at every cell the life > 0. Starting forward :type dungeon: list[list[int] :rtype: int """ m l..(dungeon) n l..(dungeon 0 __ m __ 1 a.. n __ 1: r.. 1-m..(0, dungeon 0 0 ) F [[-___.maxint-1 ___ _ __ x..(n+1)] ___ _ __ x..(m+1)] ___ i __ x..(1, m+1 ___ j __ x..(1, n+1 __ i __ 1 a.. j __ 1: F[i][j] dungeon[i-1][j-1] ____ F[i][j] m..(F[i-1][j], F[i][j-1])+dungeon[i-1][j-1] F[i][j] m..(F[i][j], dungeon[i-1][j-1]) r.. 1-F[-1][-1] __ _______ __ _______ ... Solution().calculateMinimumHP([[-3, 5]]) __ 4 ... Solution().calculateMinimumHP([[2, 1], [1, -1]]) __ 1
a0bf243480b693a93c25c50d57521db6016509c8
ankitoct/Core-Python-Code
/36. Formatting String/4. FormatMethodExample3.py
682
3.984375
4
# Comma as thousand Separator print("{:,}".format(1234567890)) #variable name = "Rahul" age= 62 print("My name is {} and age {}".format(name, age)) # Expressing a Percentage a = 50 b = 3 print("{:.2%}".format(a/b)) # Accessing arguments items value = (10, 20) print("{0[0]} {0[1]}".format(value)) # Format with Dict data1 = {'rahul': 2000, 'sonam': 3000} print("{0[rahul]:d} {0[sonam]:d}".format(data1)) # Format with Dict data2 = {'rahul': 2000, 'sonam': 3000} print("{d[rahul]:d} {d[sonam]:d}".format(d=data2)) # Accessing arguments by name: data3 = {'rahul': 2000, 'sonam': 3000} print("{rahul} {sonam}".format(**data3)) # ** is a format parameter (minimum field width)
12936686d58e2ccdff4f16f366025d911fee11a0
piurass/Mateus
/teste6.py
547
4.0625
4
print("digite um numero") numero1=input() print("digite outro numero") numero2=input() adição=int(numero1) + int(numero2) print("asoma é " + str(adição)) print("digite outro numero") numero3=input() subitração=int(numero2) - int(numero3) print("subitração é " + str(subitração)) print("digite outro numero") numero4=input() mutiplicação=int(numero3) * int(numero4) print("mutiplicaçã é " + str(mutiplicação)) print("digite outro numero") numero5=input() divisão=int(numero4) / int(numero5) print("divisão é " + str(divisão))
21feb4f45cebb0b78451a09f98a7fd1694a42a4a
TheUncertaintim/NatureWithKivy
/2_Forces/Exercise_2-5.py
3,620
4.125
4
""" Take a look at our formula for drag again: drag force = coefficient * speed * speed. The faster an object moves, the greater the drag force against it. In fact, an object not moving in water experiences no drag at all. Expand the example to drop the balls from different heights. How does this affect the drag as they hit the water? """ from kivy.app import App from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.clock import Clock from kivy.uix.floatlayout import FloatLayout from kivy.properties import ListProperty import numpy as np from random import randint from noise import pnoise1 from lib.pvector import PVector class Pocket(Widget): color = ListProperty([0,0,0,0]) def __init__(self, size, pos, c, coef=1, **kwargs): super(Pocket, self).__init__(**kwargs) self.size = size self.pos = pos self.fric_coef = coef if isinstance(c, list): self.color = c elif isinstance(c, str): if c == "r": self.color = [.5, 0, 0, 1] elif c == "g": self.color = [0, .5, 0, 1] elif c == "b": self.color = [0, 0, .5, 1] else: r = random() self.color = [r(), r(), r(), 1] class Ball(Widget): g = PVector(0, -.1) def __init__(self, size, pockets, **kwargs): super(Ball, self).__init__(**kwargs) self.pockets = pockets self.size = size, size self.mass = size / 10 self.vel = PVector(0, 0) self.acc = PVector(0, 0) def update(self, dt): gravity = self.g * self.mass # Apply drag when the ball is in the water drag = self.inWater() self.applyForce(gravity) self.applyForce(drag) self.checkEdge() self.move() def inWater(self): drag = PVector(0,0) collisions = map(self.collide_widget, self.pockets) for i, collision in enumerate(collisions): if collision: magnitude = 0.1 * self.vel.length2() drag = -1 * self.vel.normalize() * magnitude return drag def applyForce(self, force): acc = force / self.mass self.acc += acc def checkEdge(self): # check horizontal border if self.x + self.size[0] > Window.width: self.vel.x *= -1 self.x = Window.width - self.size[0] elif self.x < 0: self.vel.x *= -1 self.x = 0 # check vertical border if self.y + self.size[1] > Window.height: self.vel.y *= -1 self.y = Window.height - self.size[1] elif self.y < 0: self.vel.y *= -1 self.y = 0 def move(self): self.vel += self.acc self.vel.limit(10) self.pos = PVector(self.pos) + self.vel self.acc *= 0 class Universe(FloatLayout): def __init__(self, **kwargs): super(Universe, self).__init__(**kwargs) # add pockets for speeding-up/down balls water = Pocket(size=(Window.width, 150), pos=(0,0), c=[.5, .5, .5, 1]) self.add_widget(water) # add balls for x in np.arange(200, 600, 40).tolist(): self.add_balls(pos=(x, x+50), pockets=[water]) def add_balls(self, pos, pockets): wid = Ball(pos=pos, size=20, pockets=pockets) self.add_widget(wid) Clock.schedule_interval(wid.update, .01) class NatureApp(App): def build(self): return Universe() if __name__ == "__main__": NatureApp().run()
3724afd1ec93d3b45ac8dc83ba5f18b172f6ed87
kitagawa-hr/Project_Euler
/python/037.py
1,265
3.734375
4
""" Project Euler Problem 37 ======================== The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from itertools import product from functions import is_prime, list_to_num def is_truncable(x): """ >>> is_truncable(3797) True """ s = str(x) if all([is_prime(int(s[i:])) for i in range(len(s))]): if all([is_prime(int(s[:i])) for i in range(1, len(s) + 1)]): return True return False def main(): num = [1, 3, 7, 9] ans = [] for n in range(8, 100): if is_truncable(n): ans.append(n) for digit in range(3, 7): numlis = list(product(num, repeat=digit)) for x in numlis: y = list_to_num(x) if is_truncable(y): ans.append(y) if len(ans) >= 11: print(sum(ans[:11])) return if __name__ == '__main__': main()
85fa9e674a3756876b9990f2b6659a2d4bcd93b1
voyagerdva/Algorithms
/Lection_18_Class_LinkedList.py
632
3.90625
4
# ================================================== # # Lection 18. # Класс "Связанный массив" # asymptotics: O(1) # # ================================================== class LinkedList: def __init__(self): self._begin = None def insert(self, x): self._begin = [x, self._begin] def pop(self): assert self._begin is not None, "List is empty" x = self._begin[0] self._begin = self._begin[1] return x a = LinkedList() for i in range(1, 100, 1): a.insert(i) print(a.pop()) N = 10000 A = [0] * N A.insert(0, 1) print(A)
a32bb7ccc05f9dc8c79736b05a8e65d56a23f167
sherifkandeel/leetcode
/expirements/reading_writing_bst.py
951
3.578125
4
class Node: def __init__(self): self.val = -1 self.left = None self.right = None def preorder(root): if root == None: return print root.val preorder(root.left) preorder(root.right) def build(arr, root, maxx, minn): if len(arr) == 0: return None val = arr[0] arr.remove(val) root.val = val if len(arr) != 0: root.left = build(arr, Node(), val, minn) root.right = build(arr, Node(), maxx, val) return root def insert(tree, val): if tree == None: tree = Node() tree.val = val return tree if val > tree.val: tree.right = insert(tree.right, val) if val < tree.val: tree.left = insert(tree.left, val) return tree arr = [30,20,10,40,35,50] maxx = 9999 minn = 0 root = Node() root.val = arr[0] # build(arr, root, maxx, minn) for i in arr[1:]: insert(root, i) preorder(root)
35ec4163208336680c2f802f3eb56667346ae265
aszewciw/custom_py_modules
/victor/plotting_vc.py
10,719
3.546875
4
#! /usr/bin/env python # Victor Calderon # February 15, 2016 # Vanderbilt University """ Set of plotting functions commonly used in my codes. """ import matplotlib matplotlib.use( 'Agg' ) import matplotlib.pyplot as plt import os import numpy as num def Rotating_GIF(output_dir, ax, files, output_gif, prefix='tem'): """ Produces GIF for every rotation of figure in three axes. And deleted temporary figures. Parameters ---------- output_dir: str Location of output images ax: axis_like object, matplotlib_like object Figure axis to be rotated files: array_like List of absolute paths to output figures. output_gif: str Path to output gif figure. Creates a gif file with output figures. prefix: str Prefix of output images """ ## Prefix of output images output_files_pref = '{0}/{1}'.format(output_dir,prefix) ## Rotations for jj in range(0, 361, 15 ): ''' Rotation about z-axis''' elevation = 0 azimuth = jj ax.view_init(elev = elevation, azim = azimuth ) fname = '{0}_0_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(0, 91,10 ): ''' Rotation about y-axis ''' elevation = jj azimuth = 0 ax.view_init(elev = elevation, azim = azimuth ) fname = '{0}_1_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(0, 91, 10 ): ''' Rotation about z-axis ''' elevation = 90 azimuth = jj ax.view_init(elev = elevation, azim = azimuth ) fname = '{0}_2_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(90, 0, -10 ): ''' Rotation about x-axis ''' elevation = jj azimuth = 90 ax.view_init(elev = elevation, azim = azimuth ) fname = '{0}_3_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(90, 181, 10 ): ''' Rotation about y-axis ''' elevation = 0 azimuth = jj ax.view_init(elev = elevation, azim = azimuth ) fname = '{0}_4_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(0, 91, 10 ): elevation = jj azimuth = 180 ax.view_init(elev = elevation, azim = azimuth ) fname = '{0}_5_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(180, 271, 10 ): elevation = 90 azimuth = jj ax.view_init(elev = elevation, azim = azimuth ) fname = '{0}_6_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(90, 0, -10 ): elevation = jj azimuth = 270 ax.view_init(elev = elevation, azim = azimuth ) fname = '{0}_7_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) ## Creating GIF file delay = 32 repeat = True loop = -1 if repeat else 0 os.system('convert -delay %d -loop %d %s %s' %( delay,loop," ".join(files), \ output_gif) ) print('\t\t Output GIF file: {0}'.format(output_gif)) ## Removing temp files for fname in files: os.remove(fname) def Rotating_GIF_2axis(output_dir, ax1, ax2, files, output_gif, prefix='tem'): """ Produces GIF for every rotation of figure in three axes. And deleted temporary figures. Parameters ---------- output_dir: str Location of output images ax1: axis_like object, matplotlib_like object Primary Figure axis to be rotated ax2: axis_like object, matplotlib_like object Secondary Figure axis to be rotated files: array_like List of absolute paths to output figures. output_gif: str Path to output gif figure. Creates a gif file with output figures. prefix: str Prefix of output images """ ## Prefix of output images output_files_pref = '{0}/{1}'.format(output_dir,prefix) ## Rotations for jj in range(0, 361, 15 ): ''' Rotation about z-axis''' elevation = 0 azimuth = jj ax1.view_init(elev = elevation, azim = azimuth ) ax2.view_init(elev = elevation, azim = azimuth ) fname = '{0}_0_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(0, 91,10 ): ''' Rotation about y-axis ''' elevation = jj azimuth = 0 ax1.view_init(elev = elevation, azim = azimuth ) ax2.view_init(elev = elevation, azim = azimuth ) fname = '{0}_1_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(0, 91, 10 ): ''' Rotation about z-axis ''' elevation = 90 azimuth = jj ax1.view_init(elev = elevation, azim = azimuth ) ax2.view_init(elev = elevation, azim = azimuth ) fname = '{0}_2_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(90, 0, -10 ): ''' Rotation about x-axis ''' elevation = jj azimuth = 90 ax1.view_init(elev = elevation, azim = azimuth ) ax2.view_init(elev = elevation, azim = azimuth ) fname = '{0}_3_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(90, 181, 10 ): ''' Rotation about y-axis ''' elevation = 0 azimuth = jj ax1.view_init(elev = elevation, azim = azimuth ) ax2.view_init(elev = elevation, azim = azimuth ) fname = '{0}_4_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(0, 91, 10 ): elevation = jj azimuth = 180 ax1.view_init(elev = elevation, azim = azimuth ) ax2.view_init(elev = elevation, azim = azimuth ) fname = '{0}_5_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(180, 271, 10 ): elevation = 90 azimuth = jj ax1.view_init(elev = elevation, azim = azimuth ) ax2.view_init(elev = elevation, azim = azimuth ) fname = '{0}_6_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) for jj in range(90, 0, -10 ): elevation = jj azimuth = 270 ax1.view_init(elev = elevation, azim = azimuth ) ax2.view_init(elev = elevation, azim = azimuth ) fname = '{0}_7_{1}.png'.format( output_files_pref, jj) plt.savefig( fname ) files.append( fname ) ## Creating GIF file delay = 32 repeat = True loop = -1 if repeat else 0 os.system('convert -delay %d -loop %d %s %s' %( delay,loop," ".join(files), \ output_gif) ) print('\t\t Output GIF file: {0}'.format(output_gif)) ## Removing temp files for fname in files: os.remove(fname) def GIF_MOVIE(files, output_gif, delay=60, repeat=True, removef=False): """ Given a list if 'files', it creates a gif file, and deletes temp files. Parameters ---------- files: array_like List of abs. paths to temporary figures output_gif: str Absolute path to output gif file. """ loop = -1 if repeat else 0 os.system('convert -delay %d -loop %d %s %s' %( delay,loop," ".join(files), \ output_gif) ) if removef: for fname in files: os.remove(fname) def Med_scatter_plot(x_data, y_data, ax, statfunc=num.median, alpha=.34, mode='perc',\ perc_opt='data', fill=True, *args): """ Calculates median, scatter or percentiles. Optionally: plots the median relation and scatter/percentiles of the data. x_data: array_like, Shape (N, ...), one-dimensional array of x and y values. Array of x- and y-values for `N` number of data points. y_data: array_like, Shape (N,2), two-dimensional array of x and y values. Array of x- and y-values for `N` number of data points. ax: axis_like object, matplotlib object axis to plot the results. statfunc: numpy statistical function (default=numpy.median) Statistical function to evaluate the data alpha: float (default = .34) Percentile value to be estimated Value between (0,100) mode: string Type of plot to produce. - 'perc': Plots the values between the 50 pm `alpha` about the med, plus line for statfunc. - 'scat': Plots the mean of each bin, along with the scatter of the data. perc_opt: string, optional Option for how to calculate the percentiles in each bin of data. - perc_opt='data': It uses the actual data enclosed by `alpha` about med. - perc_opt='numpy': Use the numpy.percentile function to estimate the percentiles. fill: boolean, optional (default=True) Option for filling the area of interest. args: array_like, optional Array of arguments to be passed to matplotlib functions. """ assert(mode=='perc' or mode=='scat') assert(alpha>=0. and alpha<=1.) assert() n_bins = y_data.shape[0] stat_sort_ydat=num.sort(y_data) if mode=='perc': stat_sort_dat_val = statfunc(stat_sort_ydat, axis=1) if perc_opt=='data': stat_sort_dat_per=num.array([ [stat_sort_ydat[xx][int(((alpha/2.))*len(stat_sort_ydat[xx]))], stat_sort_ydat[xx][int((1.-(alpha/2.))*len(stat_sort_ydat[xx]))]] for xx in range(len(stat_sort_ydat))]) elif perc_opt=='numpy': stat_sort_dat_per=num.array([ [num.percentile(stat_sort_ydat[xx],100.*(alpha/2.)), num.percentile(stat_sort_ydat[xx],100.*(1.-(alpha/2.)))] for xx in range(len(stat_sort_ydat))]) if fill: ax.plot(x_data, stat_sort_dat_val, *args) ax.fill_between(x_data, y1=stat_sort_dat_per.T[0], y2=stat_sort_dat_per.T[1], *args) else: ax.errorbar(x_data, stat_sort_dat_val, yerr=stat_sort_dat_per, *args)
cb4d20cc215c5f6eddebbffee37af68af0019725
aylat/Payroll_Program
/Payroll_Program.py
1,332
4.25
4
# aylat # This program will calculate and display different aspects of a user's payroll # Define constants OT_MULTIPLIER = 1.5 DEDUCTION_PERCENTAGE = 0.2 # Prompt user to input information EmployeeName = input('Enter the employees full name: ') RegHours = float(input('Enter the number of regular hours worked by the employee: ')) OvertimeHours = float(input('Enter the number of overtime hours worked by the employee: ')) PayRate = float(input('Enter the hourly pay for the the employee: ')) # Perform payroll calculations based on user input RegPay = RegHours * PayRate OvertimePay = OvertimeHours * PayRate * OT_MULTIPLIER GrossPay = RegPay + OvertimePay Deductions = GrossPay * DEDUCTION_PERCENTAGE NetPay = GrossPay - Deductions # Display and format the output to the user print('\n') print('Employee Name:\t\t', EmployeeName) print('Regular Hours Worked:\t', format(RegHours, '.2f')) print('Overtime Hours Worked:\t', format(OvertimeHours, '.2f')) print('Hourly Pay Rate:\t$', format(PayRate, ',.2f'), sep='') print('\n') print('Regular Pay:\t\t$', format(RegPay, ',.2f'), sep='') print('Overtime Pay:\t\t$', format(OvertimePay, ',.2f'), sep='') print('Gross Pay:\t\t$', format(GrossPay, ',.2f'), sep='') print('Deductions:\t\t$', format(Deductions, ',.2f'), sep='') print('Net Pay:\t\t$', format(NetPay, ',.2f'), sep='')
6a9597bce066c258dffbe92564bd93260566a516
comorina/Ducat_Assignment
/p18.py
188
3.96875
4
print("Even numbers : ") for i in range(1,101): if(i%2==0): print(i, end=" ") print("\nOdd numbers : ") for i in range(1,101): if(i%2!=0): print(i, end=" ")
cc77ad1ae4446195ba3733dbde10888710ac9627
edytadlu/Music_library
/display.py
1,345
3.703125
4
print('\n') print(' ╔╦╗╦ ╦╔═╗╦╔═╗ ╦ ╦╔╗ ╦═╗╔═╗╦═╗╦ ╦') print(' ║║║║ ║╚═╗║║ ║ ║╠╩╗╠╦╝╠═╣╠╦╝╚╦╝') print(' ╩ ╩╚═╝╚═╝╩╚═╝ ╩═╝╩╚═╝╩╚═╩ ╩╩╚═ ╩ ') print('\n') def print_table(albums): print("-------------------------------------------------------------------------") print('ARTIST | ALBUM | YEAR OF RELEASE | GENRE | DURATION ') print("-------------------------------------------------------------------------") for album in albums: print(' | '.join(album)) print("-------------------------------------------------------------------------") # artist = album[0] # print(artist) # album_name = album[1] # print(album_name) # year = int(album[2]) # print(year) # genre = album[3] # print(genre) # album_time = int(album[4]) # print(album_time) def display_menu(): print('Menu:') print("1 -> Display All") print("2 -> Find album by genre ") print("3 -> Find album from time range") print("4 -> Find shortest/longest album") print("5 -> Find the album by artist") print("6 -> Find the album by album name") print("0 -> Exit")
36260b4dcf82a5723cb342e092a55dc1efc51052
yileizhang0111/pp-project-1-yileizhang0111-master
/trading/indicators.py
2,566
3.984375
4
import numpy as np def moving_average(stock_price, n=7, weights=[]): ''' Calculates the n-day (possibly weighted) moving average for a given stock over time. Input: stock_price (ndarray): single column with the share prices over time for one stock, up to the current day. n (int, default 7): period of the moving average (in days). weights (list, default []): must be of length n if specified. Indicates the weights to use for the weighted average. If empty, return a non-weighted average. Output: ma (ndarray): the n-day (possibly weighted) moving average of the share price over time. ''' # Lines X-Y: gordoncluster # URL: https://gordoncluster.wordpress.com/2014/02/13/python-numpy-how-to-generate-moving-averages-efficiently-part-2/ # Python numpy How to Generate Moving Averages Efficiently Part 2, 2014 # Accessed on 7 Nov 2020. if len (weights) == 0: weights = np.repeat (1.0, n) / n ma = np.convolve (stock_price, weights, 'valid') return ma def oscillator(stock_price, n=7, osc_type='stochastic'): ''' Calculates the level of the stochastic or RSI oscillator with a period of n days. Input: stock_price (ndarray): single column with the share prices over time for one stock, up to the current day. n (int, default 7): period of the moving average (in days). osc_type (str, default 'stochastic'): either 'stochastic' or 'RSI' to choose an oscillator. Output: osc (ndarray): the oscillator level with period $n$ for the stock over time. ''' start = 0 end = start + n osc = np.zeros (len (stock_price) - n + 1) while end <= len (stock_price): if osc_type == "stochastic": highest = max (stock_price[start:end]) lowest = min (stock_price[start:end]) if highest != lowest: osc[start] = (stock_price[end - 1] - lowest) / (highest - lowest) else: osc[start] = 0 elif osc_type == "RSI": diff = np.diff (stock_price[start:end]) positive = np.average (diff[diff > 0]) if not np.isnan (np.average (diff[diff > 0])) else 0 negative = abs (np.average (diff[diff < 0])) if not np.isnan (abs (np.average (diff[diff < 0]))) else 0 if positive == 0 and negative == 0: osc[start] = 0 else: osc[start] = positive / (negative + positive) start += 1 end += 1 return osc
1f1c1adf731f8ca844b589d5014e0b90098cb542
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/163_13.py
2,856
4.21875
4
Python | Convert a list of lists into tree-like dict Given a list of lists, write a Python program to convert the given list of lists into a tree-like dictionary. **Examples:** **Input :** [[1], [2, 1], [3, 1], [4, 2, 1], [5, 2, 1], [6, 3, 1], [7, 3, 1]] **Output :** {1: {2: {4: {}, 5: {}}, 3: {6: {}, 7: {}}}} **Input :** [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']] **Output :** {'A': {'C': {'D': {}}, 'B': {}}} **Method #1 :** Naive Method This is a Naive approach in which we use two for loops to traverse the list of lists. We initialize the empty dictionary ‘tree’ to _currTree_ and each time we check if the key (list of list’s item) is included in the _currTree_ or not. If not, include it in the _currTree_ , otherwise do nothing. Finally, assign the currTree[key] to currTree. __ __ __ __ __ __ __ # Python3 program to Convert a list # of lists into Dictionary (Tree form) def formTree(list): tree = {} for item in list: currTree = tree for key in item[::-1]: if key not in currTree: currTree[key] = {} currTree = currTree[key] return tree # Driver Code lst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']] print(formTree(lst)) --- __ __ **Output:** {'A': {'B': {}, 'C': {'D': {}}}} **Method #2 :** Using reduce() The reduce() function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. We will use reduce() to traverse the dictionary and reuse getTree() to find the location to store the value for setTree(). All but the last element in _mapList_ is needed to find the ‘parent’ dictionary to add the value to, then use the last element to set the value to the right key. __ __ __ __ __ __ __ # Python3 program to Convert a list # of lists into Dictionary (Tree form) from functools import reduce from operator import getitem def getTree(tree, mappings): return reduce(getitem, mappings, tree) def setTree(tree, mappings): getTree(tree, mappings[:-1])[mappings[-1]] = dict() # Driver Code lst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']] tree ={} for item in lst: setTree(tree, item[::-1]) print(tree) --- __ __ **Output:** {'A': {'B': {}, 'C': {'D': {}}}} Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
bd0577bf0b4c2cfa0cbbb041034be9d3c80bd0ab
recruz02/coderbyte_solutions
/python/simple_symbols.py
650
3.828125
4
def SimpleSymbols(pString): # code goes here myChars = list(pString) for index in range(0, len(myChars)): # CHECK EDGE CONDITIONS if myChars[0].isalpha(): return "false" if myChars[len(myChars)-1].isalpha(): return "false" # OTHERWISE CHECK LEFT AND RIGHT CHARACTERS if myChars[index].isalpha(): if myChars[index-1] != '+' or myChars[index+1] != '+': return "false" return "true" # keep this function call here print SimpleSymbols(raw_input())
e3d0fbb37c624f2d2063d6834a14d583015f6101
wyaadarsh/LeetCode-Solutions
/Python3/0987-Vertical-Order-Traversal-of-a-Binary-Tree/soln.py
672
3.84375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def verticalTraversal(self, root: 'TreeNode') -> 'List[List[int]]': ans = collections.defaultdict(list) def traverse(node, x, y): if node: ans[x].append((y, node.val)) traverse(node.left, x - 1, y + 1) traverse(node.right, x + 1, y + 1) traverse(root, 0, 0) ret = [] for key in sorted(ans): lst = sorted(ans[key]) ret.append([b for a, b in lst]) return ret
8460526bbb0448efed3bc19ea5e5b994ea6f2faf
trigartha/NeuralExperiments
/BasicNeuralNet/BasicNeuralNet/BasicNeuralNet.py
1,264
4.0625
4
import numpy as np # Takes in weighted sum of the inputs and normalizes # them through between 0 and 1 through a sigmoid function def sigmoid(x): return 1 / (1 + np.exp(-x)) # to calculate the adjustments def sigmoid_derivative(x): return x * (1 - x) training_inputs = np.array([[0,0,1], [1,1,1], [1,0,1], [0,1,1]]) training_outputs = np.array([[0,1,1,0]]).T np.random.seed(1) synaptic_weights = 2 * np.random.random((3,1))-1 print('Random starting synaptic weights: ') print(synaptic_weights) for iteration in range(20000): input_layer = training_inputs # With the help of Sigmoid activation function, we are able to reduce the loss during the # time of training because it eliminates the gradient problem in machine learning model # while training. outputs = sigmoid(np.dot(input_layer, synaptic_weights)) # Calculate error error = training_outputs - outputs adjustments = error * sigmoid_derivative(outputs) # np.dot * (multiplier, multiplier) synaptic_weights += np.dot(input_layer.T, adjustments) print('Synaptic weights after traning') print(synaptic_weights) print('Outputs after training: ') print(outputs)
56e7e357b2a2741c3f621cf764155f63c8b668dc
maximilianogomez/Progra1
/Practica 2/EJ7.py
956
4.1875
4
# Escribir una función que reciba una lista como parámetro y devuelva True si la lista # está ordenada en forma ascendente o False en caso contrario. Por ejemplo, # ordenada([1, 2, 3]) retorna True y ordenada(['b', 'a']) retorna False. Desarrollar # además un programa para verificar el comportamiento de la función. #Funciones: def ordenasc(lista): '''Copia una lista, la ordena y la compara con la original''' orden = False listaord = lista.copy() #otra forma es listaord = lista[ : ] listaord.sort() if listaord == lista: orden = True return orden #Programa Principal: def main(): print("TP2:EJ7") lista = [1, 2, 3] lista2 = ['b', 'a'] print(lista) print(lista2) if ordenasc(lista2): print("La lista esta ordenada Ascendentemente") else: print("La lista no esta ordenada ascendentemente") if __name__ == "__main__": main()
b296aabacc4322e13cf7dad273d6fd6129b89d30
tjroberts/Othello
/gameBoard.py
13,081
3.671875
4
#Tyler Robertson #ID : 22991994 import collections import copy BLACK = 'black' WHITE = 'white' class invalidMoveException(Exception) : '''this will be raised if the user enters a move that is out of range of the current board''' pass class occupiedSpaceException(Exception) : '''this exception is fired when the player tries to move to a space that is already occupied by a playing piece''' pass class gameState : BLACK = 'black' WHITE = 'white' def __init__(self, boardRows, boardCols, gameType : 'gameTypeTuple') : self._boardRows = boardRows self._boardCols = boardCols self._gameType = gameType self._board = [] for rows in range(boardRows) : self._board.append([" "] * boardCols) self._setupGameboard() def _setupGameboard(self) -> None : #determine the middle of the board upperDiagonalRow = (self._boardRows // 2) - 1 upperDiagonalCol = (self._boardCols // 2) - 1 if self._gameType.isTradSetup.upper() == 'YES' : self._board[upperDiagonalRow][upperDiagonalCol] = gameState.WHITE self._board[upperDiagonalRow + 1][upperDiagonalCol + 1] = gameState.WHITE self._board[upperDiagonalRow][upperDiagonalCol + 1] = gameState.BLACK self._board[upperDiagonalRow + 1][upperDiagonalCol] = gameState.BLACK else : self._board[upperDiagonalRow][upperDiagonalCol] = gameState.BLACK self._board[upperDiagonalRow + 1][upperDiagonalCol + 1] = gameState.BLACK self._board[upperDiagonalRow][upperDiagonalCol + 1] = gameState.WHITE self._board[upperDiagonalRow + 1][upperDiagonalCol] = gameState.WHITE def _makeMove(self, playerToken : str, row : int, col : int) -> bool : if row > self._boardRows or row < 1 : raise invalidMoveException() elif col > self._boardCols or col < 1 : raise invalidMoveException() elif not self._board[row - 1][col - 1] == " " : raise occupiedSpaceException() row -= 1 col -= 1 self._board[row][col] = playerToken isMove = self._checkForFlips(playerToken, row, col) if not isMove : self._board[row][col] = ' ' return isMove def _checkForFlips(self, playerToken : str, row : int, col : int) -> bool : isHorizontal = self._checkHorizontal(row, col, playerToken) isVerticle = self._checkVerticle(row, col, playerToken) isUpDiagonal = self._checkUpDiagonal(row, col, playerToken) isDownDiagonal = self._checkDownDiagonal(row, col, playerToken) if isHorizontal or isVerticle or isUpDiagonal or isDownDiagonal : return True else : return False def _checkHorizontal(self, row : int, col : int, playerToken : str) -> bool : playerCol = col if playerToken == gameState.BLACK : opponentToken = gameState.WHITE else : opponentToken = gameState.BLACK #loop through the row in question for colIndex in range(self._boardCols) : flip = True foundTwo = False startCol = 0 endCol = 0 #find first piece if self._board[row][colIndex] == playerToken : startCol = colIndex #check for another piece for col in range(colIndex + 1, self._boardCols) : if self._board[row][col] == playerToken : foundTwo = True endCol = col break if foundTwo : #check if all spaces between are opponents color for checkCol in range(startCol + 1, endCol) : if not self._board[row][checkCol] == opponentToken : flip = False break if foundTwo and flip and not startCol + 1 == endCol : if playerCol == startCol or playerCol == endCol : for flipCol in range(startCol + 1, endCol) : self._board[row][flipCol] = playerToken return True return False def _checkVerticle(self, row: int, col : int, playerToken : str) -> bool : playerRow = row if playerToken == gameState.BLACK : opponentToken = gameState.WHITE else : opponentToken = gameState.BLACK #loop through the column last move played in for rowIndex in range(self._boardRows): flip = True foundTwo = False startRow = 0 endRow = 0 #find the first piece if self._board[rowIndex][col] == playerToken : startRow = rowIndex #check for another piece for row in range(rowIndex + 1, self._boardRows) : if self._board[row][col] == playerToken : foundTwo = True endRow = row break if foundTwo : #check if all spaces between are opponent color for checkRow in range(startRow + 1, endRow) : if not self._board[checkRow][col] == opponentToken : flip = False break if foundTwo and flip and not startRow + 1 == endRow : if playerRow == startRow or playerRow == endRow : for flipRow in range(startRow + 1, endRow) : self._board[flipRow][col] = playerToken return True return False #checks up diagonal row a token was just placed in for flips def _checkUpDiagonal(self, row : int, col : int, playerToken : str) -> bool : upDiagonalRow = row upDiagonalCol = col if playerToken == gameState.BLACK : opponentToken = gameState.WHITE else : opponentToken = gameState.BLACK while upDiagonalCol > 0 and upDiagonalRow < (self._boardRows - 1) : upDiagonalRow += 1 upDiagonalCol -= 1 #check up diagonal for flips countRow = upDiagonalRow countCol = upDiagonalCol while countRow >= 0 and countCol <= (self._boardCols - 1) : flip = True foundTwo = False #find first piece if self._board[countRow][countCol] == playerToken : startRow = countRow startCol = countCol countRow2 = startRow - 1 countCol2 = startCol + 1 #find second piece while countRow2 >= 0 and countCol2 <= (self._boardCols - 1) : if self._board[countRow2][countCol2] == playerToken : foundTwo = True endRow = countRow2 endCol = countCol2 break countRow2 -= 1 countCol2 += 1 #check values between start and end points for opponents color if foundTwo : flipRowCount = startRow - 1 flipColCount = startCol + 1 while not flipRowCount == endRow : if not self._board[flipRowCount][flipColCount] == opponentToken : flip = False break flipRowCount -= 1 flipColCount += 1 countRow -= 1 countCol += 1 #if two pieces are found and opponent pieces are between them if foundTwo and flip : flipRowCount = startRow flipColCount = startCol if startCol == col or endCol == col : #check and make sure there is something to flip between if not flipRowCount - 1 == endRow : while not flipRowCount == endRow : self._board[flipRowCount][flipColCount] = playerToken flipRowCount -= 1 flipColCount += 1 return True else : continue return False #looks for move in the down diagonal that the piece was placed in def _checkDownDiagonal(self, row : int, col : int, playerToken : str) -> bool : downDiagonalRow = row downDiagonalCol = col if playerToken == gameState.BLACK : opponentToken = gameState.WHITE else : opponentToken = gameState.BLACK #find starting coordinates of down diagonal while downDiagonalCol > 0 and downDiagonalRow > 0: downDiagonalRow -= 1 downDiagonalCol -= 1 #check down diagonal for flips countRow = downDiagonalRow countCol = downDiagonalCol while countRow <= (self._boardRows - 1) and countCol <= (self._boardCols - 1) : flip = True foundTwo = False #find first piece if self._board[countRow][countCol] == playerToken : startRow = countRow startCol = countCol countRow2 = startRow + 1 countCol2 = startCol + 1 #find second piece while countRow2 <= (self._boardRows - 1) and countCol2 <= (self._boardCols - 1) : if self._board[countRow2][countCol2] == playerToken : foundTwo = True endRow = countRow2 endCol = countCol2 break countRow2 += 1 countCol2 += 1 #check values between start and end points for opponents color if foundTwo : flipRowCount = startRow + 1 flipColCount = startCol + 1 while not flipRowCount == endRow : if not self._board[flipRowCount][flipColCount] == opponentToken : flip = False break flipRowCount += 1 flipColCount += 1 countRow += 1 countCol += 1 #if two peices are found and there are opponent pieces between them if foundTwo and flip : flipRowCount = startRow flipColCount = startCol if startCol == col or endCol == col : #check and make sure there is something to flip between if not flipRowCount + 1 == endRow : while not flipRowCount == endRow : self._board[flipRowCount][flipColCount] = playerToken flipRowCount += 1 flipColCount += 1 return True else : continue return False #detrmine if there are any available moves for the player def _checkIfPossibleMove(self, playerToken : str) -> bool : foundFlip = False originalBoard = copy.deepcopy(self._board) for row in range(1,self._boardRows + 1) : for col in range(1,self._boardCols + 1) : if self._isEmpty(row - 1, col - 1) : foundFlip = self._makeMove(playerToken, row, col) self._board[row - 1][col - 1] = ' ' if foundFlip : self._board = originalBoard return True return False def _isEmpty(self, row : int, col : int) -> bool : if self._board[row][col] == ' ' : return True else : return False def _isBoardFull(self, gameType : 'gameTypeTuple') -> bool : numBlack, numWhite = self._countPieces() boardFull = numBlack + numWhite == self._boardRows * self._boardCols if boardFull : return True return False def _countPieces(self) -> int: numBlack = 0 numWhite = 0 for row in range(self._boardRows) : for col in range(self._boardCols) : if self._board[row][col] is gameState.BLACK : numBlack += 1 elif self._board[row][col] is gameState.WHITE : numWhite += 1 return numBlack, numWhite
67d6e066efc37c5561cd27caa2b1f82791c3d1c6
TasosBaikas/python-projects
/Ασκηση 5.py
4,958
4.0625
4
from random import randrange,seed,shuffle from datetime import datetime from math import floor,ceil seed(None) Arrays = 100 def inputChecker(rowOrColumn): while(1): try: NumberOfRowsOrColumns = int(input(f"give {rowOrColumn} for the matrix (must be more than 2):")) print(" ") if NumberOfRowsOrColumns > 2: break else: print(f"wrong {rowOrColumn[:-1]} input!!") print(" ") except: SystemExit(0) return NumberOfRowsOrColumns def userInput(): for i in range(10): print(" ") print("----------- The SOS statistic -----------") for i in range(3): print(" ") rows = inputChecker("rows") columns = inputChecker("columns") wantToSeeTheArrays = int(input(f"Do you want to see the {Arrays} Arrays; (1 for Yes or 0 for No) :")) print(" ") if wantToSeeTheArrays == 1: wantToSeeTheArrays = 1 else: wantToSeeTheArrays = 0 return rows,columns,wantToSeeTheArrays def makeSosArray(rows,columns): sosTempList = [] if (randrange(0,2)): #for not to place more S or O if the matrix has an odd number of cells for cell in range(floor(rows*columns/2)): sosTempList.append("S") for cell in range(ceil(rows*columns/2)): sosTempList.append("O") else: for cell in range(ceil(rows*columns/2)): sosTempList.append("S") for cell in range(floor(rows*columns/2)): sosTempList.append("O") shuffle(sosTempList) def fillSosArray(): matrix = [] for row in range(rows): matrix.append([]) for column in range(columns): matrix[row].append(sosTempList[row*(columns) + column]) return matrix filledMatrix = fillSosArray() return filledMatrix def checkForSos(rows,columns,sosArray): def checkRows(): sosFound = 0 for row in range(rows): for column in range(columns - 2): if sosArray[row][column] == "S" and sosArray[row][column + 1] == "O" and sosArray[row][column + 2] == "S" : sosFound += 1 return sosFound def checkColumns(): sosFound = 0 for column in range(columns): for row in range(rows - 2): if sosArray[row][column] == "S" and sosArray[row + 1][column] == "O" and sosArray[row + 2][column] == "S" : sosFound += 1 return sosFound def checkDiagonals(): sosFound = 0 for row in range(rows - 2): #first time across the array for column in range(columns - 2): if sosArray[row][column] == "S" and sosArray[row + 1][column + 1] == "O" and sosArray[row + 2][column + 2] == "S" : sosFound += 1 #second time across the array for column in range(columns - 2): if sosArray[row][-column - 1] == "S" and sosArray[row + 1][-column - 2] == "O" and sosArray[row + 2][-column - 3] == "S" : sosFound += 1 return sosFound #first we are looking at the rows sosFoundInRows = checkRows() sosTriesInRows = rows*(columns - 2) #Next we are looking at the columns sosFoundInColumns = checkColumns() sosTriesInColumns = columns*(rows - 2) #Next we are looking for the diagonals sosFoundInDiagonals = checkDiagonals() sosTriesInDiagonals = (rows - 2)*2 totalSosFound = sosFoundInRows + sosFoundInColumns + sosFoundInDiagonals totalSosTries = sosTriesInRows + sosTriesInColumns + sosTriesInDiagonals return totalSosFound,totalSosTries def printArrays(rows,sosArray,sosFound,sosTries): print("----------------") for row in range(rows): print(sosArray[row]) print("SOS found = " + str(sosFound)) print("Checks that were made = " + str(sosTries)) def main(): rows,columns,wantToSeeTheArrays = userInput() totalSosFound = 0 totalSosTries = 0 for game in range(Arrays): sosArray = makeSosArray(rows,columns) sosFound,sosTries = checkForSos(rows,columns,sosArray) if wantToSeeTheArrays: printArrays(rows,sosArray,sosFound,sosTries) totalSosFound += sosFound totalSosTries += sosTries average = totalSosFound/totalSosTries print("====================================") print(f"Total SOS found in the {Arrays} Arrays = {totalSosFound}") print(f"Total checks for SOS that were made in the {Arrays} Arrays = {totalSosTries}" + "\n") print(f"The average SOS that were found in the {Arrays} Arrays is {average*100}%") main()
c56ae76a8d1f5e12f767375818a9aca9cd120952
smokeless/py3course
/18_cows_and_bulls.py
2,254
4.21875
4
''' Create a program that will play the “cows and bulls” game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the wrong place, they have a “cow”. For every digit the user guessed correctly in the right place is a “bull.” Every time the user makes a guess, tell them how many “cows” and “bulls” they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout teh game and tell the user at the end. Say the number generated by the computer is 1038. An example interaction could look like this: Welcome to the Cows and Bulls Game! Enter a number: 1234 2 cows, 0 bulls 1256 1 cow, 1 bull ... Until the user guesses the number. ''' import random def generateNumber(): number = '' for i in range(1,5): randString = str(random.randint(1,9)) number = number + randString return number def checkBulls(userNumber, computerNumber): bullCow = [0, 0] for char in range(0,4): if(userNumber[char] in computerNumber): if userNumber[char] == computerNumber[char]: bullCow[0] += 1 else: bullCow[1] += 1 return bullCow def parseInput(): uInput = input('>> ') if uInput.isdigit() and len(uInput)==4: return uInput else: print('not a valid number.') return False if __name__ == '__main__': print("I will come up with a four digit number. You guess the", "number. Every digit you guess correctly in the wrong", "place is a cow. Every digit you guess correctly in ", "the right place is a bull.") computerNumber = generateNumber() guesses = 0 while True: myNumber = parseInput() while myNumber == False: myNumber = parseInput() bulls = checkBulls(myNumber, computerNumber) print('bulls', bulls[0]) print('cows', bulls[1]) guesses += 1 print('guesses', guesses) if bulls[0] == 4: print('the number was,', computerNumber) print('you won!') exit(0)
7f2e0a5f021f0aa569425d0808e00f2619fff328
LfqGithub/LfqGithub.github.io
/docs/python/oldButImportant/note/sorted_test.py
152
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- print(sorted([1,2,32,-3,5],key=abs)) print(sorted(['abc','AC','Tim','Lucy'],key=str.lower,reverse=True))
08bbe0be9ef3903061ef6bb13f30cc3003bf17ba
chrisjdavie/interview_practice
/old_leetcode/0079-word-search/redo.py
4,280
3.828125
4
""" 3rd try - just making sure I've got all the aspects of this in my head - I can do it faster without bugs - I can write the clean code first time round - I understand the details Retro - I did get most of these. I think the code is a tad better. It revieled that I still have slight issues automaticallly figuring out index ordering in grids. But this isn't a new issue. https://leetcode.com/problems/word-search/ Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. The not-too Pythonic "class Solution" is a leetcode thing """ from typing import List, Set from unittest import TestCase from parameterized import parameterized class Solution: def exist(self, board: List[List[str]], word: str) -> bool: row_max = len(board) col_max = len(board[0]) def dfs(char_num: int, row_num: int, col_num: int, visited: Set[int] ) -> bool: if char_num >= len(word): return True coords = (row_num, col_num) if (coords in visited or col_num >= col_max or col_num < 0 or row_num >= row_max or row_num < 0 or word[char_num] != board[row_num][col_num]): return False visited.add(coords) valid = ( dfs(char_num + 1, row_num, col_num + 1, visited) or dfs(char_num + 1, row_num, col_num - 1, visited) or dfs(char_num + 1, row_num + 1, col_num, visited) or dfs(char_num + 1, row_num - 1, col_num, visited)) visited.remove(coords) return valid visited = set() for row_num in range(row_max): for col_num in range(col_max): if dfs(0, row_num, col_num, visited): return True return False class TestExist(TestCase): def setUp(self): self._solution = Solution() @parameterized.expand([ ("A", True), ("B", False) ]) def test_single_character(self, word, expected_result): board = [ ["A"] ] self.assertEqual(self._solution.exist(board, word), expected_result) def test_one_row_single_charater(self): word = "A" board = [ ["B", "A"] ] self.assertEqual(self._solution.exist(board, word), True) def test_multi_row_single_charater(self): word = "A" board = [ ["B"], ["A"] ] self.assertEqual(self._solution.exist(board, word), True) @parameterized.expand([ ("AB", True), ("AC", True), ("BA", True), ("CA", True), ("AD", False) ]) def test_two_charaters(self, word, expected_result): board = [ ["A", "B"], ["C", "D"] ] self.assertEqual(self._solution.exist(board, word), expected_result) @parameterized.expand([ ("AG", False), ("AC", False) ]) def test_doesnt_loop(self, word, expected_result): board = [ ["A", "B", "C"], ["D", "E", "F"], ["G", "H", "I"] ] self.assertEqual(self._solution.exist(board, word), expected_result) def test_doesnt_repeat(self): word = "ABA" board = [ ["B", "A"] ] self.assertEqual(self._solution.exist(board, word), False) def test_can_revisit(self): word = "ABEFCB" board = [ ["A", "B", "C"], ["B", "E", "F"] ] self.assertEqual(self._solution.exist(board, word), True) @parameterized.expand([ ("ABCCED", True), ("SEE", True), ("ABCB", False) ]) def test_examples(self, word, expected_result): board = [ ["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"] ] self.assertEqual(self._solution.exist(board, word), expected_result)
de35fd1752e1fbc041f8791c73ecf854c9941615
HalfMoonFatty/Interview-Questions
/272. Closest Binary Search Tree Value II.py
3,121
3.859375
4
''' Problem: Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. Note: Given target value is a floating point. You may assume k is always valid, that is: k ≤ total nodes. You are guaranteed to have only one unique set of k values in the BST that are closest to the target. Follow up: Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)? Hint: 1. Consider implement these two helper functions: - getPredecessor(N), which returns the next smaller node to N. - getSuccessor(N), which returns the next larger node to N. 2. Try to assume that each node has a parent pointer, it makes the problem much easier. 3. Without parent pointer we just need to keep track of the path from the root to the current node using a stack. 4. You would need two stacks to track the path in finding predecessor and successor node separately. ''' class Solution(object): def closestKValues(self, root, target, k): """ :type root: TreeNode :type target: float :type k: int :rtype: List[int] """ # keep track of the path from the root to the current node using a stack def initSuccessor(root, target, suc): while root: if root.val > target: suc.append(root) root = root.left else: root = root.right return # keep track of the path from the root to the current node using a stack def initPredecessor(root, target, pred): while root: # note: add node whose value equals to target to the pred stack if root.val <= target: pred.append(root) root = root.right else: root = root.left return def getNextSuccessor(suc): cur = suc.pop() ret = cur.val cur = cur.right while cur: suc.append(cur) cur = cur.left return ret def getNextPredecessor(pred): cur = pred.pop() ret = cur.val cur = cur.left while cur: pred.append(cur) cur = cur.right return ret if not root: return None result = [] suc, prev = [], [] # pred and suc stack initialization initPredecessor(root, target, pred) initSuccessor(root, target, suc) for i in range(k): # pay attention to the corner case if not suc: result.append(getNextPredecessor(pred)) elif not pred: result.append(getNextSuccessor(suc)) else: if abs(target-suc[-1].val) < abs(target-pred[-1].val): result.append(getNextSuccessor(suc)) else: result.append(getNextPredecessor(pred)) return result
56b53836372c5a6c3f7e98db8090be159719ddfd
GiliardGodoi/algorithms
/math/metodos_numericos/dicotomia.py
1,368
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Implementa o método da dicotomia para encontrar o zero de funções. ''' import math class MetodoDicotomia(): ''' Implementa o método da dicotomia para encontrar as raízes de uma função. ''' def dicotomia(self, funcao, xa, xb, precisao=0.1): ''' Recebe como parâmetro uma função, um valores iniciais xa e xb e a precisão desejada. Precisão default é de 0.1 ''' anterior = xb xc = xa while abs(xc-anterior) > precisao: anterior = xc xc = (xa + xb) / 2.0 if funcao(xa) * funcao(xc) < 0.0: xb = xc elif funcao(xb) * funcao(xc) < 0.0: xa = xc return xc if __name__ == "__main__": def funcaoExponencial(x): ''' E^x + x/2 ''' return math.exp(x) + (x / 2.0) Dicotomia = MetodoDicotomia() RAIZ = Dicotomia.dicotomia(funcaoExponencial, -0.9, -0.8, precisao=0.000000001) print("Raiz igual a =", RAIZ) print("f(raiz) ==", funcaoExponencial(RAIZ)) def crazyFunction(x): return x - 3 - math.pow(x,-x) RAIZ = Dicotomia.dicotomia(crazyFunction, 2, 6, precisao=0.0000000000001) print("Raiz igual a =", RAIZ) print(crazyFunction(RAIZ))
952941dfeb140121c2c4823b36996e21a3fbf222
valentine909/PythonProBootcamp
/day11_blackjack.py
3,297
3.796875
4
from day11_art import logo CARDS = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] # Our Blackjack House Rules # The deck is unlimited in size. # There are no jokers. # The Jack/Queen/King all count as 10. Х # The the Ace can count as 11 or 1. # The cards in the list have equal probability of being drawn. # Cards are not removed from the deck as they are drawn. class Player: def __init__(self): self.hand = [] def deal_card(self): import random self.hand.append(random.choice(CARDS)) def show_cards(self): return self.hand def score(self): score = sum(self.hand) if score > 21 and 11 in self.hand: self.hand.remove(11) self.hand.append(1) return sum(self.hand) class Computer(Player): def show_cards(self, full=False): return self.hand if full else self.hand[0] class Blackjack: def __init__(self, AI=Computer(), Human=Player()): self.AI = AI self.AI.__init__() self.Human = Human self.Human.__init__() def check_lose_or_win(self, final=False): if final: if self.AI.score() > 21 or self.Human.score() > self.AI.score(): return self.win() elif self.Human.score() < self.AI.score(): return self.lose() else: return self.draw() if self.Human.score() > 21: return self.lose() elif self.Human.score() == 21 and self.AI.score() == 21: return self.draw() elif self.Human.score() == 21: return self.win() return False def start(self): print(logo) for _ in range(2): self.Human.deal_card() self.AI.deal_card() self.current_table() if self.check_lose_or_win(): return self.game() def win(self): self.final_table() print("You Win") return True def lose(self): self.final_table() print("You Lose") return True def draw(self): self.final_table() print("Draw") return True def current_table(self): print(f"Your cards: {self.Human.show_cards()}, current score: {self.Human.score()}") print(f"Computer's first card: {self.AI.show_cards()}") def final_table(self): print(f"Your final hand: {self.Human.show_cards()}, final score: {self.Human.score()}") print(f"Computer's final hand: {self.AI.show_cards(full=True)}, final score: {self.AI.score()}") def game(self): proceed = input("Type 'y' to get another card, type 'n' to pass: ") while proceed == 'y': self.Human.deal_card() if self.check_lose_or_win(): return self.current_table() proceed = input("Type 'y' to get another card, type 'n' to pass: ") while self.AI.score() < 17: self.AI.deal_card() self.check_lose_or_win(final=True) if __name__ == '__main__': iam_playing = input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") while iam_playing == 'y': game_session = Blackjack() game_session.start() iam_playing = input("Do you want to play more? Type 'y' or 'n': ")
74cb96b0dc36857ed8dc8d86bcaaa5d5789c2214
Djarahh/DataProcessing
/Homework/Week6/linked.py
723
3.53125
4
import pandas as pd # source of dataset: https://public.opendatasoft.com/explore/dataset/opioid-overdose-deaths-as-a-percent-of-all-drug-overdose-deaths/information/ INPUT_CSV = "share-of-adults-defined-as-obese.csv" OUTPUT_CSV = "output.csv" OUTPUT_JSON = "output.json" # Reading only Date, sex, age, from CSV df = pd.read_csv(INPUT_CSV, usecols=["Entity", "Code", "Year", "Obesity_Among_Adults"], na_values=['']) # Changing data to make it usable df["Obesity_Among_Adults"] = df["Obesity_Among_Adults"].astype("float64") # Put data into CSV file df.to_csv(OUTPUT_CSV) # Convert all data to JSON file df.to_json(OUTPUT_JSON, orient="index")
b3953ef859a5c54a9faefc416b05f3429fd6e372
sumitpkedia/Python
/DecoratorWrapperClass.py
823
3.515625
4
def decorator_function(original_function): #message = msg def wrapper_function(*args, **kwargs): print('INSIDE WRAPPER') return original_function(*args, **kwargs) #return inner_function() return wrapper_function @decorator_function def display(): print('PRINTING.......') @decorator_function def display_info(name, age): print('Display info {} {}'.format(name, age)) #decorated_display = decorator_function(display) #decorated_display() display() display_info('John', 25) class decorator_Class(object): def __init__(self, original_function): self.original_function = original_function def __call))(self, *args, **kwargs): print('Call method executed') return self.original_function(*args, **kwargs)
395bc59071212d69c3a10e0cecda2e9b91471e3a
skosantosh/python
/control_flow_forloop.py
813
4.15625
4
# if Statement if 1 < 2: print("First column") if 2 < 10: print("Second column") if 1 < 2: print("Hello") elif 3 == 3: print('elif ran') else: print("last") # For Loop """ nums = (1, 2, 3, 4, 5, 6) for num in nums: print(num) """ # for loop for Dictionary d = {'Sam': 1, "Frank": 2, "Dan": 3} for k in d: print(k) print(d[k]) # for loop in list mypairs = [(1, 2), (3, 4), (5, 6), (7, 8)] for item in mypairs: print(item) for (a, b) in mypairs: print(b) print(a) print(mypairs[0]) tupleeg = (1, 2, 3, 4) print(tupleeg) matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # list Comprehention first_col = [row[0] for row in matrix] second_col = [row[1] for row in matrix] third_col = [row[2] for row in matrix] print(first_col) print(second_col) print(third_col)
fcb303b5c2cef827ee71a9170bfb2f5ffda340dd
lberezy/COMP10001
/Project 3/lberezy.py
16,284
4.09375
4
''' Project 3 - COMP10001 Author: Lucas Berezy A Hearts card game 'AI' and score prediction. I've never played Hearts before this, and it's still a little confusing to me which means you get to laugh extra hard at some of the plays the AI may make. enjoy. ''' import itertools from random import choice, gauss from math import floor # construct some card set constants, might come in handy and set gymnastics is # fun. SUITS = set(['H', 'D', 'C', 'S']) # hearts, diamonds, clubs, spades NUMBERS = set([str(i) for i in range(2, 10)]).union(set(['0'])) ROYALS = set(['J', 'Q', 'K', 'A']) RANKS = NUMBERS.union(ROYALS) RANK_ORDER = \ ['2', '3', '4', '5', '6', '7', '8', '9', '0', 'J', 'Q', 'K', 'A'] ALL_CARDS = map(''.join, itertools.product(RANKS, SUITS)) def f_suit(suit): ''' returns an appropriate filter function based on the suit. For use in filter()., otherwise returns None ''' if suit in SUITS: return lambda card: card[1] == suit def cards_to_suit(cards, sort=True): ''' takes a list of cards, returns an optionally sorted dict of lists of each suit of cards (in rank order) ''' suits = {} # create dictionary with {suit: [cards]} for suit in SUITS: suits[suit] = [card for card in cards if f_suit(suit)(card)] if sort: card_sort(suits[suit]) return suits def card_sort(cards, rev=False): '''sorts a list of cards in rank order''' return sorted(cards, key=lambda x: RANK_ORDER.index(x[0]), reverse=rev) def have_suit(hand, suit): ''' checks to see if suit is in hand ''' if len([card[1] for card in hand if card[1] == suit]): return True return False def have_any_cards(cards, hand): ''' Returns true if any card in list of cards is in hand ''' assert isinstance(cards, list) for card in cards: if card in hand: return True return False def have_penalty(hand): ''' Returns true iff there is a Heart or QS in hand ''' if 'QS' in hand: return True if len(filter(f_suit('H', hand))): return True return False def is_penalty(card): ''' determines if a card is a penalty card ''' if card == 'QS' or card[1] == 'H': return True return False def card_gen(stop_card): ''' Just learnt what yield does, so here's a generator function to generate cards from the bottom of a suit up until a stop card. useful when generating runs of cards in a list: [card for card in card_gen(stop_card)] kinda messy though. ''' suit = stop_card[1] stop_rank = stop_card[0] if stop_rank not in RANKS or suit not in SUITS: # invalid end point return cards = map(''.join, itertools.product(RANKS, suit)) # generator source # can't use card_sort() as this isn't a list cards.sort(key=lambda x: RANK_ORDER.index(x[0])) # sorted (2..ace) count = 0 while True: card = cards[count] yield card count += 1 if card == (stop_card): break def pass_cards(hand): ''' Pases a 3, hopefully advantageous cards at the beginning of the round. Prioritises passing QKA of Spades, then the QS or 0D then if possible, voiding in a suit.''' def pick(card): ''' removes card from hand and places it in picked list ''' to_pass.append(hand.pop(hand.index(card))) to_pass = [] # 3 cards to pass high_diamonds = ['AD', 'KD', 'QD', 'JD'] keep_high_diamonds = False # Remove A,K,Q of Spades first for card in ['AS', 'KS', 'QS']: if card in filter(f_suit('S'), hand) and len(to_pass) < 3: pick(card) # it's hard to capture this card when in hand, so give away unless you # don't have a card to capture it with (A,K,Q,J of Diamonds) if '0D' in filter(f_suit('D'), hand) \ and have_any_cards(high_diamonds, hand) and (len(to_pass) < 3): pick('0D') # set a flag so we know not to give these away later keep_high_diamonds = True # sort remaining suits by size # dictionary of {suit: [cards]} suit_dict = cards_to_suit(hand) # form a list of suits in order of how many cards each contains sorted_suits = sorted(suit_dict.keys(), key=lambda x: len(suit_dict[x])) # attempt to go void, from shortest suit to longest suit for suit in sorted_suits: # dictionary of {suit: [cards]} # try and take highest cards first for card in card_sort(suit_dict[suit], rev=True): if len(to_pass) < 3: if keep_high_diamonds and card in high_diamonds: continue else: pick(card) else: return to_pass return to_pass def is_valid_play(played, hand, play, broken): ''' Determines if a given play is valid, based on current hand, played cards in current trick and if hearts are broken according to the rules in the spec. ''' if play not in hand: # no fun allowed return False if not play: # must play something return False # leading if played == []: # trying to lead penalty card when not broken and not forced to break if not broken and (play[1] == 'H' or play == 'QS') and \ (have_suit(hand, 'D') or have_suit(hand, 'D') or (filter(f_suit('S'), hand) != ['QS'])): return False return True # otherwise... lead_card = played[0] # not following suit when following is possible # if you are trying to play off suit, but can follow suit, don't allow it if have_suit(hand, lead_card[1]) and play[1] != lead_card[1]: return False # at this point, anything else is a valid move (I hope) return True def get_valid_plays(played, hand, broken, is_valid=is_valid_play): ''' returns a list of all valid plays that can be made from a hand given some play state variables. ''' output = [] for card in hand: if (is_valid(played, hand, card, broken)): output.append(card) return output def score_game(tricks_won): ''' scores each players list of tricks won and returns a tuple of players scores and a boolean regarding their winning status in a list, in order of the original ordering of lists in tricks_won. players may draw. ''' def shot_moon(): ''' returns a boolean True if the player has captured every penalty card including the QS. ''' # flatten list of lists tricks = list(itertools.chain.from_iterable(tricklist)) # have all the penalty cards? if len(filter(f_suit('H'), tricks)) == len(RANK_ORDER) \ and ('QS' in tricks): return True return False scores = [] # construct a list of final scores for each player for tricklist in tricks_won: score = 0 for trick in tricklist: score += score_trick(trick) # did the player 'shoot the moon' (score = 26 or 16 (from 0D))? # if so, make them win. # and the award for worst player goes to... if score == 16 and shot_moon(): # (shot moon + 0D == 16) # set the new score score = -36 # wew, magic numbers (-26 moon shoot + -10 for 0D) if score == 26 and shot_moon(): score *= -1 # turn that frown upside down! scores.append(score) # decorate the list so that each element is now a tuple of (score, Bool) # where Boolean True represents _a_ winning player (i.e. is equal to the # minumum score. (can be multiple winners) return [(score, (lambda x: x == min(scores))(score)) for score in scores] def score_trick(trick): ''' scores a trick based on the rules set out in the spec. Hearts: +1 point Q of S: +13 points 0 of D: -10 points ''' score = 0 score += len(filter(f_suit('H'), trick)) # number of hearts in trick score += 13 * ('QS' in trick) # Queen of Spades score += -10 * ('0D' in trick) # 10 of Diamonds return score def play(tricks_won, played, hand, broken, is_valid=is_valid_play, valid_plays=get_valid_plays, score=score_game): ''' plays a valid card in a round of hearts according, and quite badly. apologies for the large amount of return branching. ''' def get_round_no(): ''' returns the current round of play based on tricks won ''' return sum([len(tricklist) for tricklist in tricks_won]) def must_follow(): ''' returns a boolean status of the player being required to follow suit''' # if any lead_suit cards in valid_plays, then player must follow if not len(played): # no following if it's your lead return False lead_suit = played[0][1] # leading suit if len(filter(f_suit(lead_suit), get_valid_plays(played, hand, broken, is_valid))): return True return False def get_danger(): ''' returns a somewhat arbitrary danger level ''' past_cards = list(itertools.chain.from_iterable(tricks_won)) danger = 0 danger += (13 - len(filter(f_suit('H'), played))) # hearts remaining if 'QS' in played: danger += 5 if 'QS' in past_cards: danger -= 2 return danger # state-ish variables round_no = get_round_no() danger = get_danger() if len(played): lead_suit = played[0][1] # suit that is currently leading else: lead_suit = '' valid_plays = get_valid_plays(played, hand, broken, is_valid) # play 'logic' # if there is only one move, make it if len(valid_plays) == 1: return valid_plays[0] # return string not list # discard highest possible on opening if round_no == 0: try: # grab highest value valid card and get rid of it return card_sort(valid_plays, rev=True)[0] except: pass # if the 0D has been played, try to capture it if '0D' in played: # try each card in Diamonds above 0D, highest first # probably would be better to do: in ['JD','QD','KD','AD'] for card in [x for x in card_gen('AD')][:-5:-1]: if card in valid_plays: return card # return string, not list # if QS played, try not to win the trick if 'QS' in played: # panic! # if don't have to follow, discard a high card safely if not must_follow(): exclude = set(filter(f_suit(lead_suit), valid_plays)) to_play = [card for card in valid_plays if card not in exclude] return card_sort(to_play, rev=True)[0] # otherwise, try card in Spades < QS, highest to lowest for card in reversed([x for x in card_gen('JS')]): if card in valid_plays: return card # return string, not list if must_follow(): # if you must follow, play the smallest card if danger <= 1 or len(played) < 3: # note: this isn't always a good strategy return card_sort(valid_plays)[0] else: # play biggest return card_sort(valid_plays, rev=True)[0] # attempt to throw away an off-suit high card if safe to do so if not must_follow(): # grab highest value valid card and get rid of it exclude = set(filter(f_suit(lead_suit), valid_plays)) to_play = [card for card in valid_plays if card not in exclude] if len(to_play): return card_sort(to_play, rev=True)[0] # if it's a safe-ish suit or not too dangerous and near the end of the # trick, make a high play. if lead_suit in ['S', 'C', 'D'] and danger <= 4 or \ (len(filter(f_suit('H'), played)) == 0 and (len(played) >= 3)): return card_sort(valid_plays, rev=True)[0] # when dangerous, play smallest card if danger >= 4: return card_sort(valid_plays)[0] # 0/10 move # if all else fails, return random valid card # BELIEVE IN THE HEART OF THE CARDS! return choice(valid_plays) def predict_score(hand): ''' takes a playing hand at the start of the game (after passing) and attempts to predict the final score based on this information alone via the (poor) construction of a Gaussian distribution. Ideally it would be nice to gather some statistical data on how this 'player' (among others) scores based on different hands, then map the likeness of a given hand onto this distribution. It would be wrong to cause excessive load scraping the online test playground however. Assumptions: If holding QS, then median score is likely to be higher. The closer the player is to holding a full-hand of hearts (idk, but it sounds like a dangerous position to be in), the higher the score. Score is also likely to be higher if player holds 0D and no higher diamonds to capture with. If the player does have higher diamonds, the median score will be shifted toward 0 by the number of these cards. Score is likely to be toward 0 if starting with a hand that is void in 1 or more suits as it offers more opportunity for safe disposals. If the average card in the hand has a low rank, then the score is likely to be lower.''' def clamp(score, s_min=-10, s_max=26): if score >= s_max: # max score return s_max elif score <= s_min: return s_min else: return score # warning: the following section is filled with made up pseudo-statistical # numbers. I really wish they were magic in the 'helpful wizard' sense # of the word, but they're more of the 'uh...sure...okay' kind. Sorry. # Stand back, I'm going to try STATISTICS! # ... and by statistics I mean fiddling with parameters arbitrarily. # some (un)educated guesses at possible initial score distributions mu = 4 # mean initial score sigma = 2.5 # standard deviation in score hearts_count = len(filter(f_suit('H'), hand)) mu += 0.4 * hearts_count / len(hand) sigma += hearts_count / 2 # compute average card rank of hand hand_score = 0 for card in hand: if card[0] in ROYALS: hand_score += 12 mu += 1 # kind does something else: hand_score += int(card[0]) hand_score = float(hand_score) / len(hand) # average # adjust mu accordingly mu += (hand_score - 10) # yep, another made up number # consider void suits void_suits = 0 for suit in SUITS: if (len(filter(f_suit(suit), hand)) == 0): void_suits += 1 mu -= void_suits * 3 # more likely to have a score closer to zero # consider Queen of Spades if 'QS' in hand: mu += (13 - mu) # a guess at what the mean score might be closer to sigma -= 0.5 # more likely to occur # consider 10 of Diamonds, others are likely to win a trick here # on second thought, this kind of doesn't make sense if '0D' in hand: higher_diamonds = len([x for x in filter(f_suit('D'), hand) if x in ['JD', 'QD', 'KD', 'AD']]) mu -= 2 * (0.4 * higher_diamonds) # makes it more unlikely to capture sigma += 0.8 prediction = int(floor(gauss(mu, sigma))) # compute integer score prediction = clamp(prediction) # clamp to [-10..26] range if prediction in [26, 16]: # may have possibly shot the moon if prediction == 16: if choice([0, 0, 1]): # 1/3 chance of moon shoot return -36 else: return 16 else: return -26 else: return int(prediction)